<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Angrybirds;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
		    // if we're in a namespace deeper than one level we need to fix the \ in the path
                    __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    /*public function onBootstrap($e)
    {
        // You may not need to do this if you're doing it elsewhere in your
        // application
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }*/
}

<?php

/* DEVELOPMENT BRANCH */

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Angrybirds;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
		    // if we're in a namespace deeper than one level we need to fix the \ in the path
                    __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    /*public function onBootstrap($e)
    {
        // You may not need to do this if you're doing it elsewhere in your
        // application
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }*/
}

Test changes in develop branch

Test changes in develop branch


<?php
require_once('MotionX.php');

/**
 * Parse KML
 */
class Parser {

    private $sourceFile;
    private $xml;

    public function __construct($sourceFile) {
        $this->setSourceFile($sourceFile);
    }

    public function setSourceFile($sourceFile) {
        $this->sourceFile = $sourceFile;
    }

    private function getXml() {
        if (!$this->xml) {
            $this->setXml();
        }
        return $this->xml;
    }

    private function setXml() {
        $this->xml = simplexml_load_string($this->readFromKmz());
    }

    private function readFromKmz() {
        $contents = null;
        $zip = new ZipArchive;
        if ($zip->open($this->sourceFile) === TRUE) {
            $contents = $zip->getFromIndex(0);
            $zip->close();
        }
        return $contents;
    }

    public function getRide() {
        $ride = new MotionX($this->getXml());
        return $ride->toArray();
    }
}

<?php
require_once('MotionX.php');

/**
 * Parse KML
 */
class Parser {

    private $sourceFile;
    private $xml;

    public function __construct($sourceFile) {
        $this->setSourceFile($sourceFile);
    }

    public function setSourceFile($sourceFile) {
        $this->sourceFile = $sourceFile;
    }

    private function getXml() {
        if (!$this->xml) {
            $this->setXml();
        }
        return $this->xml;
    }

    private function setXml() {
        $this->xml = simplexml_load_string($this->readFromKmz());
    }

    private function readFromKmz() {
        $contents = null;
        $zip = new ZipArchive;
        if ($zip->open($this->sourceFile) === TRUE) {
            $contents = $zip->getFromIndex(0);
            $zip->close();
        }
        return $contents;
    }

    public function geoFence($top, $right, $bottom, $left) {
        $xml = $this->getXml();
        $xml->registerXPathNamespace('kml', 'http://earth.google.com/kml/2.2');
        $coordinates = (string) $xml->xpath('//kml:coordinates')[2];

        foreach(preg_split("/((\r?\n)|(\r\n?))/", $coordinates) as $line){
            if (!empty($line)) {
                list($long, $lat, $alt) = explode(',', $line);

                settype($long, "float");
                settype($lat, "float");
                settype($alt, "float");

                if ($long < $right && $long > $left
                    && $lat < $top && $lat > $bottom) {
                    echo "In range: {$line}" . PHP_EOL;
                }
            }
        }
    }

    public function getRide() {
        $ride = new MotionX($this->getXml());
        return $ride->toArray();
    }
}

Add rough and ready geo-fence method

Add rough and ready geo-fence method


<?php

namespace Acme\Bundle\DemoFlexibleEntityBundle\Tests\Functional\Controller;

/**
 * Test related class
 *
 * @author    Romain Monceau <romain@akeneo.com>
 * @copyright 2012 Akeneo SAS (http://www.akeneo.com)
 * @license   http://opensource.org/licenses/MIT MIT
 *
 */
class FlexibleControllerTest extends KernelAwareControllerTest
{

    /**
     * Define flexible controller name for url generation
     * @staticvar string
     */
    protected static $controller = 'flexible';

    /**
     * Test related method
     */
    public function testIndexAction()
    {
        foreach (self::$locales as $locale) {
            $this->client->request(
                'GET',
                self::prepareUrl($locale, 'index')
            );
            $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        }
    }

    /**
     * Test related method
     */
    public function testEntityConfigAction()
    {
        foreach (self::$locales as $locale) {
            $this->client->request(
                'GET',
                self::prepareUrl($locale, 'config')
            );
            $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        }
    }
}

<?php

namespace Acme\Bundle\DemoFlexibleEntityBundle\Tests\Functional\Controller;

/**
 * Test related class
 *
 * @author    Romain Monceau <romain@akeneo.com>
 * @copyright 2012 Akeneo SAS (http://www.akeneo.com)
 * @license   http://opensource.org/licenses/MIT MIT
 *
 */
class FlexibleControllerTest extends KernelAwareControllerTest
{

    /**
     * Define flexible controller name for url generation
     * @staticvar string
     */
    protected static $controller = 'flexible';

    /**
     * Test related method
     */
    public function testIndexAction()
    {
        foreach (self::$locales as $locale) {
            $this->client->request(
                'GET',
                self::prepareUrl($locale, 'index')
            );
            $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        }
    }

    /**
     * Test related method
     */
//    public function testEntityConfigAction()
//    {
//        foreach (self::$locales as $locale) {
//            $this->client->request(
//                'GET',
//                self::prepareUrl($locale, 'config')
//            );
//            $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
//        }
//    }
}

BAP-738: Rename buttons "Add new" to "Add {entity_name}"


<?php  //$Id$

/// This file defines the current version of the
/// backup/restore code that is being used.  This can be
/// compared against the values stored in the
/// database (backup_version) to determine whether upgrades should
/// be performed (see db/backup_*.php)

    $backup_version = 2007090500;   // The current version is a date (YYYYMMDDXX)
    $backup_release = '1.9 beta +';     // User-friendly version number

?>

<?php  //$Id$

/// This file defines the current version of the
/// backup/restore code that is being used.  This can be
/// compared against the values stored in the
/// database (backup_version) to determine whether upgrades should
/// be performed (see db/backup_*.php)

    $backup_version = 2007101000;   // The current version is a date (YYYYMMDDXX)
    $backup_release = '1.9 beta 2';     // User-friendly version number

?>

Bump to beta 2 (real branch)

Bump to beta 2 (real branch)


<?php
class Kwc_List_ChildPages_Teaser_Generator extends Kwf_Component_Generator_Table
{
    protected $_hasNumericIds = false;
    protected $_idColumn = 'child_id';
    protected $_useComponentId = true;

    protected function _formatConfig($parentData, $row)
    {
        $ret = parent::_formatConfig($parentData, $row);
        $ret['targetPage'] = Kwf_Component_Data_Root::getInstance()
            ->getComponentByDbId($row->target_page_id, array('subroot'=>$parentData, 'limit'=>1));

        if (!$ret['targetPage']) return null; //can happen if page was deleted but entry still exists

        return $ret;
    }

    public function getDuplicateProgressSteps($source)
    {
        return 0;
    }

    public function duplicateChild($source, $parentTarget, Zend_ProgressBar $progressBar = null)
    {
        //don't duplicate children of this generator *here* because we don't know the new child ids yet
        //as they depend on the new pages (that might not yet exist at this point)
        return null;
    }
}

<?php
class Kwc_List_ChildPages_Teaser_Generator extends Kwf_Component_Generator_Table
{
    protected $_hasNumericIds = false;
    protected $_idColumn = 'child_id';
    protected $_useComponentId = true;

    protected function _formatConfig($parentData, $row)
    {
        $ret = parent::_formatConfig($parentData, $row);
        $ret['targetPage'] = Kwf_Component_Data_Root::getInstance()
            ->getComponentByDbId($row->target_page_id, array('subroot'=>$parentData, 'limit'=>1, 'ignoreVisible'=>true));

        if (!$ret['targetPage']) return null; //can happen if page was deleted but entry still exists

        return $ret;
    }

    public function getDuplicateProgressSteps($source)
    {
        return 0;
    }

    public function duplicateChild($source, $parentTarget, Zend_ProgressBar $progressBar = null)
    {
        //don't duplicate children of this generator *here* because we don't know the new child ids yet
        //as they depend on the new pages (that might not yet exist at this point)
        return null;
    }
}

Fix ChildPages_Teaser for invisible page


<?php

namespace Neves\Events;

use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;

class EventServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../../config/transactional-events.php',
            'transactional-events'
        );

        if (! $this->app['config']->get('transactional-events.enable')) {
            return;
        }

        $connectionResolver = $this->app->make('db');
        $eventDispatcher = $this->app->make(EventDispatcher::class);
        $this->app->extend('events', function () use ($connectionResolver, $eventDispatcher) {
            $dispatcher = new TransactionalDispatcher($connectionResolver, $eventDispatcher);
            $dispatcher->setTransactionalEvents($this->app['config']->get('transactional-events.transactional'));
            $dispatcher->setExcludedEvents($this->app['config']->get('transactional-events.excluded'));

            return $dispatcher;
        });
    }

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../../config/transactional-events.php' => config_path('transactional-events.php'),
        ]);
    }
}

<?php

namespace Neves\Events;

use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;

class EventServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../../config/transactional-events.php',
            'transactional-events'
        );

        if (! $this->app['config']->get('transactional-events.enable')) {
            return;
        }

        $connectionResolver = $this->app->make('db');
        $eventDispatcher = $this->app->make(EventDispatcher::class);
        $this->app->extend('events', function () use ($connectionResolver, $eventDispatcher) {
            $dispatcher = new TransactionalDispatcher($connectionResolver, $eventDispatcher);
            $dispatcher->setTransactionalEvents($this->app['config']->get('transactional-events.transactional'));
            $dispatcher->setExcludedEvents($this->app['config']->get('transactional-events.excluded'));

            return $dispatcher;
        });
    }

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $configPath = app()->basePath() . '/config';

        $this->publishes([
            __DIR__.'/../../config/transactional-events.php' => $configPath.'/transactional-events.php',
        ]);
    }
}

Replace config() helper for Lumen

Replace config() helper for Lumen


<?php

require_once('config.php');
global $config;

$userid = session_get_user_id();
$stmt = $pdo->prepare("SELECT `election` FROM `access` WHERE `user`= ?");
$stmt->bindParam(1, $userid);
$stmt->execute();
$elections = $stmt->fetchAll();

?>

ELECTIONS

        <?php foreach ($elections as $row) {
        	$stmt = $pdo->prepare("SELECT `name` FROM `elections` WHERE `id`= ?");
        	$stmt->bindParam(1, $row["election"]);
        	$stmt->execute();

        	$election_name = $stmt->fetch(PDO::FETCH_NUM)[0];
        	?>
        	<li <?php if($_GET['id'] == $row['election']) { ?>class="active"<?php } ?>><a href="/election?id=<?php echo $row["election"]; ?>"> <?php echo $election_name; ?>

        	<?php
        } ?>
        <li <?php if($_GET['id'] == "new") { ?>class="active"<?php } ?>> New Election...

<?php

require_once('config.php');
global $config;

$userid = session_get_user_id();
$stmt = $pdo->prepare("SELECT `election` FROM `access` WHERE `user`= ?");
$stmt->bindParam(1, $userid);
$stmt->execute();
$elections = $stmt->fetchAll();

?>

ELECTIONS

        <?php foreach ($elections as $row) {
        	$stmt = $pdo->prepare("SELECT `name` FROM `elections` WHERE `id`= ?");
        	$stmt->bindParam(1, $row["election"]);
        	$stmt->execute();

        	$election_name = $stmt->fetch(PDO::FETCH_NUM)[0];
        	?>
        	<li <?php if($_GET['id'] == $row['election']) { ?>class="active"<?php } ?>><a href="/election?id=<?php echo $row["election"]; ?>&subid=dashboard"> <?php echo $election_name; ?>

        	<?php
        } ?>
        <li <?php if($_GET['id'] == "new") { ?>class="active"<?php } ?>> New Election...

Make main link go to dashboard for election


<?php
namespace Phortress;

/**
 * The global environment for a program.
 *
 * @package Phortress
 */
class GlobalEnvironment extends NamespaceEnvironment {
	/**
	 * The superglobals for this environment.
	 *
	 * @var array
	 */
	private $superglobals;

	public function __construct() {
		parent::__construct('Global', null);

		$this->superglobals = array(
			'GLOBALS' => &$this->variables,
			'_SERVER' => array(),
			'_GET' => array(),
			'_POST' => array(),
			'_FILES' => array(),
			'_COOKIE' => array(),
			'_SESSION' => array(),
			'_REQUEST' => array(),
			'_ENV' => array()
		);

		self::copyValueReferences($this->variables, $this->superglobals);
	}

	public function getGlobal() {
		return $this;
	}

	/**
	 * Gets the superglobals in this global environment.
	 *
	 * @return array
	 */
	public function &getSuperglobals() {
		return $this->superglobals;
	}
}

<?php
namespace Phortress;
use PhpParser\Node\Name;
use PhpParser\Node\Name\Relative;

/**
 * The global environment for a program.
 *
 * @package Phortress
 */
class GlobalEnvironment extends NamespaceEnvironment {
	/**
	 * The superglobals for this environment.
	 *
	 * @var array
	 */
	private $superglobals;

	public function __construct() {
		parent::__construct('Global', null);

		$this->superglobals = array(
			'GLOBALS' => &$this->variables,
			'_SERVER' => array(),
			'_GET' => array(),
			'_POST' => array(),
			'_FILES' => array(),
			'_COOKIE' => array(),
			'_SESSION' => array(),
			'_REQUEST' => array(),
			'_ENV' => array()
		);

		self::copyValueReferences($this->variables, $this->superglobals);
	}

	/**
	 * Gets the superglobals in this global environment.
	 *
	 * @return array
	 */
	public function &getSuperglobals() {
		return $this->superglobals;
	}

	public function getGlobal() {
		return $this;
	}

	public function resolveNamespace(Name $namespaceName = null) {
		if (self::isAbsolutelyQualified($namespaceName)) {
			$namespaceName = new Relative(
				$namespaceName->parts,
				$namespaceName->getAttributes());
		}

		return parent::resolveNamespace($namespaceName);
	}
}

Implement absolutely qualified namespace resolution.


Hey {{ $user->username }}!

{{ $blueprint->sender->username }} replied to your post (#{{ $blueprint->post->number }}) in {{ $blueprint->post->discussion->title }}.

{{ \Flarum\Core::config('base_url') }}/d/{{ $blueprint->reply->discussion_id }}/-/{{ $blueprint->reply->number }}

---

{{ strip_tags($blueprint->post->contentHtml) }}

Hey {{ $user->username }}!

{{ $blueprint->reply->user->username }} replied to your post (#{{ $blueprint->post->number }}) in {{ $blueprint->post->discussion->title }}.

{{ \Flarum\Core::config('base_url') }}/d/{{ $blueprint->reply->discussion_id }}/-/{{ $blueprint->reply->number }}

---

{{ strip_tags($blueprint->post->contentHtml) }}

Fix error in post mention emails

Fix error in post mention emails


<?php
// MySQL Parameters
define("MYSQL_USER", "root");
define("MYSQL_PASSWORD", "");
define("MYSQL_HOST", "localhost");

// Show Options
define("SHOW_CONFIG", true);
define("SHOW_PARAMETERS", true);

// Main projects Directory
define("WWW_DIR", "../");

// Ignored projects to not sync
define("IGNORED_PROJECTS", 'n-a,.,..,index,css,.git,js,img,damp');

?>

<?php
// MySQL Parameters
define("MYSQL_USER", "root");
define("MYSQL_PASSWORD", "");
define("MYSQL_HOST", "localhost");

// Show Options
define("SHOW_CONFIG", true);
define("SHOW_PARAMETERS", true);

// Main projects Directory
define("WWW_DIR", "../");

// Ignored projects to not sync
define("IGNORED_PROJECTS", 'n-a,.,..,index,css,.git,js,img,damp');

define('WAMP_PATH', realpath('C:/wamp64').'\\');
define('CUSTOM_VHOST_PATH_CONFIG', "C:/wamp64/bin/apache/apache*/conf/extra/httpd-vhosts.conf");

?>

Add WAMP PATH and VHOST PATH (Defaut WAMP 64 v3, mostly used)


<?php

namespace ChopBox\Http\Controllers;

use ChopBox\helpers\PostChop;
use ChopBox\Http\Requests\ChopsFormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input as Input;

class ChopsController extends Controller
{
    /**
     * Store posted chops
     *
     * @param  Request $request
     *
     * @return Response Redirect to homepage view
     */
    public function store(ChopsFormRequest $request, PostChop $post)
    {
        $user = Auth::user();
        $images = Input::file('image');

		$chopsId = $post->saveChops($user, $request);

        if (! is_null($images[0])) {
            $shortened_url = $post->uploadImages($images);
            $post->saveUploads($user, $images, $shortened_url, $chopsId);
        }

        return redirect()->action('HomeController@index');
    }
}

<?php

namespace ChopBox\Http\Controllers;

use ChopBox\helpers\PostChop;
use Illuminate\Support\Facades\Auth;
use ChopBox\Http\Requests\ChopsFormRequest;
use Illuminate\Support\Facades\Input as Input;

class ChopsController extends Controller
{
    /**
     * Store posted chops
     *
     * @param  Request $request
     *
     * @return Response Redirect to homepage view
     */
    public function store(ChopsFormRequest $request, PostChop $post)
    {
        $user = Auth::user();
        $images = Input::file('image');

		$chopsId = $post->saveChops($user, $request);

        if (! is_null($images[0])) {
            $shortened_url = $post->uploadImages($images);
            $post->saveUploads($user, $images, $shortened_url, $chopsId);
        }

        return redirect()->action('HomeController@index');
    }
}

[ChopBox] Fix indentation and arrange imports from shortest tolongest


<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Image;

class ImageController extends Controller
{
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $image = Image::find($id);
        $data = [
            'image' => $image,
            'texts' => $image->texts
         ];
        return view('image', $data);
    }
    /**
    * Manage Post Request
    *
    * @return void
    */
    public function postImage(Request $request)
    {
        $this->validate($request, [
            'image_file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:1024',
        ]);
        $imageName = time().'.'.$request->image_file->getClientOriginalExtension();
        $request->image_file->move(public_path('images'), $imageName);

        $image = new Image;
        $image->parent_id = $request->parent_id;
        $image->file = $imageName;
        $image->save();

        return back()
            ->with('success','You have successfully upload images.')
            ->with('image',$imageName);
    }
}

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Image;

class ImageController extends Controller
{
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $image = Image::find($id);
        $data = [
            'image' => $image,
            'texts' => $image->texts
         ];
        return view('image', $data);
    }
    /**
    * Manage Post Request
    *
    * @return void
    */
    public function postImage(Request $request)
    {
        $this->validate($request, [
            'image_file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
        ]);
        $imageName = time().'.'.$request->image_file->getClientOriginalExtension();
        $request->image_file->move(public_path('images'), $imageName);

        $image = new Image;
        $image->parent_id = $request->parent_id;
        $image->file = $imageName;
        $image->save();

        return back()
            ->with('success','You have successfully upload images.')
            ->with('image',$imageName);
    }
}

Change max filesize for uploaded images

Change max filesize for uploaded images


<?php
namespace RbComment\Mvc\Controller\Plugin;

use Zend\Mail\Message;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class Mailer extends AbstractPlugin
{
    private $serverUrlHelper;
    private $mailerService;
    private $configService;

    public function __construct(
        $serverUrlHelper,
        $mailerService,
        array $configService
    ) {
        $this->serverUrlHelper = $serverUrlHelper;
        $this->mailerService   = $mailerService;
        $this->configService   = $configService;
    }

    public function __invoke($comment)
    {
        $mailerConfig = $this->configService['rb_comment']['email'];

        $htmlContent = $comment->content;
        $htmlContent .= '

';
        $htmlContent .= 'serverUrlHelper() . $comment->uri . '#rbcomment-' . $comment->id . '">' .
                        $mailerConfig['context_link_text'] .
                        '';

        $html = new MimePart($htmlContent);
        $html->type = "text/html";

        $body = new MimeMessage();
        $body->setParts([$html]);

        $message = new Message();
        $message->addFrom($mailerConfig['from'])
                ->setSubject($mailerConfig['subject'])
                ->setBody($body);

        foreach ($mailerConfig['to'] as $mConfig) {
            $message->addTo($mConfig);
        }

        $this->mailerService->send($message);
    }
}

<?php
namespace RbComment\Mvc\Controller\Plugin;

use Zend\Mail\Message;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class Mailer extends AbstractPlugin
{
    private $serverUrlHelper;
    private $mailerService;
    private $configService;

    public function __construct(
        $serverUrlHelper,
        $mailerService,
        array $configService
    ) {
        $this->serverUrlHelper = $serverUrlHelper;
        $this->mailerService   = $mailerService;
        $this->configService   = $configService;
    }

    public function __invoke($comment)
    {
        $mailerConfig = $this->configService['rb_comment']['email'];

        $htmlContent = $comment->content;
        $htmlContent .= '

';
        $htmlContent .= 'serverUrlHelper->__invoke() . $comment->uri . '#rbcomment-' . $comment->id . '">' .
                        $mailerConfig['context_link_text'] .
                        '';

        $html = new MimePart($htmlContent);
        $html->type = "text/html";

        $body = new MimeMessage();
        $body->setParts([$html]);

        $message = new Message();
        $message->addFrom($mailerConfig['from'])
                ->setSubject($mailerConfig['subject'])
                ->setBody($body);

        foreach ($mailerConfig['to'] as $mConfig) {
            $message->addTo($mConfig);
        }

        $this->mailerService->send($message);
    }
}

Fix serverUrl invokable call in the mailer plugin


<?php

namespace HiPay\Wallet\Mirakl\Cashout\Model\Operation;

use HiPay\Wallet\Mirakl\Common\AbstractEnumeration;

/**
 * Status class
 * Represent the status of an operation.
 *
 * @author    Ivanis Kouamé <ivanis.kouame@smile.fr>
 * @copyright 2015 Smile
 */
class Status extends AbstractEnumeration
{
    //Initial status of the operation
    const CREATED = 1;

    //Transfer status
    const TRANSFER_SUCCESS = 3;
    const TRANSFER_FAILED = -9;

    //Withdraw statuses
    const WITHDRAW_REQUESTED = 5;
    const WITHDRAW_SUCCESS = 6;
    const WITHDRAW_FAILED = -7;
    const WITHDRAW_CANCELED = -8;
}

<?php

namespace HiPay\Wallet\Mirakl\Cashout\Model\Operation;

use HiPay\Wallet\Mirakl\Common\AbstractEnumeration;

/**
 * Status class
 * Represent the status of an operation.
 *
 * @author    Ivanis Kouamé <ivanis.kouame@smile.fr>
 * @copyright 2015 Smile
 *
 * @method int getValue()
 */
class Status extends AbstractEnumeration
{
    //Initial status of the operation
    const CREATED = 1;

    //Transfer status
    const TRANSFER_SUCCESS = 3;
    const TRANSFER_FAILED = -9;

    //Withdraw statuses
    const WITHDRAW_REQUESTED = 5;
    const WITHDRAW_SUCCESS = 6;
    const WITHDRAW_FAILED = -7;
    const WITHDRAW_CANCELED = -8;
}

Add documentation about the getValue method


<?php
namespace Goetas\Twital\Node;

use Goetas\Twital\Node;
use Goetas\Twital\Exception;
use Goetas\Twital\Compiler;
use Goetas\Twital\Helper\DOMHelper;

/**
 *
 * @author Asmir Mustafic <goetas@gmail.com>
 *
 */
class ExtendsNode implements Node
{
    public function visit(\DOMElement $node, Compiler $context)
    {
        if ($node->hasAttribute("from-exp")) {
            $filename = $node->getAttribute("from-exp");
        } elseif ($node->hasAttribute("from")) {
            $filename = '"' . $node->getAttribute("from") . '"';
        } else {
            throw new Exception("The 'from' or 'from-exp' attribute is required");
        }

        // remove any non-element node
        foreach (iterator_to_array($node->childNodes) as $child) {
            if (!($child instanceof \DOMElement)) {
                $child->parentNode->removeChild($child);
            }
        }

        $context->compileChilds($node);

        $ext = $context->createControlNode("extends {$filename}");

        $set = iterator_to_array($node->childNodes);
        if (count($set)) {
            $n = $node->ownerDocument->createTextNode("\n");
            array_unshift($set, $n);
        }
        array_unshift($set, $ext);

        DOMHelper::replaceWithSet($node, $set);

    }
}

<?php
namespace Goetas\Twital\Node;

use Goetas\Twital\Node;
use Goetas\Twital\Exception;
use Goetas\Twital\Compiler;
use Goetas\Twital\Helper\DOMHelper;

/**
 *
 * @author Asmir Mustafic <goetas@gmail.com>
 *
 */
class ExtendsNode implements Node
{
    public function visit(\DOMElement $node, Compiler $context)
    {
        if ($node->hasAttribute("from-exp")) {
            $filename = $node->getAttribute("from-exp");
        } elseif ($node->hasAttribute("from")) {
            $filename = '"' . $node->getAttribute("from") . '"';
        } else {
            throw new Exception("The 'from' or 'from-exp' attribute is required");
        }

        $context->compileChilds($node);

        $ext = $context->createControlNode("extends {$filename}");

        $set = iterator_to_array($node->childNodes);
        if (count($set)) {
            $n = $node->ownerDocument->createTextNode("\n");
            array_unshift($set, $n);
        }
        array_unshift($set, $ext);

        DOMHelper::replaceWithSet($node, $set);
    }
}

Allow to have text nodes when using t:extends. They can be twig nodes


<?php

use Illuminate\Foundation\AliasLoader;

class FoundationAliasLoaderTest extends PHPUnit_Framework_TestCase
{
    public function testLoaderCanBeCreatedAndRegisteredOnce()
    {
        $loader = AliasLoader::getInstance(['foo' => 'bar']);

        $this->assertEquals(['foo' => 'bar'], $loader->getAliases());
        $this->assertFalse($loader->isRegistered());
        $loader->register();

        $this->assertTrue($loader->isRegistered());
    }

    public function testGetInstanceCreatesOneInstance()
    {
        $loader = AliasLoader::getInstance(['foo' => 'bar']);
        $this->assertEquals($loader, AliasLoader::getInstance());
    }
}

<?php

use Illuminate\Foundation\AliasLoader;

class FoundationAliasLoaderTest extends PHPUnit_Framework_TestCase
{
    public function testLoaderCanBeCreatedAndRegisteredOnce()
    {
        $loader = AliasLoader::getInstance(['foo' => 'bar']);

        $this->assertEquals(['foo' => 'bar'], $loader->getAliases());
        $this->assertFalse($loader->isRegistered());
        $loader->register();

        $this->assertTrue($loader->isRegistered());
    }

    public function testGetInstanceCreatesOneInstance()
    {
        $loader = AliasLoader::getInstance(['foo' => 'bar']);
        $this->assertSame($loader, AliasLoader::getInstance());
    }
}

Check Loader instance identity, not equality


<?php
class Kwf_Owlcarousel_Kwc_Carousel_Component extends Kwc_Abstract_List_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['componentName'] = trlKwfStatic('List Carousel');
        $ret['generators']['child']['component'] = 'Kwf_Owlcarousel_Kwc_Carousel_Image_Component';

        $ret['carouselConfig'] = array(
            'loop' => true,
            'center' => true,
            'items' => 2,
            'nav' => true,
            'dots' => false,
            'margin' => 10,
            'smartSpeed' => 1500,
            'touchSmartSpeed' => 600,
            'startRandom' => false,
            'autoplay' => false,
            'autoplayTimeout' => 7000
        );

        $ret['assetsDefer']['dep'][] = 'owlcarousel';
        return $ret;
    }

    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $ret['config'] = array(
            'carouselConfig' => $this->_getSetting('carouselConfig'),
            'countItems' => count($ret['listItems']),
            'contentWidth' => $this->getContentWidth()
        );
        return $ret;
    }
}

<?php
class Kwf_Owlcarousel_Kwc_Carousel_Component extends Kwc_Abstract_List_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['componentName'] = trlKwfStatic('List Carousel');
        $ret['generators']['child']['component'] = 'Kwf_Owlcarousel_Kwc_Carousel_Image_Component';

        $ret['carouselConfig'] = array(
            'loop' => true,
            'center' => true,
            'items' => 2,
            'nav' => true,
            'dots' => false,
            'margin' => 10,
            'smartSpeed' => 1500,
            'touchSmartSpeed' => 600,
            'startRandom' => false,
            'autoplay' => false,
            'autoplayTimeout' => 7000,
            'responsiveRefreshRate' => 90
        );

        $ret['assetsDefer']['dep'][] = 'owlcarousel';
        return $ret;
    }

    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $ret['config'] = array(
            'carouselConfig' => $this->_getSetting('carouselConfig'),
            'countItems' => count($ret['listItems']),
            'contentWidth' => $this->getContentWidth()
        );
        return $ret;
    }
}

Adjust setting responsiveRefreshRate to trigger resize before elementWidthChange


<?php

namespace Statamic\Addons\Sitemap;

use Illuminate\Routing\Route;
use Illuminate\Routing\RouteCollection;
use Statamic\Extend\ServiceProvider;

class SitemapServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    public $defer = true;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $old_routes = app('router')->getRoutes();
        $new_routes = new RouteCollection();

        foreach ($old_routes as $i => $route) {
            if ($route->getUri() == "{segments?}") {
                $sitemap_route = new Route(['GET'], 'sitemap.xml', ['uses' => '\Statamic\Addons\Sitemap\SitemapController@index']);

                $new_routes->add($sitemap_route);
            }

            $new_routes->add($route);
        }

        app('router')->setRoutes($new_routes);
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

<?php

namespace Statamic\Addons\Sitemap;

use Illuminate\Routing\Route;
use Illuminate\Routing\RouteCollection;
use Statamic\Extend\ServiceProvider;

class SitemapServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    public $defer = true;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        // Here we get all the current routes, then add our sitemap route right before the catch-all segment route
        $old_routes = app('router')->getRoutes();
        $new_routes = new RouteCollection();

        foreach ($old_routes as $i => $route) {
            if ($route->getUri() == "{segments?}") {
                $sitemap_route = new Route(['GET'], 'sitemap.xml', ['uses' => '\Statamic\Addons\Sitemap\SitemapController@index']);

                $new_routes->add($sitemap_route);
            }

            $new_routes->add($route);
        }

        app('router')->setRoutes($new_routes);
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Add comment to service provider

Add comment to service provider


<?php
/**
 * The template for displaying the footer
 *
 * Contains the closing of the "off-canvas-wrap" div and all content after.
 *
 * @package WordPress
 * @subpackage FoundationPress
 * @since FoundationPress 1.0.0
 */

?>

		</section>
		<div id="footer-container">
			<footer id="footer">
				<?php do_action( 'foundationpress_before_footer' ); ?>
				<?php dynamic_sidebar( 'footer-widgets' ); ?>
				<?php do_action( 'foundationpress_after_footer' ); ?>
			</footer>
		</div>

		<?php do_action( 'foundationpress_layout_end' ); ?>
	<?php if ( ! get_theme_mod( 'wpt_mobile_menu_layout' ) || get_theme_mod( 'wpt_mobile_menu_layout' ) == 'offcanvas' ) : ?>
		</div><!-- Close off-canvas wrapper inner -->
	</div><!-- Close off-canvas wrapper -->

	<?php if ( ! get_theme_mod( 'wpt_mobile_menu_layout' ) || get_theme_mod( 'wpt_mobile_menu_layout' ) == 'offcanvas' ) : ?>
	<!-- Close off-canvas content wrapper -->
	</div>
	<?php endif; ?>

	<?php endif; ?>

<?php wp_footer(); ?>
<?php do_action( 'foundationpress_before_closing_body' ); ?>
</body>
</html>

<?php
/**
 * The template for displaying the footer
 *
 * Contains the closing of the "off-canvas-wrap" div and all content after.
 *
 * @package WordPress
 * @subpackage FoundationPress
 * @since FoundationPress 1.0.0
 */

?>

		</section>
		<div id="footer-container">
			<footer id="footer">
				<?php do_action( 'foundationpress_before_footer' ); ?>
				<?php dynamic_sidebar( 'footer-widgets' ); ?>
				<?php do_action( 'foundationpress_after_footer' ); ?>
			</footer>
		</div>

		<?php do_action( 'foundationpress_layout_end' ); ?>

<?php if ( get_theme_mod( 'wpt_mobile_menu_layout' ) == 'offcanvas' ) : ?>
		</div><!-- Close off-canvas wrapper inner -->
	</div><!-- Close off-canvas wrapper -->
</div><!-- Close off-canvas content wrapper -->
<?php endif; ?>

<?php wp_footer(); ?>
<?php do_action( 'foundationpress_before_closing_body' ); ?>
</body>
</html>

Adjust conditional for offcanvas closing divs


<?php namespace Jayked\Laravelfilemanager\controllers;

use Jayked\Laravelfilemanager\controllers\Controller;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;

/**
 * Class DownloadController
 * @package Jayked\Laravelfilemanager\controllers
 */
class DownloadController extends LfmController {
	public $option = 'download';

    /**
     * Download a file
     *
     * @return mixed
     */
    public function getDownload()
    {
        return Response::download($this->getPath('directory') . Input::get('file'));
    }

}

<?php namespace Jayked\Laravelfilemanager\controllers;

use Jayked\Laravelfilemanager\controllers\Controller;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;

/**
 * Class DownloadController
 * @package Jayked\Laravelfilemanager\controllers
 */
class DownloadController extends LfmController {
	public $option = 'download';

    /**
     * Download a file
     *
     * @return mixed
     */
    public function getDownload()
    {
        $location = $this->getPath('directory') . Input::get('file');
        $this->validateLocation($location);
        return Response::download($location);
    }

}

[DOWNLOAD] Validate access to download requested path


<?php

App::uses('PhpReader', 'Configure');
App::uses('ConfigReaderInterface', 'Configure');

/**
 * DashboardsConfigReader
 *
 * @package  Croogo.Dashboards.Lib.Configure
 * @since    2.2
 * @author   Rachman Chavik <rchavik@gmail.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class DashboardsConfigReader extends PhpReader implements ConfigReaderInterface
{

	protected $_settingKey = 'Dashboards';

/**
 * Reads a plugin dashboard setting and store them under $_settingKey
 *
 * @param string $key Configuration key name
 * @return array
 */
	public function read($key) {
		$config = parent::read($key);
		$defaults = array(
			'title' => false,
			'weight' => 9999,
			'element' => false,
			'cache' => true,
			'access' => array(),
			'column' => false,
			'collapsed' => false,
		);
		foreach ($config as $alias => &$setting) {
			$setting = Hash::merge($defaults, $setting);
		}
		$result = array($this->_settingKey => $config);
		return $result;
	}

}

<?php

App::uses('PhpReader', 'Configure');
App::uses('ConfigReaderInterface', 'Configure');

/**
 * DashboardsConfigReader
 *
 * @package  Croogo.Dashboards.Lib.Configure
 * @since    2.2
 * @author   Rachman Chavik <rchavik@gmail.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class DashboardsConfigReader extends PhpReader implements ConfigReaderInterface
{

	protected $_settingKey = 'Dashboards';

/**
 * Reads a plugin dashboard setting and store them under $_settingKey
 *
 * @param string $key Configuration key name
 * @return array
 */
	public function read($key) {
		$config = parent::read($key);
		$defaults = array(
			'title' => false,
			'weight' => 9999,
			'element' => false,
			'cache' => true,
			'access' => array(),
			'column' => false,
			'collapsed' => false,
		);
		$settings = array();
		foreach ($config as $alias => $setting) {
			$alias = Inflector::slug($alias, '-');
			$setting = Hash::merge($defaults, $setting);
			$settings[$alias] = $setting;
		}
		$result = array($this->_settingKey => $settings);
		return $result;
	}

}

Convert dashboard alias using dots with dashes

Using dots in an identifier is common in config files.
By converting it as `-`, it enables using the dashboard
alias as jquery selector.


<?php

namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs;

use Symfony\Component\ClassLoader\UniversalClassLoader;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class TestKernel extends Kernel
{
    public function __construct()
    {
        parent::__construct('test_stub_env', true);
    }

    public function init()
    {
    }

    public function getRootDir()
    {
        return sys_get_temp_dir() . '/translation-test-stub-cache';
    }

    public function registerBundles()
    {
        $loader = new UniversalClassLoader();

        $loader->registerNamespace('SomeProject\\', array(__DIR__));
        $loader->registerNamespace('SomeAnotherProject\\', array(__DIR__));
        $loader->register();

        return array(
            new \SomeProject\Bundle\SomeBundle\SomeBundle(),
            new \SomeAnotherProject\Bundle\SomeAnotherBundle\SomeAnotherBundle()
        );
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
    }
}

<?php

namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs;

use Symfony\Component\ClassLoader\UniversalClassLoader;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class TestKernel extends Kernel
{
    public function __construct()
    {
        parent::__construct('test_stub_env', true);
    }

    public function init()
    {
    }

    public function getRootDir()
    {
        return sys_get_temp_dir() . '/translation-test-stub-cache';
    }

    public function registerBundles()
    {
        // Run unit test
        $loader = new UniversalClassLoader();

        $loader->registerNamespace('SomeProject\\', array(__DIR__));
        $loader->registerNamespace('SomeAnotherProject\\', array(__DIR__));
        $loader->register();

        return array(
            new \SomeProject\Bundle\SomeBundle\SomeBundle(),
            new \SomeAnotherProject\Bundle\SomeAnotherBundle\SomeAnotherBundle()
        );
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
    }
}

BAP-16497: Change ClassLoader component
- trigger unit test run


<?php

namespace App\Module\Web\Controller;

use Air\View\ViewFactoryInterface;

/**
 * Class AbstractWebController
 * @package App\Module\Web\Controller
 * @author Petr Pliska <petr.pliska@post.cz>
 */
abstract class AbstractWebController
{
    /**
     * @Inject
     * @var ViewFactoryInterface
     */
    protected $viewFactory;
}

<?php

namespace App\Module\Web\Controller;

use Air\View\ViewFactoryInterface;

/**
 * Class AbstractWebController
 * @package App\Module\Web\Controller
 * @author Petr Pliska <petr.pliska@post.cz>
 */
abstract class AbstractWebController
{
    /**
     * @inject
     * @var ViewFactoryInterface
     */
    protected $viewFactory;
}

Fix a type in annotation

Fix a type in annotation


<?php namespace Ejcnet\Sourcebot;

class Sourcebot {

  public function helloWorld($bool = true)
  {
    return $bool;
  }

}

<?php namespace Ejcnet\Sourcebot;

class Sourcebot {

  public function helloWorld()
  {
    $bool = true;
    return $bool;
  }

}

Fix single responsibility warning from CodeClimate


<?php

class Services_Twilio_Rest_Members
    extends Services_Twilio_ListResource
{
    /**
     * Return the member at the front of the queue. Note that any operations
     * performed on the Member returned from this function will use the /Front
     * Uri, not the Member's CallSid.
     *
     * @return Services_Twilio_Rest_Member The member at the front of the queue
     */
    public function front() {
        return new $this->instance_name($this->client, $this->uri . '/Front');
    }

    /* Participants are identified by CallSid, not like ME123 */
    public function getObjectFromJson($params, $idParam = 'sid') {
        return parent::getObjectFromJson($params, 'call_sid');
    }

    public function getResourceName($camelized = false)
    {
      // The JSON property name is atypical.
      return $camelized ? 'Members' : 'queue_members';
    }
}

Fix account->queue->members JSON property name.


Are you sure you want to delete this page? This cannot be recovered.

<?
	$msg = '';

	if ($count = $page->mptt->count() > 0):
		$titlelist = '';

		foreach ($page->mptt->descendants() as $pi):
			$titlelist .= "
" . $pi->title . "
";
		endforeach;

		$titlelist = preg_replace("/\, $/", "", $titlelist);

		$msg = "
Warning:
Deleting this page will make it's " . $count . " child ";

		$msg .= ($count !== 1) ? 'page' : 'pages';

		$msg .=  " inaccessible:

" . $titlelist . "

";
	endif;

	echo $msg;
?>

Click 'Okay' to delete, or 'Cancel' to keep the page.

Are you sure you want to delete this page? This cannot be recovered.

<?
	$msg = '';

	if ($count = $page->mptt->count() > 0):
		$titlelist = '';

		foreach ($page->mptt->descendants() as $pi):
			$titlelist .= "
" . $pi->page->title . "
";
		endforeach;

		$titlelist = preg_replace("/\, $/", "", $titlelist);

		$msg = "
Warning:
Deleting this page will make it's " . $count . " child ";

		$msg .= ($count !== 1) ? 'page' : 'pages';

		$msg .=  " inaccessible:

" . $titlelist . "

";
	endif;

	echo $msg;
?>

Click 'Okay' to delete, or 'Cancel' to keep the page.

Delete page warning working with child page count


<?php
/**
 * Encapsulation of model manipulation and business rules
 */
abstract class Jaded_Service
{
	/**
	 * Singleton instances of services
	 */
	protected static $aInstances = array();

	////////////////////////////////////////////////////////////////////////////////
	// PUBLIC STATIC //////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////

	/**
	 * Returns an instance of the requested service
	 * @param string $sType
	 * @return Jaded_Service
	 * @throws Jaded_Service_Exception if the type requested is an invalid service
	 */
	public static function instance($sType)
	{
		if (empty(self::$aInstances[$sType])) {
			if (!is_subclass_of($sType, __CLASS__)) {
				throw new Jaded_Service_Exception("Invalid Service type [{$sType}]", Jaded_Service_Exception::InvalidType);
			}
			self::set($sType, new $sType());
		}
		return self::$aInstances[$sType];
	}

	/**
	 * Set a service instance
	 * @param string $sType
	 * @param Jaded_Service $oService
	 */
	public static function set($sType, Jaded_Service $oService)
	{
		self::$aInstances[$sType] = $oService;
	}
}

<?php
/**
 * Encapsulation of model manipulation and business rules
 */
abstract class Jaded_Service
{
	/**
	 * Singleton instances of services
	 */
	protected static $aInstances = array();

	////////////////////////////////////////////////////////////////////////////////
	// PUBLIC STATIC //////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////

	/**
	 * Returns an instance of the requested service
	 * @param string $sType
	 * @return Jaded_Service
	 * @throws Jaded_Service_Exception if the type requested is an invalid service
	 */
	public static function instance($sType)
	{
		if (empty(self::$aInstances[$sType])) {
			if (!is_subclass_of($sType, __CLASS__)) {
				throw new Jaded_Service_Exception("Invalid Service type [{$sType}]", Jaded_Service_Exception::InvalidType);
			}
			self::set($sType, new $sType());
		}
		return self::$aInstances[$sType];
	}

	/**
	 * Set a service instance
	 * @param string $sType
	 * @param Jaded_Service $oService
	 */
	public static function set($sType, $oService)
	{
		if ($oService !== null && !($oService instanceof __CLASS__)) {
			throw new Jaded_Service_Exception("Invalid Service type [{$sType}]", Jaded_Service_Exception::InvalidType);
		}
		self::$aInstances[$sType] = $oService;
	}
}

Set service objects can be null.

Set service objects can be null.


<?php
/**
 * System messages translation for CodeIgniter(tm)
 *
 * @author	CodeIgniter community
 * @copyright	Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
 * @license	http://opensource.org/licenses/MIT	MIT License
 * @link	http://codeigniter.com
 */
defined('BASEPATH') OR exit('No direct script access allowed');

$lang['terabyte_abbr'] = 'Тб';
$lang['gigabyte_abbr'] = 'Гб';
$lang['megabyte_abbr'] = 'Мб';
$lang['kilobyte_abbr'] = 'Кб';
$lang['bytes'] = 'Байт';

<?php
/**
 * System messages translation for CodeIgniter(tm)
 *
 * @author	CodeIgniter community
 * @copyright	Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
 * @license	http://opensource.org/licenses/MIT	MIT License
 * @link	http://codeigniter.com
 */
defined('BASEPATH') OR exit('No direct script access allowed');

$lang['terabyte_abbr'] = 'ТБ';
$lang['gigabyte_abbr'] = 'ГБ';
$lang['megabyte_abbr'] = 'МБ';
$lang['kilobyte_abbr'] = 'КБ';
$lang['bytes'] = 'Байт';

Revert "Revert "Abbreviations changed in accordance with national standard""


<?php

namespace Avanzu\AdminThemeBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('avanzu_admin_theme');

        $rootNode->children()
                    ->scalarNode('bower_bin')
                        ->defaultValue('/usr/local/bin/bower')
                    ->end()
                    ->scalarNode('use_assetic')
                        ->defaultValue(true)
                    ->end()
                    ->scalarNode('use_twig')
                        ->defaultValue(true)
                    ->end()
                    ->arrayNode('options')
                        ->children()
                            ->scalarNode('skin')->end()

                        ->beforeNormalization()->castToArray()->end()
                    ->end()
                ->end();
        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

<?php

namespace Avanzu\AdminThemeBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('avanzu_admin_theme');

        $rootNode->children()
                    ->scalarNode('bower_bin')
                        ->defaultValue('/usr/local/bin/bower')
                    ->end()
                    ->scalarNode('use_assetic')
                        ->defaultValue(true)
                    ->end()
                    ->scalarNode('use_twig')
                        ->defaultValue(true)
                    ->end()
                    ->arrayNode('options')
                        ->children()
                            ->scalarNode('skin')
                            ->defaultValue('skin-blue-light')
                        ->end()
                    ->end() // ->beforeNormalization()->castToArray()->end()
                ->end();
        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

Remove before normalization and use blue light as default


<?php

namespace Drupal\AppConsole\Test\DataProvider;

/**
 * Class ModuleDataProviderTrait
 * @package Drupal\AppConsole\Test\DataProvider
 */
trait ControllerDataProviderTrait
{
    /**
     * @return array
     */
    public function commandData()
    {
        $this->setUpTemporalDirectory();

        $services = [
          'twig' => [
            'name' => 'twig',
            'machine_name' => 'twig',
            'class' => '\Twig_Environment',
            'short' => 'Twig_Environment',
          ]
        ];

        $routes = [
          ['title' => 'Foo Controller', 'method' => 'index', 'route' => 'index']
        ];

        return [
          // ToDo: send sercives, issues with Twig container get
          //['foo', 'FooController', $routes, true, $services, 'foo_controller'],
          ['foo', 'FooController', $routes, true, null, 'foo_controller'],
          ['foo', 'FooController', $routes, false, null, 'foo_controller'],

        ];
    }
}

<?php

namespace Drupal\AppConsole\Test\DataProvider;

/**
 * Class ModuleDataProviderTrait
 * @package Drupal\AppConsole\Test\DataProvider
 */
trait ControllerDataProviderTrait
{
    /**
     * @return array
     */
    public function commandData()
    {
        $this->setUpTemporalDirectory();

        $routes = [
          ['title' => 'Foo Controller', 'method' => 'index', 'route' => 'index']
        ];

        return [
          ['foo', 'FooController', $routes, true, null, 'foo_controller'],
          ['foo', 'FooController', $routes, false, null, 'foo_controller'],

        ];
    }
}

Remove Todo and unused services property


<?php

namespace SpellingDictionary;

class Words {
	public function addWord() {
		$dbw = Database::getConnection( DB_MASTER );
		}

}

<?php

namespace SpellingDictionary;

class Words {
	static function addWord( $formData ) {
		// $user = $this->getUser();
		global $wgSpellingDictionaryDatabase;
		$dbw = wfGetDB( DB_MASTER, array(), $wgSpellingDictionaryDatabase );

		$user = "ABC";

		$values = array(
			'sd_word' => $formData['word'],
			'sd_language' => $formData['language'],
			'sd_user' => $user,
			'sd_timestamp' => $dbw->timestamp(),
		);

		$dbw->insert( 'spell_dict_word_list',
			$values,
			__METHOD__ );
			return true;
		// return 'Try again';
	}
}

Insert the word submitted into the table

-Presently used a dummy variable as user, to be changed to the current
session user


<?php

namespace Marein\Nchan\Http;

final class Url
{
    /**
     * @var string
     */
    private $value;

    /**
     * Url constructor.
     *
     * @param string $value
     */
    public function __construct(string $value)
    {
        $parsed = parse_url($value);

        if ($parsed === false) {
            throw new \InvalidArgumentException();
        }

        if (!isset($parsed['host']) && !isset($parsed['scheme'])) {
            throw new \InvalidArgumentException();
        }

        $this->value = $value;
    }

    /**
     * Returns the new Url with the concatenated values.
     *
     * @param string $value
     *
     * @return Url
     */
    public function append(string $value): Url
    {
        return new Url((string)$this . $value);
    }

    /**
     * Returns the url.
     *
     * @return string
     */
    public function __toString(): string
    {
        return $this->toString();
    }

    /**
     * Returns the url.
     *
     * @return string
     */
    public function toString(): string
    {
        return $this->value;
    }
}

<?php

namespace Marein\Nchan\Http;

final class Url
{
    /**
     * @var string
     */
    private $value;

    /**
     * Url constructor.
     *
     * @param string $value
     */
    public function __construct(string $value)
    {
        $parsed = parse_url($value);

        if ($parsed === false) {
            throw new \InvalidArgumentException($value . ' is not a valid url.');
        }

        if (!isset($parsed['host']) && !isset($parsed['scheme'])) {
            throw new \InvalidArgumentException('The url ' . $value . ' must at least consists of host and scheme.');
        }

        $this->value = $value;
    }

    /**
     * Returns the new Url with the concatenated values.
     *
     * @param string $value
     *
     * @return Url
     */
    public function append(string $value): Url
    {
        return new Url((string)$this . $value);
    }

    /**
     * Returns the url.
     *
     * @return string
     */
    public function __toString(): string
    {
        return $this->toString();
    }

    /**
     * Returns the url.
     *
     * @return string
     */
    public function toString(): string
    {
        return $this->value;
    }
}

Throw meaningful exception message if given url is not valid.


<?php
/**
 * Interface for JiraWebhookData converters.
 *
 * @credits https://github.com/kommuna
 * @author  Chewbacca chewbacca@devadmin.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace JiraWebhook;

use JiraWebhook\Models\JiraWebhookData;
use Maknz\Slack\Message;

interface JiraWebhookDataConverter
{
    /**
     * Convert $data into a Slack Client Instance
     *
     * @param JiraWebhookData $data parsed data from JIRA webhook
     * @param Message $message Slack Client Message instance
     *
     * @return Message
     */
    public function convert(JiraWebhookData $data, Message $message);
}

<?php
/**
 * Interface for JiraWebhookData converters.
 *
 * @credits https://github.com/kommuna
 * @author  Chewbacca chewbacca@devadmin.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace JiraWebhook;

use JiraWebhook\Models\JiraWebhookData;

interface JiraWebhookDataConverter
{
    /**
     * Convert $data into a formatted string message
     *
     * @param JiraWebhookData $data parsed data from JIRA webhook
     *
     * @return string
     */
    public function convert(JiraWebhookData $data);
}

Remove slack dependency from interface

[TL-48] Remove slack dependency from interface


<?php

echo "Backfilling commit summaries...\n";

$commits = new LiskMigrationIterator(new PhabricatorRepositoryCommit());
foreach ($commits as $commit) {
  echo 'Filling Commit #'.$commit->getID()."\n";

  if (strlen($commit->getSummary())) {
    continue;
  }

  $data = $commit->loadOneRelative(
    new PhabricatorRepositoryCommitData(),
    'commitID');

  if (!$data) {
    continue;
  }

  $commit->setSummary($data->getSummary());
  $commit->save();
}

echo "Done.\n";

<?php

echo "Backfilling commit summaries...\n";

$table = new PhabricatorRepositoryCommit();
$conn_w = $table->establishConnection('w');
$commits = new LiskMigrationIterator($table);
foreach ($commits as $commit) {
  echo 'Filling Commit #'.$commit->getID()."\n";

  if (strlen($commit->getSummary())) {
    continue;
  }

  $data = $commit->loadOneRelative(
    new PhabricatorRepositoryCommitData(),
    'commitID');

  if (!$data) {
    continue;
  }

  queryfx(
    $conn_w,
    'UPDATE %T SET summary = %s WHERE id = %d',
    $commit->getTableName(),
    $data->getSummary(),
    $commit->getID());
}

echo "Done.\n";

Fix accidental forward dependency in old commit summary migration

Summary: See IRC. This migration inadvertently depends on the columns in the commit table, because it calls `save()`, and thus broke for installs with data after we added the `importStatus` column. Since that was ~9 months after this patch, probably not many installs are affected.

Test Plan: Ran patch locally with `--apply` on data. Had user verify fix.

Reviewers: btrahan

Reviewed By: btrahan

CC: aran

Differential Revision: https://secure.phabricator.com/D8152


<?php

namespace Clippings\ParsedownProvider\Test;

use Pimple\Container;
use Clippings\ParsedownProvider\ParsedownServiceProvider;

class ParsedownServiceProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testRegister()
    {
        $container = new Container();
        $container->register(new ParsedownServiceProvider());
        $this->assertNotNull(
            $container['parsedown'],
            '"parsedown" service must be registered by the provider'
        );
        $this->assertInstanceOf(
            'Parsedown',
            $container['parsedown'],
            '"parsedown" service must be an instance of Parsedown'
        );
        $this->assertSame(
            $container['parsedown'],
            $container['parsedown'],
            '"parsedown" service must always return the same instance'
        );
    }
}

<?php

namespace Clippings\ParsedownProvider\Test;

use Pimple\Container;
use Clippings\ParsedownProvider\ParsedownServiceProvider;

class ParsedownServiceProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testRegister()
    {
        $app = new Container();
        $app->register(new ParsedownServiceProvider());

        $this->assertArrayHasKey('parsedown.class', $app);
        $this->assertArrayHasKey('parsedown.breaks_enabled', $app);
        $this->assertArrayHasKey('parsedown.markup_escaped', $app);
        $this->assertArrayHasKey('parsedown.urls_linked', $app);
        $this->assertArrayHasKey('parsedown', $app);
        $this->assertArrayHasKey('parsedown.twig_filter', $app);

        $this->assertInstanceOf('Parsedown', $app['parsedown']);
        $this->assertSame($app['parsedown'], $app['parsedown']);

        $this->assertTrue($app['parsedown.breaks_enabled']);
        $this->assertFalse($app['parsedown.markup_escaped']);
        $this->assertTrue($app['parsedown.urls_linked']);

        $this->assertInstanceOf(
            'Twig_SimpleFilter',
            $app['parsedown.twig_filter']
        );
    }
}

Test all services and variables the provider register by default


<?php

/************************************************************************
 * Extension Manager/Repository config file for ext "bootstrap_package".
 ************************************************************************/
$EM_CONF[$_EXTKEY] = array(
    'title' => 'Bootstrap Package',
    'description' => 'Bootstrap Package delivers a full configured frontend theme for TYPO3, based on the Bootstrap CSS Framework.',
    'category' => 'templates',
    'constraints' => array(
        'depends' => array(
            'typo3' => '7.6.0-7.99.99'
        ),
        'conflicts' => array(
            'css_styled_content' => '*',
            'fluid_styled_content' => '*',
            'themes' => '*',
            'fluidpages' => '*',
            'dyncss' => '*',
        ),
    ),
    'autoload' => array(
        'psr-4' => array(
            'BK2K\\BootstrapPackage\\' => 'Classes'
        ),
    ),
    'state' => 'stable',
    'uploadfolder' => 0,
    'createDirs' => '',
    'clearCacheOnLoad' => 1,
    'author' => 'Benjamin Kott',
    'author_email' => 'info@bk2k.info',
    'author_company' => 'private',
    'version' => '7.0.0-dev',
);

<?php

/************************************************************************
 * Extension Manager/Repository config file for ext "bootstrap_package".
 ************************************************************************/
$EM_CONF[$_EXTKEY] = array(
    'title' => 'Bootstrap Package',
    'description' => 'Bootstrap Package delivers a full configured frontend theme for TYPO3, based on the Bootstrap CSS Framework.',
    'category' => 'templates',
    'constraints' => array(
        'depends' => array(
            'typo3' => '7.6.2-8.99.99'
        ),
        'conflicts' => array(
            'css_styled_content' => '*',
            'fluid_styled_content' => '*',
            'themes' => '*',
            'fluidpages' => '*',
            'dyncss' => '*',
        ),
    ),
    'autoload' => array(
        'psr-4' => array(
            'BK2K\\BootstrapPackage\\' => 'Classes'
        ),
    ),
    'state' => 'stable',
    'uploadfolder' => 0,
    'createDirs' => '',
    'clearCacheOnLoad' => 1,
    'author' => 'Benjamin Kott',
    'author_email' => 'info@bk2k.info',
    'author_company' => 'private',
    'version' => '7.0.0-dev',
);

Add TYPO3 CMS 8 as compatible version

[TASK] Add TYPO3 CMS 8 as compatible version


<?php
namespace Concrete\Core\Form\Service\Widget;
use Loader;
use View;
use Request;
class Typography {

    /**
     * Creates form fields and JavaScript includes to add a font picker widget.
     *
     *     $dh->output('background-color', '#f00');
     *
     * @param string $inputName
     * @param array $value
     * @param array $options
     */
    public function output($inputName, $value = array(), $options = array()) {
        $view = View::getInstance();
        $view->requireAsset('core/style-customizer');

        $options['inputName'] = $inputName;
        $options = array_merge($options, $value);
        $strOptions = json_encode($options);

        print '';
        print "";

    }

}

<?php
namespace Concrete\Core\Form\Service\Widget;
use View;
class Typography
{
    /**
     * Creates form fields and JavaScript includes to add a font picker widget.
     *
     *     $dh->output('background-color', '#f00');
     *
     * @param string $inputName
     * @param array  $value
     * @param array  $options
     */
    public function output($inputName, $value = array(), $options = array())
    {
        $view = View::getInstance();
        $view->requireAsset('core/style-customizer');

        $options['inputName'] = $inputName;
        $options = array_merge($options, $value);
        $strOptions = json_encode($options);

        print '';
        print "";

    }

}

Update PSR-2 and remove unused use

Update PSR-2 and remove unused use


<?php
namespace Cms\Controller;

use App\Controller\AppController as BaseController;
use Cake\Event\Event;
use Cms\Model\Table\ArticlesTable;

class AppController extends BaseController
{
    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * @return void
     */
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }

    /**
     * {@inheritDoc}
     */
    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);

        $table = $this->{$this->name};
        $table = $table->association('Articles') ? $this->{$this->name}->Articles->target() : $table;

        if (!$table instanceof ArticlesTable) {
            return;
        }

        // pass article types to all Views
        $this->set('types', $table->getTypes());

        $searchQuery = $this->request->query('q') ?: '';

        $searchTitle = $searchQuery ? __('Search Results for') . ' \'' . $searchQuery . '\'' : '';
        // pass search title to all Views
        $this->set('searchTitle', $searchTitle);

        // set search query on Articles table
        $table->setSearchQuery($searchQuery);
    }
}

<?php
namespace Cms\Controller;

use App\Controller\AppController as BaseController;
use Cake\Event\Event;
use Cms\Model\Table\ArticlesTable;

class AppController extends BaseController
{
    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * @return void
     */
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }

    /**
     * {@inheritDoc}
     */
    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);

        $table = $this->{$this->name};
        $table = $table->association('Articles') ? $this->{$this->name}->Articles->target() : $table;

        if (!$table instanceof ArticlesTable) {
            return;
        }

        // pass article types to all Views
        $this->set('types', $table->getTypes());

        $searchQuery = $this->request->query('q') ?: '';

        $searchTitle = $searchQuery ? __('Search Results for') . ' \'' . $searchQuery . '\'' : '';
        // pass search title to all Views
        $this->set('searchTitle', $searchTitle);

        // set search query on Articles table
        $table->setSearchQuery($searchQuery);
    }

    /**
     * {@inheritDoc}
     */
    public function beforeRender(Event $event)
    {
        parent::beforeRender($event);

        $this->viewBuilder()->setHelpers(['CakephpTinymceElfinder.TinymceElfinder']);
        $this->set('user', $this->Auth->user());
    }
}

Load required helper class and pass auth user info to the View


<?php

declare(strict_types=1);

namespace Brick\Geo\Engine;

use Brick\Geo\Geometry;

/**
 * Represents a geometry parameter sent to the database engine.
 *
 * This object is used to carry a representation of the geometry from the abstract DatabaseEngine to one of its
 * concrete implementations, like PDOEngine or SQLite3Engine.
 */
class GeometryParameter
{
    /**
     * The WKT or WKB data.
     *
     * @readonly
     *
     * @var string
     */
    public $data;

    /**
     * True for WKB, false for WKT.
     *
     * @readonly
     *
     * @var bool
     */
    public $isBinary;

    /**
     * @readonly
     *
     * @var int
     */
    public $srid;

    public function __construct(Geometry $geometry, bool $isBinary)
    {
        $this->data     = $isBinary ? $geometry->asBinary() : $geometry->asText();
        $this->isBinary = $isBinary;
        $this->srid     = $geometry->SRID();
    }
}

<?php

declare(strict_types=1);

namespace Brick\Geo\Engine;

use Brick\Geo\Geometry;

/**
 * Represents a geometry parameter sent to the database engine.
 *
 * This object is used to carry a representation of the geometry from the abstract DatabaseEngine to one of its
 * concrete implementations, like PDOEngine or SQLite3Engine.
 *
 * @psalm-immutable
 */
class GeometryParameter
{
    /**
     * The WKT or WKB data.
     *
     * @var string
     */
    public $data;

    /**
     * True for WKB, false for WKT.
     *
     * @var bool
     */
    public $isBinary;

    /**
     * @var int
     */
    public $srid;

    public function __construct(Geometry $geometry, bool $isBinary)
    {
        $this->data     = $isBinary ? $geometry->asBinary() : $geometry->asText();
        $this->isBinary = $isBinary;
        $this->srid     = $geometry->SRID();
    }
}

Replace readonly with psalm-immutable at class level


<?php
declare(strict_types = 1);

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class MeetingDay extends Model
{
  protected $fillable = ['meeting_id', 'day', 'from', 'to'];
  protected $hidden = ['meeting_id', 'id'];
  protected $dates = ['day'];
  public $timestamps = false;

  public function hours(): HasMany
  {
    return $this->hasMany(MeetingDayHour::class);
  }
}

<?php
declare(strict_types = 1);

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class MeetingDay extends Model
{
  protected $fillable = ['meeting_id', 'day', 'from', 'to'];
  protected $hidden = ['meeting_id', 'id'];
  protected $dates = ['day'];
  public $timestamps = false;

  public function setDayAttribute($value)
  {
    $this->attributes['day'] = Carbon::createFromFormat('Y-m-d\\TH:i:s.uZ', $value);
  }

  public function hours(): HasMany
  {
    return $this->hasMany(MeetingDayHour::class);
  }
}

Improve date handling (with JS date format)


<?php

namespace M6Web\Bundle\FirewallBundle\EventListener;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use M6Web\Bundle\FirewallBundle\Firewall\ProviderInterface;

/**
 * class RequestListener
 */
class RequestListener extends Bundle
{
    /**
    * firewall provider
    */
    protected $provider;

    /**
    * @param provider $provider firewall provider
    */
    public function __construct(ProviderInterface $provider)
    {
        $this->provider = $provider;
    }

    /**
    * on request event
    * @param GetResponseEvent $event event
    */
    public function onRequest(GetResponseEvent $event)
    {
        $patterns = $this->provider->getPatterns();
        if ($patterns) {
            foreach ($patterns as $pattern) {
                if ($pattern['matcher']->matches($event->getRequest())) {
                   $firewall = $this->provider->getFirewall($pattern['config']);
                   $firewall->handle();
                }
            }
        }
    }

}

<?php

namespace M6Web\Bundle\FirewallBundle\EventListener;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use M6Web\Bundle\FirewallBundle\Firewall\ProviderInterface;

/**
 * class RequestListener
 */
class RequestListener extends Bundle
{
    /**
    * firewall provider
    */
    protected $provider;

    /**
    * @param provider $provider firewall provider
    */
    public function __construct(ProviderInterface $provider)
    {
        $this->provider = $provider;
    }

    /**
    * on request event
    * @param GetResponseEvent $event event
    */
    public function onRequest(GetResponseEvent $event)
    {
        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
            return;
        }
        $patterns = $this->provider->getPatterns();
        if ($patterns) {
            foreach ($patterns as $pattern) {
                if ($pattern['matcher']->matches($event->getRequest())) {
                   $firewall = $this->provider->getFirewall($pattern['config']);
                   $firewall->handle();
                }
            }
        }
    }

}

Check patterns only on master request

Check patterns only on master request


<?php
require('auth.php');

if(!isset($_POST['domain'], $_POST['list'], $_POST['token'])) {
    log_and_die("Missing POST variables");
}

check_cors();
check_csrf($_POST['token']);
check_domain();

switch($_POST['list']) {
    case "white":
        echo exec("sudo pihole -w -q ${_POST['domain']}");
        break;
    case "black":
        echo exec("sudo pihole -b -q ${_POST['domain']}");
        break;
}

?>

<?php
require('auth.php');

if(!isset($_POST['domain'], $_POST['list'], $_POST['token']) || !isset($_POST['domain'], $_POST['list'], $_POST['pw'])) {
	log_and_die("Missing POST variables");
}

if(isset($_POST['token']))
{
	check_cors();
	check_csrf($_POST['token']);
}
elseif(isset($_POST['pw']) && $_POST['list'] == "white")
{
	require("password.php");
	if(strlen($pwhash) == 0)
	{
		log_and_die("No password specified - whitelisting with password not supported");
	}
	elseif($wrongpassword)
	{
		log_and_die("Wrong password - whitelisting of ${_POST['domain']} not permitted");
	}
}
check_domain();

switch($_POST['list']) {
	case "white":
		echo exec("sudo pihole -w -q ${_POST['domain']}");
		break;
	case "black":
		echo exec("sudo pihole -b -q ${_POST['domain']}");
		break;
}

?>

Allow whitelisting when correct passwort is given via POST


<?php

namespace pho\Reporter;

use pho\Console\Console;
use pho\Suite\Suite;
use pho\Runnable\Spec;

class DotReporter extends AbstractReporter implements ReporterInterface
{
    private static $maxPerLine = 60;

    private $lineLength;

    /**
     * Creates a SpecReporter object, used to render a nested view of test
     * suites and specs.
     *
     * @param Console $console A console for writing output
     */
    public function __construct(Console $console)
    {
        parent::__construct($console);
        $this->lineLength = 0;
    }

    /**
     * Ran before an individual spec.
     *
     * @param Spec $spec The spec before which to run this method
     */
    public function beforeSpec(Spec $spec)
    {
        $this->specCount += 1;

        if ($this->lineLength == self::$maxPerLine) {
            $this->console->writeLn('');
        }
    }

    /**
     * Ran after an individual spec.
     *
     * @param Spec $spec The spec after which to run this method
     */
    public function afterSpec(Spec $spec)
    {
        $this->lineLength += 1;

        if (!$spec->passed()) {
            $this->failedSpecs[] = $spec;
            $failure = $this->formatter->red('F');
            $this->console->write($failure);
        } else {
            $this->console->write('.');
        }
    }
}

<?php

namespace pho\Reporter;

use pho\Console\Console;
use pho\Suite\Suite;
use pho\Runnable\Spec;

class DotReporter extends AbstractReporter implements ReporterInterface
{
    private static $maxPerLine = 60;

    private $lineLength;

    /**
     * Creates a SpecReporter object, used to render a nested view of test
     * suites and specs.
     *
     * @param Console $console A console for writing output
     */
    public function __construct(Console $console)
    {
        parent::__construct($console);
        $this->lineLength = 0;
    }

    /**
     * Ran before an individual spec.
     *
     * @param Spec $spec The spec before which to run this method
     */
    public function beforeSpec(Spec $spec)
    {
        $this->specCount += 1;

        if ($this->lineLength == self::$maxPerLine) {
            $this->console->writeLn('');
            $this->lineLength = 0;
        }
    }

    /**
     * Ran after an individual spec.
     *
     * @param Spec $spec The spec after which to run this method
     */
    public function afterSpec(Spec $spec)
    {
        $this->lineLength += 1;

        if (!$spec->passed()) {
            $this->failedSpecs[] = $spec;
            $failure = $this->formatter->red('F');
            $this->console->write($failure);
        } else {
            $this->console->write('.');
        }
    }
}

Fix dot reporter not resetting the current line length


<?php

namespace GrooveHQ\Service;

class AgentsDescription extends BasicServiceDescription
{

    protected function getServiceDescription()
    {
        return [
            'operations' => [
                'find' => [
                    'summary' => 'Finding one agent',
                    'httpMethod' => 'GET',
                    'uri' => '/agents/{agent_email}',
                    'parameters' => [
                        'agent_email' => [
                            'description' => 'The agent email',
                            'type' => 'string',
                            'location' => 'uri',
                        ],
                    ]
                ],
            ]
        ];
    }

}

<?php

namespace GrooveHQ\Service;

class AgentsDescription extends BasicServiceDescription
{

    protected function getServiceDescription()
    {
        return [
            'operations' => [
                'list' => [
                    'summary' => 'Listing agents',
                    'httpMethod' => 'GET',
                    'uri' => '/agents',
                    'parameters' => [
                        'group' => [
                            'description' => 'The ID of a Group to filter by',
                            'type' => 'string',
                            'required' => false,
                            'location' => 'query'
                        ]
                    ],
                ],
                'find' => [
                    'summary' => 'Finding one agent',
                    'httpMethod' => 'GET',
                    'uri' => '/agents/{agent_email}',
                    'parameters' => [
                        'agent_email' => [
                            'description' => 'The agent email',
                            'type' => 'string',
                            'location' => 'uri',
                        ],
                    ]
                ],
            ]
        ];
    }

}

Add method for listing agents

Add method for listing agents


<?php

get_header(); ?>

			      Katherine

			      Anne

			      Porter

			    correspondence

Over 5,000 pages of digitized materials granting unprecedented access
			       to the ideas, attitudes, and experiences of a distinguished
			       20th century American writer.

			     Read More

<?php get_footer(); ?>

Simplify markup on front page

Simplify markup on front page

Now that we no longer depend on Lettering.js


<?php

return array(
    'host'     => 'localhost',
    'port'     => '61613',
    'login'    => 'admin',
    'passcode' => 'password',
    'vhost'    => 'apollo',
);

<?php

return array(
    'host'     => '127.0.0.1',
    'port'     => '61613',
    'login'    => 'admin',
    'passcode' => 'password',
    'vhost'    => 'apollo',
);

Use IP instead of hostname for functionnal tests


<?php
return array(
    'app' => array(
        'base_url' => 'http://lightdatasys.com/app/#',
    ),
);

<?php
return array(
    'app' => array(
        'base_url' => 'http://lightdatasys.com/app/#',
        'commissioner' => array(
            'name' => 'The Commissioner',
            'email' => '',
        ),
    ),
);

Add the ability to configure commissioner name/email


@extends('layouts.base')

@section('content')
  @while(have_posts()) @php(the_post())
    @include('partials/content-single-'.get_post_type())
  @endwhile
@endsection

@extends('layouts.base')

@section('content')
  @while(have_posts()) @php(the_post())
    @include('partials/content-single-'.get_post_type())
  @endwhile

  @php
      global $post;
      $categories = wp_get_post_terms( get_the_ID(), 'category');
      $category_posts = new WP_Query( array(
        'cat'          => $categories[0]->term_id,
        'post__not_in' => array( get_the_ID() ),
    ) );
  @endphp

  @while($category_posts->have_posts()) @php($category_posts->the_post())

Read More:

              @if(has_post_thumbnail())

              @endif

                          @include('partials/entry-cat')

{{ get_the_title() }}

                          @include('partials/entry-meta')

                          @php(the_excerpt())

  @endwhile
@endsection

Add read more section to bottom of single posts


<?php
?>

	<form method="get" id="searchform" role="form" class="navbar-form navbar-right" action="<?php echo esc_url( home_url( '/' ) ); ?>">

				<input type="text" class="form-control" name="s" id="s" placeholder="<?php esc_attr_e( 'Search...', 'ttp' ); ?>" />

	</form>

<?php
?>

	<form method="get" id="searchform" role="form" class="navbar-form navbar-right" action="<?php echo esc_url( home_url( '/' ) ); ?>">

				<input type="text" class="form-control" name="s" id="s" placeholder="<?php esc_attr_e( 'Search...', 'ttp' ); ?>" />

					<button type="submit" class="btn btn-default"></button>

	</form>

Fix markup for button as search box add-on


<?php namespace Performance\Lib;

/**
 * Created by PhpStorm.
 * User: bvanhoekelen
 * Date: 13-03-17
 * Time: 21:35
 */
interface PerformanceInterface
{
    /*
     * Set measuring point X
     *
     * @param string|null   $label
     * @return void
     */
    public static function point($label = null);

    /*
     * Finish measuring point
     *
     * @return void
     */
    public static function finish();

    /*
     * Return test results
     *
     * @return mixed
     */
    public static function results();

}

<?php namespace Performance\Lib;

/**
 * Created by PhpStorm.
 * User: bvanhoekelen
 * Date: 13-03-17
 * Time: 21:35
 */
interface PerformanceInterface
{
    /*
     * Set measuring point X
     *
     * @param string|null   $label
     * @return void
     */
    public static function point($label = null);

    /*
     * Finish measuring point
     *
     * @return void
     */
    public static function finish();

    /*
     * Return test results
     *
     * @return mixed
     */
    public static function results();

    /*
     * Change config items
     *
     * @param
     * @return mixed
     */
    public static function config($configItem);

    /*
     * Change single config item
     *
     * @param string    $item
     * @param mixed     $value
     * @return mixed
     */
    public static function changeConfig($item, $value);

}

Add config and changeConfig to interface


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Elasticsearch;

use App\Console\Helpers\Indexer;

class UninstallSearch extends Command
{

    use Indexer;

    protected $signature = 'search:uninstall {prefix? : The prefixes of the indexes to delete} {--y|yes : Answer "yes" to all prompts confirming to delete index}';

    protected $description = 'Tear down the Search Service indexes';

    /**
     * The prefix of the indexes to delete.
     *
     * @var string
     */
    protected $prefix;

    public function __construct()
    {

        parent::__construct();
        $this->prefix = env('ELASTICSEARCH_INDEX_PREFIX', 'test_');

    }

    public function handle()
    {

        if ($this->argument('prefix'))
        {

            $this->prefix = $this->argument('prefix');

        }

        if (!$this->option('yes') && !$this->confirm("This will delete all indexes that begin with the prefix " .$this->prefix .". Do you wish to continue?"))
        {

            return false;

        }

        foreach (allModelsThatUse(\App\Models\ElasticSearchable::class) as $model)
        {

            $endpoint = endpointFor($model);
            $index = $this->prefix .$endpoint;

            $params = [
                'index' => $index,
            ];

            if (Elasticsearch::indices()->exists($params))
            {

                $return = Elasticsearch::indices()->delete($params);

                $this->info($this->done($return));

            }
            else
            {

                $this->info("Index " .$index . " does not exist.");

            }

        }

    }

}

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Elasticsearch;

use App\Console\Helpers\Indexer;

class UninstallSearch extends Command
{

    use Indexer;

    protected $signature = 'search:uninstall {index? : The group of indexes to delete} {--y|yes : Answer "yes" to all prompts confirming to delete index}';

    protected $description = 'Tear down the Search Service indexes';

    /**
     * The prefix of the indexes to delete.
     *
     * @var string
     */
    protected $index;

    public function __construct()
    {

        parent::__construct();
        $this->index = env('ELASTICSEARCH_INDEX', 'test_');

    }

    public function handle()
    {

        if ($this->argument('index'))
        {

            $this->index = $this->argument('index');

        }

        if (!$this->option('yes') && !$this->confirm("This will delete all indexes that are a part of the " .$this->index ." alias. Do you wish to continue?"))
        {

            return false;

        }

        foreach (allModelsThatUse(\App\Models\ElasticSearchable::class) as $model)
        {

            $endpoint = endpointFor($model);
            $index = $this->index .'-' .$endpoint;

            $this->info('Deleting ' .$index .' index...');

            $params = [
                'index' => $index,
            ];

            if (Elasticsearch::indices()->exists($params))
            {

                $return = Elasticsearch::indices()->delete($params);

                $this->info($this->done($return));

            }
            else
            {

                $this->info("Index " .$index . " does not exist.");

            }

        }

    }

}

Add support for proper aliasing

Add support for proper aliasing


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use \GuzzleHttp\Client as Guzzle;

class PagesController extends Controller
{
	public function index()
	{
		$popularTitles = $this->getPopularTitles();

		return view('pages.index')
			->with([
				'popularTitles' => $popularTitles->results,
				'config' => $this->config
			]);
    }

	private function getPopularTitles()
	{
		$movies = (new Guzzle())->get('http://api.themoviedb.org/3/movie/popular?api_key=' . $this->apiKey);

		return json_decode($movies->getBody());
	}
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use \GuzzleHttp\Client as Guzzle;

class PagesController extends Controller
{
	public function index()
	{
		return view('pages.index')
			->with([
				'popularTitles' => MovieController::getPopularTitles(),
				'config' => $this->config
			]);
    }
}

Remove method from pages controller

Remove method from pages controller


<?php

use Phpcq\Config\BuildConfigInterface;
use Phpcq\Plugin\ConfigurationPluginInterface;

return new class implements ConfigurationPluginInterface {
    public function getName() : string
    {
        return 'phpunit';
    }

    public function validateConfig(array $config) : void
    {
    }

    public function processConfig(array $config, BuildConfigInterface $buildConfig) : iterable
    {
        yield $buildConfig
            ->getTaskFactory()
            ->buildRunPhar('phpunit')
            ->withWorkingDirectory($buildConfig->getProjectConfiguration()->getProjectRootPath())
            ->build();
    }
};

<?php

use Phpcq\Config\BuildConfigInterface;
use Phpcq\Plugin\ConfigurationPluginInterface;

return new class implements ConfigurationPluginInterface {
    public function getName() : string
    {
        return 'phpunit';
    }

    private static $knownConfigKeys = [
        'custom_flags' => 'custom_flags'
    ];

    public function validateConfig(array $config) : void
    {
        // Fix: we do not use the directories in this task, so we do not want to bail on them.
        unset($config['directories']);
        if ($diff = array_diff_key($config, self::$knownConfigKeys)) {
            throw new \Phpcq\Exception\RuntimeException(
                'Unknown config keys encountered: ' . implode(', ', array_keys($diff))
            );
        }
    }

    public function processConfig(array $config, BuildConfigInterface $buildConfig) : iterable
    {
        yield $buildConfig
            ->getTaskFactory()
            ->buildRunPhar('phpunit')
            ->withWorkingDirectory($buildConfig->getProjectConfiguration()->getProjectRootPath())
            ->build();
    }
};

Implement draft of config validation for phpunit


<?php

/*
 * This file is part of the pinepain/php-weak PHP extension.
 *
 * Copyright (c) 2016 Bogdan Padalko <zaq178miami@gmail.com>
 *
 * Licensed under the MIT license: http://opensource.org/licenses/MIT
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code or visit http://opensource.org/licenses/MIT
 */

namespace Weak;

class Reference
{
    /**
     * @param object        $referent Referent object
     * @param callable|null $notify   Callback to notify when referent object destroyed.
     *
     * Callback will receive current Weak\Reference object as a first argument. Note, that referent object at that time
     * will be already destroyed.
     */
    public function __construct(object $referent, callable $notify = null)
    {
    }

    /**
     * Get referent object
     *
     * @return object | null
     */
    public function get()
    {
    }

    /**
     * Whether referent object exists
     *
     * @return bool
     */
    public function valid() : bool
    {
    }
}

<?php

/*
 * This file is part of the pinepain/php-weak PHP extension.
 *
 * Copyright (c) 2016 Bogdan Padalko <zaq178miami@gmail.com>
 *
 * Licensed under the MIT license: http://opensource.org/licenses/MIT
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code or visit http://opensource.org/licenses/MIT
 */

namespace Weak;

class Reference
{
    /**
     * @param object                  $referent Referent object
     * @param callable | array | null $notify   Optional notifier to signal when referent object destroyed.
     *
     * If notifier is callback, it will be called with a current Weak\Reference object as a first argument. Note, that
     * referent object at that time will be already destroyed. Callback will not be called if referent object destructor
     * or previous notify callback throws exception.
     *
     * If notifier is array, current Weak\Reference object will be appended to it regardless any exception thrown by
     * referent object destructor or previous notify callback.
     */
    public function __construct(object $referent, $notify = null)
    {
    }

    /**
     * Get referent object
     *
     * @return object | null
     */
    public function get()
    {
    }

    /**
     * Whether referent object exists
     *
     * @return bool
     */
    public function valid() : bool
    {
    }

    /**
     * Get notifier
     *
     * @param callable | array | null $notify Notifier to replace existent notifier with. Same as in constructor.
     *
     * If any value provided, any existent notifier will be replaced and returned.
     *
     * @return callable | array | null Current notifier or the old one when replacing it with provided value.
     */
    public function notifier($notify = null)
    {
    }
}

Add array notifier and ability to change existent notifier


<?php
if (!defined('PHPUnit2_MAIN_METHOD')) {
    define('PHPUnit2_MAIN_METHOD', 'AllTests::main');
}

require_once 'PHPUnit2/Framework/TestSuite.php';
require_once 'PHPUnit2/TextUI/TestRunner.php';

/**
 * Read in user-defined test configuration if available; otherwise, read default test configuration
 */
if (is_readable('TestConfiguration.php')) {
    require_once 'TestConfiguration.php';
} else {
    require_once 'TestConfiguration.php.dist';
}

require_once 'ZendTest.php';
require_once 'Zend/AllTests.php';

class AllTests
{
    public static function main()
    {
        PHPUnit2_TextUI_TestRunner::run(self::suite());
    }

    public static function suite()
    {
        $suite = new PHPUnit2_Framework_TestSuite('Zend Framework');

        $suite->addTestSuite('ZendTest');

        $suite->addTest(Zend_AllTests::suite());

        return $suite;
    }
}

if (PHPUnit2_MAIN_METHOD == 'AllTests::main') {
    AllTests::main();
}

<?php
if (!defined('PHPUnit2_MAIN_METHOD')) {
    define('PHPUnit2_MAIN_METHOD', 'AllTests::main');
}

require_once 'PHPUnit2/Framework/TestSuite.php';
require_once 'PHPUnit2/TextUI/TestRunner.php';

/**
 * Read in user-defined test configuration if available; otherwise, read default test configuration
 */
if (is_readable('TestConfiguration.php')) {
    require_once 'TestConfiguration.php';
} else {
    require_once 'TestConfiguration.php.dist';
}

/**
 * Prepend library/ to the include_path.  This allows the tests to run out of the box and
 * helps prevent finding other copies of the framework that might be present.
 */
set_include_path(get_include_path() . PATH_SEPARATOR
                 . dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'library');

require_once 'ZendTest.php';
require_once 'Zend/AllTests.php';

class AllTests
{
    public static function main()
    {
        PHPUnit2_TextUI_TestRunner::run(self::suite());
    }

    public static function suite()
    {
        $suite = new PHPUnit2_Framework_TestSuite('Zend Framework');

        $suite->addTestSuite('ZendTest');

        $suite->addTest(Zend_AllTests::suite());

        return $suite;
    }
}

if (PHPUnit2_MAIN_METHOD == 'AllTests::main') {
    AllTests::main();
}

Call set_include_path() to allow tests to run out of the box.

git-svn-id: b6e219894c353fb1d215c78b2075057d8daadfba@569 44c647ce-9c0f-0410-b52a-842ac1e357ba