<?php

namespace PHPSpec2\Diff;

class Diff
{
    private $engines = array();

    public function addEngine(EngineInterface $engine)
    {
        $this->engines[] = $engine;
    }

    public function compare($expected, $actual)
    {
        foreach ($this->engines as $engine) {
            if ($engine->supports($expected, $actual)) {
                return trim($engine->compare($expected, $actual));
            }
        }

        return null;
    }
}

<?php

namespace PHPSpec2\Diff;

class Diff
{
    private $engines = array();

    public function addEngine(EngineInterface $engine)
    {
        $this->engines[] = $engine;
    }

    public function compare($expected, $actual)
    {
        foreach ($this->engines as $engine) {
            if ($engine->supports($expected, $actual)) {
                return rtrim($engine->compare($expected, $actual));
            }
        }

        return null;
    }
}

Trim diffs only on the right side

Trim diffs only on the right side


<?php defined('SYSPATH') OR die('No direct script access.');

/**
* Logs actions performed in the CMS.
*
* @package	Sledge
* @category	Models
* @author	Rob Taylor
* @copyright	Hoop Associates
*
*/
class Sledge_Model_Activity extends ORM
{
	protected $_table_columns = array(
		'id'			=>	'',
		'remotehost'	=>	'',
		'description'	=>	'',
		'note'		=>	'',
		'person'		=>	'',
		'time'		=>	'',
	);
}

<?php defined('SYSPATH') OR die('No direct script access.');

/**
* Logs actions performed in the CMS.
*
* @package	Sledge
* @category	Models
* @author	Rob Taylor
* @copyright	Hoop Associates
*
*/
class Sledge_Model_Activity extends ORM
{
	protected $_table_columns = array(
		'id'			=>	'',
		'remotehost'	=>	'',
		'description'	=>	'',
		'note'		=>	'',
		'person_id'	=>	'',
		'time'		=>	'',
	);
}

Fix column name in activity model

Fix column name in activity model


Add hr to sponsors list

Add hr to sponsors list


<?php
namespace SlimApi\Generator;

interface GeneratorInterface
{
    /**
     * Validate names and fields provided
     *
     * @param string $name
     * @param array $fields
     *
     * @return bool are name/fields valid
     */
    public function validate($name, $fields);

    /**
     * Process the fields as required
     *
     * @param string $name
     * @param array $fields
     *
     * @return void
     */
    public function process($name, $fields);
}

<?php
namespace SlimApi\Generator;

interface GeneratorInterface
{
    /**
     * Validate names and fields provided
     *
     * @param string $name
     * @param array $fields
     *
     * @return bool are name/fields valid
     */
    public function validate($name, $fields);

    /**
     * Process the fields as required
     *
     * @param string $name
     * @param array $fields
     * @param array $options
     *
     * @return void
     */
    public function process($name, $fields, $options);
}

Make options part of the interface

Make options part of the interface


<?php
$data = Kwf_Registry::get('db')->query('SELECT * FROM `kwc_basic_image` WHERE data like \'%preview_image":true%\'')->fetchAll();
foreach ($data as $row) {
    $component = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($row['component_id'], array('ignoreVisible' => false));
    if ($component) {
        if ($component->componentClass != 'Kwc_Basic_LinkTag_Empty_Component') {
            if ($component->getComponent()->getRow()->kwf_upload_id) {
                //d($component->componentClass);
                $components[$component->getAbsoluteUrl()] = 'getAbsoluteUrl().'">'.$component->getAbsoluteUrl().'';
            }
        }
//         $components[] = $component->getUrl();
    }
}
d(array_values($components));

<?php
/**
 * Just copy this into your bootstrap to find out which components have to be checked
 * It's returning a list of every page containing a component with alternative preview-image
 */
$data = Kwf_Registry::get('db')->query('SELECT * FROM `kwc_basic_image` WHERE data like \'%preview_image":true%\'')->fetchAll();
foreach ($data as $row) {
    $component = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($row['component_id'], array('ignoreVisible' => false));
    if ($component) {
        if ($component->componentClass != 'Kwc_Basic_LinkTag_Empty_Component') {
            if ($component->getComponent()->getRow()->kwf_upload_id) {
                //d($component->componentClass);
                $components[$component->getAbsoluteUrl()] = 'getAbsoluteUrl().'">'.$component->getAbsoluteUrl().'';
            }
        }
//         $components[] = $component->getUrl();
    }
}
d(array_values($components));

Add comment to script to describe what this script is good for


<?php

namespace FluxBB\Markdown\Parser;

use FluxBB\Markdown\Common\Text;
use FluxBB\Markdown\Node\CodeBlock;

class FencedCodeBlockParser extends AbstractParser
{

    /**
     * Parse the given block content.
     *
     * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
     * in the chain.
     *
     * @param Text $block
     * @return void
     */
    public function parseBlock(Text $block)
    {
        $block->handle('{
            (?:\n\n|\A)
            (?:
                ([`~]{3})[ ]*         #1 fence ` or ~
                    ([a-zA-Z0-9]*?)?  #2 language [optional]
                \n+
                (.*?)\n                #3 code block
                \1                    # matched #1
            )
        }smx', function (Text $w, Text $fence, Text $lang, Text $code) {
            $code->escapeHtml(ENT_NOQUOTES);

            /*$this->markdown->emit('detab', array($code));
            $code->replace('/\A\n+/', '');
            $code->replace('/\s+\z/', '');*/

            $this->stack->acceptCodeBlock(new CodeBlock($code));
        }, function (Text $part) {
            $this->next->parseBlock($part);
        });
    }

}

<?php

namespace FluxBB\Markdown\Parser;

use FluxBB\Markdown\Common\Text;
use FluxBB\Markdown\Node\CodeBlock;

class FencedCodeBlockParser extends AbstractParser
{

    /**
     * Parse the given block content.
     *
     * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
     * in the chain.
     *
     * @param Text $block
     * @return void
     */
    public function parseBlock(Text $block)
    {
        $block->handle('{
            (?:\n\n|\A)
            (?:
                (                     #1 fence
                    ([`~])            #2 the fence character (` or ~)
                    \2{2,}            # at least two remaining fence characters
                )
                [ ]*
                ([a-zA-Z0-9]*?)?      #3 code language [optional]
                \n+
                (.*?)\n               #4 code block
                \1\2*                 # closing fence - at least as long as the opening one
            )
        }smx', function (Text $whole, Text $fence, Text $fenceChar, Text $lang, Text $code) {
            $code->escapeHtml(ENT_NOQUOTES);

            /*$this->markdown->emit('detab', array($code));
            $code->replace('/\A\n+/', '');
            $code->replace('/\s+\z/', '');*/

            $this->stack->acceptCodeBlock(new CodeBlock($code));
        }, function (Text $part) {
            $this->next->parseBlock($part);
        });
    }

}

Improve fenced code block parser's handling of closing fences.


<?php

use App\Controllers\HomeController;
use App\Controllers\LeadController;
use App\Controllers\ThanksController;

$app->get('/', HomeController::class.':index');

$app->post('/store', LeadController::class.':store');

$app->get('/thanks', ThanksController::class.':index');

<?php

use App\Controllers\HomeController;
use App\Controllers\LeadController;
use App\Controllers\ThanksController;

$app->get('/', HomeController::class.':index')->setName('home');
$app->post('/store', LeadController::class.':store')->setName('store');
$app->get('/thanks', ThanksController::class.':index')->setName('thanks');

Set names to default routes.

Set names to default routes.


<?php

class Author extends Eloquent {

    /**
     * Database table used by model
     */
    protected $table = 'authors';

    /**
     * Class Constants
     */

    const SHOW_NAME = 10;
    const SHOW_NICK = 20;
    const SHOW_BOTH = 30;

    public function user()
    {
        return $this->belongsTo('User');
    }
}

<?php

class Author extends Eloquent {

    /**
     * Database table used by model
     */
    protected $table = 'authors';

    /**
     * Class Constants
     */

    const SHOW_NAME = 10;
    const SHOW_NICK = 20;
    const SHOW_BOTH = 30;

    /**
     * Author belongsTo User
     */
        public function user()
    {
        return $this->belongsTo('User');
    }
}

Add comment for relationship function

Add comment for relationship function


<?php

namespace Gos\Bundle\PubSubRouterBundle\DependencyInjection;

use Gos\Bundle\PubSubRouterBundle\Generator\Generator;
use Gos\Bundle\PubSubRouterBundle\Matcher\Matcher;
use Gos\Bundle\PubSubRouterBundle\Router\Router;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * @author Johann Saunier <johann_27@hotmail.fr>
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('gos_pubsub_router');

        $rootNode
            ->addDefaultsIfNotSet()
            ->children()
                ->scalarNode('matcher_class')->defaultValue(Matcher::class)->end()
                ->scalarNode('generator_class')->defaultValue(Generator::class)->end()
                ->scalarNode('router_class')->defaultValue(Router::class)->end()
                ->arrayNode('routers')
                    ->useAttributeAsKey('name')
                    ->requiresAtLeastOneElement()
                    ->prototype('array')
                        ->children()
                            ->arrayNode('resources')
                                ->prototype('scalar')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ->end();

        return $treeBuilder;
    }
}

<?php

namespace Gos\Bundle\PubSubRouterBundle\DependencyInjection;

use Gos\Bundle\PubSubRouterBundle\Generator\Generator;
use Gos\Bundle\PubSubRouterBundle\Matcher\Matcher;
use Gos\Bundle\PubSubRouterBundle\Router\Router;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * @author Johann Saunier <johann_27@hotmail.fr>
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('gos_pubsub_router');

        if (method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->getRootNode();
        } else {
            // BC layer for symfony/config 4.1 and older
            $rootNode = $treeBuilder->root('gos_pubsub_router');

        $rootNode
            ->addDefaultsIfNotSet()
            ->children()
                ->scalarNode('matcher_class')->defaultValue(Matcher::class)->end()
                ->scalarNode('generator_class')->defaultValue(Generator::class)->end()
                ->scalarNode('router_class')->defaultValue(Router::class)->end()
                ->arrayNode('routers')
                    ->useAttributeAsKey('name')
                    ->requiresAtLeastOneElement()
                    ->prototype('array')
                        ->children()
                            ->arrayNode('resources')
                                ->prototype('scalar')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ->end();

        return $treeBuilder;
    }
}

Update config for Symfony 4.2 change

Update config for Symfony 4.2 change


<?= '<?php' ?>

namespace {{$namespace}};

use Chalcedonyt\QueryBuilderTemplate\Templates\Factory\AbstractTemplateFactory;

class {{$classname}} extends AbstractTemplateFactory
{
@if (count($parameters))
@foreach( $parameters as $param)
    /**
    * @var {{$param['class']}}
    */
    protected ${{camel_case($param['name'])}};

@endforeach
@endif
    /**
    *
@if (!count($parameters))
    * Set properties here for a parameterized factory.
@else
@foreach( $parameters as $param)
    *  @param {{$param['class']}} ${{camel_case($param['name'])}}
@endforeach
@endif
    *
    */
    public function __construct({{$parameter_string}})
    {
@if (count($parameters))
@foreach( $parameters as $param)
        $this -> {{camel_case($param['name'])}} = ${{$param['name']}};
@endforeach
@endif
    }

    /**
     * The base query. DB::table and ::select should be set here
     * @return Builder
     */
    protected function getBaseQuery()
    {
        //return DB::table('users') -> select('users.*');
    }

    /**
     * Possible Joins to make depending on the ScopeInterface objects added.
     * @return Array of Illuminate\Database\Query\JoinClause
     */
    protected function getAvailableJoinClauses(){
        /*join with the survey table
        $post_join = new JoinClause('inner','posts');
        $post_join -> on('post.user_id','=','users.id');

        return [
            $post_join
        ];*/

        return [];
    }
}
?>

<?= '<?php' ?>

namespace {{$namespace}};

use Chalcedonyt\QueryBuilderTemplate\Templates\Factory\AbstractTemplateFactory;
use DB;
use Illuminate\Database\Query\JoinClause;
class {{$classname}} extends AbstractTemplateFactory
{
@if (count($parameters))
@foreach( $parameters as $param)
    /**
    * @var {{$param['class']}}
    */
    protected ${{camel_case($param['name'])}};

@endforeach
@endif
    /**
    *
@if (!count($parameters))
    * Set properties here for a parameterized factory.
@else
@foreach( $parameters as $param)
    *  @param {{$param['class']}} ${{camel_case($param['name'])}}
@endforeach
@endif
    *
    */
    public function __construct({{$parameter_string}})
    {
@if (count($parameters))
@foreach( $parameters as $param)
        $this -> {{camel_case($param['name'])}} = ${{$param['name']}};
@endforeach
@endif
    }

    /**
     * The base query. DB::table and ::select should be set here
     * @return Builder
     */
    protected function getBaseQuery()
    {
        //return DB::table('users') -> select('users.*');
    }

    /**
     * Possible Joins to make depending on the ScopeInterface objects added.
     * @return Array of Illuminate\Database\Query\JoinClause
     */
    protected function getAvailableJoinClauses(){
        /*join with the survey table
        $post_join = new JoinClause('inner','posts');
        $post_join -> on('post.user_id','=','users.id');

        return [
            $post_join
        ];*/

        return [];
    }
}
?>

Include DB and JoinClause in the template factory generator view


<?php
namespace Neos\Flow\Http;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Core\Bootstrap;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Central authority to get hold of the active HTTP request.
 * When no active HTTP request can be determined (for example in CLI context) a new instance is built using a ServerRequestFactoryInterface implementation
 *
 * @Flow\Scope("singleton")
 */
final class ActiveHttpRequestProvider
{
    /**
     * @Flow\Inject
     * @var Bootstrap
     */
    protected $bootstrap;

    /**
     * @Flow\Inject
     * @var BaseUriProvider
     */
    protected $baseUriProvider;

    /**
     * @Flow\Inject
     * @var ServerRequestFactoryInterface
     */
    protected $serverRequestFactory;

    /**
     * Returns the currently active HTTP request, if available.
     * If the HTTP request can't be determined, a new instance is created using an instance of ServerRequestFactoryInterface
     *
     * @return ServerRequestInterface
     */
    public function getActiveHttpRequest(): ServerRequestInterface
    {
        $requestHandler = $this->bootstrap->getActiveRequestHandler();
        if ($requestHandler instanceof HttpRequestHandlerInterface) {
            return $requestHandler->getHttpRequest();
        }
        try {
            $baseUri = $this->baseUriProvider->getConfiguredBaseUriOrFallbackToCurrentRequest();
        } catch (Exception $e) {
            $baseUri = 'http://localhost';
        }
        return $this->serverRequestFactory->createServerRequest('GET', $baseUri);
    }
}

<?php
namespace Neos\Flow\Http;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Core\Bootstrap;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Central authority to get hold of the active HTTP request.
 * When no active HTTP request can be determined (for example in CLI context) a new instance is built using a ServerRequestFactoryInterface implementation
 *
 * Note: Naturally this class is not being used explicitly. But it is configured as factory for Psr\Http\Message\ServerRequestInterface instances
 *
 * @Flow\Scope("singleton")
 */
final class ActiveHttpRequestProvider
{
    /**
     * @Flow\Inject
     * @var Bootstrap
     */
    protected $bootstrap;

    /**
     * @Flow\Inject
     * @var BaseUriProvider
     */
    protected $baseUriProvider;

    /**
     * @Flow\Inject
     * @var ServerRequestFactoryInterface
     */
    protected $serverRequestFactory;

    /**
     * Returns the currently active HTTP request, if available.
     * If the HTTP request can't be determined, a new instance is created using an instance of ServerRequestFactoryInterface
     *
     * @return ServerRequestInterface
     */
    public function getActiveHttpRequest(): ServerRequestInterface
    {
        $requestHandler = $this->bootstrap->getActiveRequestHandler();
        if ($requestHandler instanceof HttpRequestHandlerInterface) {
            return $requestHandler->getHttpRequest();
        }
        try {
            $baseUri = $this->baseUriProvider->getConfiguredBaseUriOrFallbackToCurrentRequest();
        } catch (Exception $e) {
            $baseUri = 'http://localhost';
        }
        return $this->serverRequestFactory->createServerRequest('GET', $baseUri);
    }
}

Add comment about Provider not being used in userland code


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authorization\Voter;

use Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchy;

class RoleHierarchyVoterTest extends RoleVoterTest
{
    /**
     * @dataProvider getVoteTests
     */
    public function testVote($roles, $attributes, $expected)
    {
        $voter = new RoleHierarchyVoter(new RoleHierarchy(array('ROLE_FOO' => array('ROLE_FOOBAR'))));

        $this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
    }

    public function getVoteTests()
    {
        return array_merge(parent::getVoteTests(), array(
            array(array('ROLE_FOO'), array('ROLE_FOOBAR'), VoterInterface::ACCESS_GRANTED),
        ));
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authorization\Voter;

use Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchy;

class RoleHierarchyVoterTest extends RoleVoterTest
{
    /**
     * @dataProvider getVoteTests
     */
    public function testVote($roles, $attributes, $expected)
    {
        $voter = new RoleHierarchyVoter(new RoleHierarchy(array('ROLE_FOO' => array('ROLE_FOOBAR'))));

        $this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
    }

    public function getVoteTests()
    {
        return array_merge(parent::getVoteTests(), array(
            array(array('ROLE_FOO'), array('ROLE_FOOBAR'), VoterInterface::ACCESS_GRANTED),
        ));
    }

    /**
     * @dataProvider getVoteWithEmptyHierarchyTests
     */
    public function testVoteWithEmptyHierarchy($roles, $attributes, $expected)
    {
        $voter = new RoleHierarchyVoter(new RoleHierarchy(array()));

        $this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
    }

    public function getVoteWithEmptyHierarchyTests()
    {
        return parent::getVoteTests();
    }
}

[SecurityBundle] Fix disabling of RoleHierarchyVoter when passing empty hierarchy


<?php

namespace Galahad\LaravelAddressing;

use ArrayObject;
use IteratorAggregate;
use Traversable;

/**
 * Class Collection
 *
 * @package Galahad\LaravelAddressing
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class Collection implements IteratorAggregate
{
    /**
     * @var ArrayObject
     */
    private $items;

    /**
     * The construct method
     */
    public function __construct()
    {
        $this->items = new ArrayObject();
    }

    /**
     * Retrieve an external iterator
     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
     * @return Traversable An instance of an object implementing Iterator or
     * Traversable
     * @since 5.0.0
     */
    public function getIterator()
    {
        return new Iterator($this->items);
    }

    /**
     * Insert a new element in the collection
     *
     * @param $value
     */
    public function insert($value)
    {
        $this->items->append($value);
    }

    /**
     * Get the items count
     *
     * @return int
     */
    public function count()
    {
        return $this->items->count();
    }
}

<?php

namespace Galahad\LaravelAddressing;

use ArrayObject;
use IteratorAggregate;
use Traversable;

/**
 * Class Collection
 *
 * @package Galahad\LaravelAddressing
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class Collection implements IteratorAggregate
{
    /**
     * @var ArrayObject
     */
    private $items;

    /**
     * The construct method
     */
    public function __construct()
    {
        $this->items = new ArrayObject();
    }

    /**
     * Retrieve an external iterator
     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
     * @return Traversable An instance of an object implementing Iterator or
     * Traversable
     * @since 5.0.0
     */
    public function getIterator()
    {
        return new Iterator($this->items);
    }

    /**
     * Insert a new element in the collection
     *
     * @param mixed $value
     */
    public function insert($value)
    {
        if (is_array($value)) {
            foreach ($value as $val) {
                $this->items->append($val);
            }
            return;
        }
        $this->items->append($value);
    }

    /**
     * Get the items count
     *
     * @return int
     */
    public function count()
    {
        return $this->items->count();
    }
}

Add option to insert multiple elements at the same time


<?php

/**
* SpinDash — A web development framework
* © 2007–2015 Ilya I. Averkov
*
* Contributors:
* Irfan Mahfudz Guntur <ayes@bsmsite.com>
* Evgeny Bulgakov <evgeny@webline-masters.ru>
*/

namespace SpinDash\Http;

final class Response
{
	private $status_code = 200;
	private $body = '';

	public function setBody($data) {
		$this->body = $data;
	}

	public function statusCodeDescription() {
		switch($this->status_code) {
			case 404: return 'Not Found'; break;
			default: return 'OK'; break;
		}
	}

	public function sendBasic() {
		if($this->status_code !== 200) {
			header("HTTP/1.1  {$this->status_code} " . $this->statusCodeDescription());
		}
		echo $this->body;
	}

	public function sendPHPSGI() {
		return ["{$this->status_code} " . $this->statusCodeDescription(), ['Content-Type' => 'text/html'], $this->body];
	}

	public function setStatusCode($code) {
		$this->code = $code;
	}
}

<?php

/**
* SpinDash — A web development framework
* © 2007–2015 Ilya I. Averkov
*
* Contributors:
* Irfan Mahfudz Guntur <ayes@bsmsite.com>
* Evgeny Bulgakov <evgeny@webline-masters.ru>
*/

namespace SpinDash\Http;

final class Response
{
	private $code = 200;
	private $body = '';

	public function setBody($data) {
		$this->body = $data;
	}

	public function statusCodeDescription() {
		switch($this->code) {
			case 404: return 'Not Found'; break;
			default: return 'OK'; break;
		}
	}

	public function sendBasic() {
		if($this->code !== 200) {
			header("HTTP/1.1  {$this->code} " . $this->statusCodeDescription());
		}
		echo $this->body;
	}

	public function sendPHPSGI() {
		return ["{$this->code} " . $this->statusCodeDescription(), ['Content-Type' => 'text/html'], $this->body];
	}

	public function setStatusCode($code) {
		$this->code = $code;
	}
}

Send proper 404 code: fix

Send proper 404 code: fix


<?php

namespace League\Plates\Extension;

class BatchTest extends \PHPUnit_Framework_TestCase
{
    private $extension;

    public function setUp()
    {
        $this->extension = new Batch;
        $this->extension->engine = new \League\Plates\Engine();
        $this->extension->template = new \League\Plates\Template($this->extension->engine);
    }

    public function testCanCreateExtension()
    {
        $this->assertInstanceOf('League\Plates\Extension\Batch', $this->extension);
    }

    public function testGetFunctionsReturnsAnArray()
    {
        $this->assertInternalType('array', $this->extension->getFunctions());
    }

    public function testGetFunctionsReturnsAtLeastOneRecord()
    {
        $this->assertTrue(count($this->extension->getFunctions()) > 0);
    }

    public function testRunBatch()
    {
        $this->assertTrue($this->extension->runBatch('Sweet ', 'trim') === 'Sweet');
        $this->assertTrue($this->extension->runBatch('Jonathan', 'strtoupper|strtolower') === 'jonathan');
        $this->assertTrue($this->extension->runBatch('Jonathan', 'e|strtolower') === 'jonathan');
    }
}

<?php

namespace League\Plates\Extension;

class BatchTest extends \PHPUnit_Framework_TestCase
{
    private $extension;

    public function setUp()
    {
        $this->extension = new Batch;
        $this->extension->engine = new \League\Plates\Engine();
        $this->extension->template = new \League\Plates\Template($this->extension->engine);
    }

    public function testCanCreateExtension()
    {
        $this->assertInstanceOf('League\Plates\Extension\Batch', $this->extension);
    }

    public function testGetFunctionsReturnsAnArray()
    {
        $this->assertInternalType('array', $this->extension->getFunctions());
    }

    public function testGetFunctionsReturnsAtLeastOneRecord()
    {
        $this->assertTrue(count($this->extension->getFunctions()) > 0);
    }

    public function testRunBatch()
    {
        $this->assertTrue($this->extension->runBatch('Sweet ', 'trim') === 'Sweet');
        $this->assertTrue($this->extension->runBatch('Jonathan', 'strtoupper|strtolower') === 'jonathan');
        $this->assertTrue($this->extension->runBatch('Jonathan', 'e|strtolower') === 'jonathan');
    }

    public function testRunBatchException()
    {
        $this->setExpectedException('LogicException');
        $this->assertTrue($this->extension->runBatch('Jonathan', 'somefunctionthatwillneverexist'));
    }
}

Add one more test for the Batch Extension.


<?php
/*
 * Copyright 2017 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
 */

namespace Coast\Transformer\Rule;

use Coast;
use Coast\Transformer\Rule;

class NullType extends Rule
{
    protected function _transform($value)
    {
        if (!is_scalar($value)) {
            return $value;
        }
        if (!strlen($value)) {
            $value = null;
        }
        return $value;
    }
}

<?php
/*
 * Copyright 2017 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
 */

namespace Coast\Transformer\Rule;

use Coast;
use Coast\Transformer\Rule;

class NullType extends Rule
{
    protected function _transform($value)
    {
        if (!is_string($value)) {
            return $value;
        }
        if (strlen($value) == 0) {
            $value = null;
        }
        return $value;
    }
}

Tweak behaviour of Null transformer

Tweak behaviour of Null transformer


<?php
/**
 * This file is part of PMG\Queue
 *
 * Copyright (c) PMG <https://www.pmg.com>
 *
 * For full copyright information see the LICENSE file distributed
 * with this source code.
 *
 * @license     http://opensource.org/licenses/Apache-2.0 Apache-2.0
 */

namespace PMG\Queue;

abstract class UnitTestCase extends \PHPUnit_Framework_TestCase
{
    protected function skipIfPhp7()
    {
        if (self::isPhp7()) {
            $this->markTestSkipped(sprintf('PHP < 7.X is required, have %s', PHP_VERSION));
        }
    }

    protected function skipIfPhp5()
    {
        if (!self::isPhp7()) {
            $this->markTestSkipped(sprintf('PHP 5.X is required, have %s', PHP_VERSION));
        }
    }

    protected static function isPhp7()
    {
        return PHP_VERSION_ID >= 70000;
    }
}

<?php
/**
 * This file is part of PMG\Queue
 *
 * Copyright (c) PMG <https://www.pmg.com>
 *
 * For full copyright information see the LICENSE file distributed
 * with this source code.
 *
 * @license     http://opensource.org/licenses/Apache-2.0 Apache-2.0
 */

namespace PMG\Queue;

abstract class UnitTestCase extends \PHPUnit_Framework_TestCase
{
    protected function skipIfPhp7()
    {
        if (self::isPhp7()) {
            $this->markTestSkipped(sprintf('PHP < 7.X is required, have %s', PHP_VERSION));
        }
    }

    protected function skipIfPhp5()
    {
        if (!self::isPhp7()) {
            $this->markTestSkipped(sprintf('PHP 7.X is required, have %s', PHP_VERSION));
        }
    }

    protected static function isPhp7()
    {
        return PHP_VERSION_ID >= 70000;
    }
}

Correct the Message in `skipIfPhp5`

Correct the Message in `skipIfPhp5`

Which said something non-sensical before.


<?php
/*
 * This file is part of the wp-magnify/core package.
 *
 * (c) Christopher Davis <http://christopherdavis.me>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

$testDir = getenv('WP_TESTS_DIR') ?: '/tmp/wordpress-tests-lib';
require_once $testDir.'/includes/functions.php';

function _manually_load_plugin() {
    require __DIR__.'/../magnify-core.php';
}

tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );

require $testDir.'/includes/bootstrap.php';
require_once __DIR__.'/MagnifyTestCase.php';

<?php
/*
 * This file is part of the wp-magnify/core package.
 *
 * (c) Christopher Davis <http://christopherdavis.me>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

$testDir = getenv('WP_TESTS_DIR') ?: '/tmp/wordpress-tests-lib';
require_once $testDir.'/includes/functions.php';

tests_add_filter('muplugins_loaded', function () {
    require __DIR__.'/../magnify-core.php';
});

require $testDir.'/includes/bootstrap.php';
require_once __DIR__.'/MagnifyTestCase.php';

Use an Anonymous Function for Loading the Plugin


<?php
namespace OC\Migrations;

use OCP\Migration\ISimpleMigration;
use OCP\Migration\IOutput;

/**
 * Disable enterprise_key app during the upgrade to 10.5.0
 */
class Version20200610110817 implements ISimpleMigration {

	/**
	 * @param IOutput $out
	 */
	public function run(IOutput $out) {
		$appManager = \OC::$server->getAppManager();
		if ($appManager->isInstalled('enterprise_key')) {
			$appManager->disableApp('enterprise_key');
			$out->warning('The enterprise_key app is deprecated and obsolete. It has been disabled.');
		}
	}
}

<?php
namespace OC\Migrations;

use OCP\Migration\ISimpleMigration;
use OCP\Migration\IOutput;

/**
 * Disable enterprise_key app during the upgrade to 10.5.0
 */
class Version20200610110817 implements ISimpleMigration {

	/**
	 * @param IOutput $out
	 */
	public function run(IOutput $out) {
		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
			// Do nothing if ownCloud isn't installed yet (initial installation)
			return;
		}

		$appManager = \OC::$server->getAppManager();
		if ($appManager->isInstalled('enterprise_key')) {
			$appManager->disableApp('enterprise_key');
			$out->warning('The enterprise_key app is deprecated and obsolete. It has been disabled.');
		}
	}
}

Fix a problem with the initial installation


<?php

namespace Swarrot\SwarrotBundle\Processor;

use Symfony\Component\Console\Input\InputInterface;

interface ProcessorConfiguratorInterface
{
    /**
     * Define extra parameters to the configurator.
     *
     * @param array $extras
     */
    public function setExtras(array $extras);

    /**
     * Retrieves the processor's class name and list of constructors arguments.
     *
     * @param array $options
     *
     * @return array
     */
    public function getProcessorArguments(array $options);

    /**
     * Retrieves the list of additional options to add to the CLI command.
     *
     * @return array
     */
    public function getCommandOptions();

    /**
     * Resolve user input parameters to returns an array of options.
     *
     * @param InputInterface $input
     *
     * @return array
     */
    public function resolveOptions(InputInterface $input);

    /**
     * @return bool
     */
    public function isEnabled();
}

<?php

namespace Swarrot\SwarrotBundle\Processor;

use Symfony\Component\Console\Input\InputInterface;

interface ProcessorConfiguratorInterface
{
    /**
     * Define extra parameters to the configurator.
     *
     * @param array $extras
     */
    public function setExtras(array $extras);

    /**
     * Retrieves the processor's class name and list of constructors arguments.
     * The class name should be first, and is mandatory.
     *
     * @param array $options
     *
     * @return array
     */
    public function getProcessorArguments(array $options);

    /**
     * Retrieves the list of additional options to add to the CLI command.
     *
     * @return array
     */
    public function getCommandOptions();

    /**
     * Resolve user input parameters to returns an array of options.
     *
     * @param InputInterface $input
     *
     * @return array
     */
    public function resolveOptions(InputInterface $input);

    /**
     * @return bool
     */
    public function isEnabled();
}

Add tip about getProcessorArguments implementation


<?php

namespace League\FactoryMuffin\Test;

use League\FactoryMuffin\Facade\FactoryMuffin;

class TestCase extends \PHPUnit_Framework_TestCase
{
    public static function setupBeforeClass()
    {
        FactoryMuffin::loadFactories(__DIR__ . '/factories');
        FactoryMuffin::setSaveMethod('save');
    }

    public static function tearDownAfterClass()
    {
        FactoryMuffin::deleteSaved();
    }
}

<?php

namespace League\FactoryMuffin\Test;

use League\FactoryMuffin\Facade\FactoryMuffin;

class TestCase extends \PHPUnit_Framework_TestCase
{
    public static function setupBeforeClass()
    {
        FactoryMuffin::loadFactories(__DIR__ . '/factories');
        FactoryMuffin::setSaveMethod('save');
    }

    public static function tearDownAfterClass()
    {
        FactoryMuffin::setDeleteMethod('delete');
        FactoryMuffin::deleteSaved();
    }
}

Set delete method just to show how it's done


<?php

/**
 * Validate all attributes in the tokens.
 */

class HTMLPurifier_Strategy_ValidateAttributes extends HTMLPurifier_Strategy
{

    /**
     * @param HTMLPurifier_Token[] $tokens
     * @param HTMLPurifier_Config $config
     * @param HTMLPurifier_Context $context
     * @return HTMLPurifier_Token[]
     */
    public function execute($tokens, $config, $context)
    {
        // setup validator
        $validator = new HTMLPurifier_AttrValidator();

        $token = false;
        $context->register('CurrentToken', $token);

        foreach ($tokens as $key => $token) {

            // only process tokens that have attributes,
            //   namely start and empty tags
            if (!$token instanceof HTMLPurifier_Token_Start && !$token instanceof HTMLPurifier_Token_Empty) {
                continue;
            }

            // skip tokens that are armored
            if (!empty($token->armor['ValidateAttributes'])) {
                continue;
            }

            // note that we have no facilities here for removing tokens
            $validator->validateToken($token, $config, $context);

            $tokens[$key] = $token; // for PHP 4
        }
        $context->destroy('CurrentToken');
        return $tokens;
    }
}

// vim: et sw=4 sts=4

<?php

/**
 * Validate all attributes in the tokens.
 */

class HTMLPurifier_Strategy_ValidateAttributes extends HTMLPurifier_Strategy
{

    /**
     * @param HTMLPurifier_Token[] $tokens
     * @param HTMLPurifier_Config $config
     * @param HTMLPurifier_Context $context
     * @return HTMLPurifier_Token[]
     */
    public function execute($tokens, $config, $context)
    {
        // setup validator
        $validator = new HTMLPurifier_AttrValidator();

        $token = false;
        $context->register('CurrentToken', $token);

        foreach ($tokens as $key => $token) {

            // only process tokens that have attributes,
            //   namely start and empty tags
            if (!$token instanceof HTMLPurifier_Token_Start && !$token instanceof HTMLPurifier_Token_Empty) {
                continue;
            }

            // skip tokens that are armored
            if (!empty($token->armor['ValidateAttributes'])) {
                continue;
            }

            // note that we have no facilities here for removing tokens
            $validator->validateToken($token, $config, $context);
        }
        $context->destroy('CurrentToken');
        return $tokens;
    }
}

// vim: et sw=4 sts=4

Remove PHP 4 compatibility hack.

Remove PHP 4 compatibility hack.

Signed-off-by: Edward Z. Yang <dbd597f5635f432486c5d365e9bb585b3eaa1853@mit.edu>


<?php namespace GeneaLabs\LaravelMixpanel\Providers;

use GeneaLabs\LaravelMixpanel\LaravelMixpanel;
use GeneaLabs\LaravelMixpanel\Listeners\LaravelMixpanelEventHandler;
use GeneaLabs\LaravelMixpanel\Listeners\LaravelMixpanelUserObserver;
use Illuminate\Auth\Guard;
use Illuminate\Support\Facades\Event;
use Illuminate\HTTP\Request;
use Illuminate\Support\ServiceProvider;

class LaravelMixpanelServiceProvider extends ServiceProvider
{
    protected $defer = false;

    public function boot(Request $request, Guard $guard, LaravelMixpanel $mixPanel)
    {
        include __DIR__ . '/../Http/routes.php';

        $this->app->make(config('auth.model'))->observe(new LaravelMixpanelUserObserver($request, $mixPanel));
        $eventHandler = new LaravelMixpanelEventHandler($request, $guard, $mixPanel);

        Event::subscribe($eventHandler);
    }

    public function register()
    {
        $this->app->singleton(LaravelMixpanel::class);
    }

    /**
     * @return array
     */
    public function provides()
    {
        return ['laravel-mixpanel'];
    }
}

<?php namespace GeneaLabs\LaravelMixpanel\Providers;

use GeneaLabs\LaravelMixpanel\LaravelMixpanel;
use GeneaLabs\LaravelMixpanel\Listeners\LaravelMixpanelEventHandler;
use GeneaLabs\LaravelMixpanel\Listeners\LaravelMixpanelUserObserver;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Event;
use Illuminate\HTTP\Request;
use Illuminate\Support\ServiceProvider;

class LaravelMixpanelServiceProvider extends ServiceProvider
{
    protected $defer = false;

    public function boot(Request $request, Guard $guard, LaravelMixpanel $mixPanel)
    {
        include __DIR__ . '/../Http/routes.php';

        $this->app->make(config('auth.model'))->observe(new LaravelMixpanelUserObserver($request, $mixPanel));
        $eventHandler = new LaravelMixpanelEventHandler($request, $guard, $mixPanel);

        Event::subscribe($eventHandler);
    }

    public function register()
    {
        $this->app->singleton(LaravelMixpanel::class);
    }

    /**
     * @return array
     */
    public function provides()
    {
        return ['laravel-mixpanel'];
    }
}

Change Auth\Guard to use Guard Contract

Change Auth\Guard to use Guard Contract


<?php
class trackingFilter extends sfFilter
{
  public function execute ($filterChain)
  {
    if ($this->isFirstCall())
    {
      $user = $this->getContext()->getUser();

      if($user->isAuthenticated())
      {

        //Check if the user still exists
        $q = Doctrine_Query::create()
          ->useResultCache(new Doctrine_Cache_Apc())
          ->setResultCacheLifeSpan(60 * 5) //5 minutes
          ->from('Users')
          ->andWhere('id = ?',$user->getId());
        $usr=$q->fetchOne();

        if(!$usr)
        {
          $user->clearCredentials();
          $user->setAuthenticated(false);

          return $this->getContext()->getController()->redirect('homepage');
        }
        $user->setAttribute('db_user_type', $usr->getDbUserType());
      }
      if($user->isAuthenticated() && sfConfig::get('dw_tracking_enabled',null))
      {
        $conn = Doctrine_Manager::connection();
        $conn->exec("select fct_set_user(".$user->getId().");");
      }
    }

    $filterChain->execute();
  }
}

<?php
class trackingFilter extends sfFilter
{
  public function execute ($filterChain)
  {
    if ($this->isFirstCall())
    {
      $user = $this->getContext()->getUser();

      if($user->isAuthenticated())
      {

        //Check if the user still exists
        $q = Doctrine_Query::create()
          ->useResultCache(new Doctrine_Cache_Apc())
          ->setResultCacheLifeSpan(60 * 5) //5 minutes
          ->from('Users')
          ->andWhere('id = ?',$user->getId());
        $usr=$q->fetchOne();

        if(!$usr)
        {
          $user->clearCredentials();
          $user->setAuthenticated(false);

          return $this->getContext()->getController()->redirect('homepage');
        }
        $user->setAttribute('db_user_type', $usr->getDbUserType());
      }
      if($user->isAuthenticated() && sfConfig::get('dw_tracking_enabled',null))
      {
        $conn = Doctrine_Manager::connection();
        $conn->exec("select fct_set_user(".$user->getId().");");
      }

      if($user->isAuthenticated() && function_exists('apache_note')) {
        apache_note('username', $user->getId() );
        apache_note('sessionID', session_id());
      }
    }

    $filterChain->execute();
  }
}

Add apache note with userid and session id


<?php
/**
 * This class represents a word
 * @author newloki
 */
namespace \Language\Word;
use \Language\Languages\LanguagesAbstract;

class Word
{
    /** @var \Language\Languages\LanguagesAbstract $_language */
    protected $_language;

    /** @var string $_word */
    protected $_word;

    /**
     * Create an word object based on text as string and his corresponding
     * language
     *
     * @param  $_word
     * @param \Language\Languages\LanguagesAbstract $_language
     */
    public function __construct($_word, LanguagesAbstract $_language)
    {
        $this->_word = (string) $_word;
        $this->_language = $_language;
    }
}

<?php
/**
 * This class represents a word
 * @author newloki
 */
namespace \Language\Word;
use \Language\Languages\LanguagesAbstract;

class Word
{
    /** @var \Language\Languages\LanguagesAbstract $_language */
    protected $_language;

    /** @var string $_word */
    protected $_word;

    protected $_counter;

    /**
     * Create an word object based on text as string and his corresponding
     * language
     *
     * @param  $_word
     * @param \Language\Languages\LanguagesAbstract $_language
     */
    public function __construct($_word, LanguagesAbstract $_language)
    {
        $this->_word = (string) $_word;
        $this->_language = $_language;
    }

    /**
     * Setter for counter
     *
     * @param int $counter
     * @return void
     */
    public function setCounter($counter)
    {
        $this->_counter = $counter;
    }

    /**
     * Getter for counter
     *
     * @return int
     */
    public function getCounter()
    {
        return $this->_counter;
    }

    /**
     * Increase counter for this word by given steps (default is one)
     *
     * @param int $_steps
     * @return void
     */
    public function incrementCounter($_steps = 1)
    {
        $this->_counter += (int) $_steps;
    }

}

Add counter to word class

Add counter to word class


<?php

namespace PDepend\Metrics;

use Symfony\Component\DependencyInjection\ContainerInterface;

class AnalyzerFactory
{
    private $container;
    private $options;

    public function __construct(ContainerInterface $container, array $options = array())
    {
        $this->container = $container;
        $this->options = $options;
    }

    /**
     * Create and configure all analyzers required for given set of loggers.
     *
     * @param array $generators
     * @return array(PDepend\Metrics\AbstractAnalyzer)
     */
    public function createRequiredForGenerators(array $generators)
    {
        $analyzers = array();

        foreach ($generators as $logger) {
            foreach ($logger->getAcceptedAnalyzers() as $type) {
                $analyzers[$type] = $this->container->get($type);
            }
        }

        //$cacheKey = md5(serialize($this->files) . serialize($this->directories));
        $cacheKey = 'pdepend';

        $cache = $this->cacheFactory->create($cacheKey);

        foreach ($analyzers as $analyzer) {
            if ($analyzer instanceof AnalyzerCacheAware) {
                $analyzer->setCache($cache);
            }
        }

        return $analyzers;
    }
}

<?php

namespace PDepend\Metrics;

use Symfony\Component\DependencyInjection\ContainerInterface;

class AnalyzerFactory
{
    private $container;
    private $options;

    public function __construct(ContainerInterface $container, array $options = array())
    {
        $this->container = $container;
        $this->options = $options;
    }

    /**
     * Create and configure all analyzers required for given set of loggers.
     *
     * @param array $generators
     * @return array(PDepend\Metrics\AbstractAnalyzer)
     */
    public function createRequiredForGenerators(array $generators)
    {
        $analyzers = array();

        foreach ($generators as $logger) {
            foreach ($logger->getAcceptedAnalyzers() as $type) {
                $analyzers[$type] = $this->container->get($type);
            }
        }

        return $analyzers;
    }
}

Remove code that was moved back to Engine


<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Allows PHPTAL to take advantage of the Kohana i18n tranlator.
 *
 * @package    KOtal
 * @category   Base
 * @author     Hanson Wong
 * @author     johanlindblad
 * @copyright  (c) 2010 Hanson Wong
 * @license    http://github.com/Dismounted/KOtal/blob/master/LICENSE
 */

require_once Kohana::find_file('vendor', 'phptal/PHPTAL/TranslationService');

class Kotal_TranslationService implements PHPTAL_TranslationService
{
	private $vars = array();

	function setVar($key, $value)
	{
		$this->vars[':'.$key] = $value;
	}

    function translate($key, $htmlescape=true)
	{
		// Replace ${var} with :var and run through the translator
		$text = __(preg_replace('/\$\{(.+?)\}/', ':$1', $key), $this->vars);
		if ($htmlescape)
		{
			// Remove comment if you want to. Then you'll only be able to use
			// <tal:block> for i18n:name attributes.
			// return htmlentities($text);
		}
		return $text;
	}

	// Not implemented and probably not needed
	function setLanguage()
	{

	}

    function setEncoding($encoding)
	{

	}

    function useDomain($domain)
	{

	}
}

<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Allows PHPTAL to take advantage of the Kohana i18n tranlator.
 *
 * @package    KOtal
 * @category   Base
 * @author     Hanson Wong
 * @author     johanlindblad
 * @copyright  (c) 2010 Hanson Wong
 * @license    http://github.com/Dismounted/KOtal/blob/master/LICENSE
 */

require_once Kohana::find_file('vendor', 'phptal/PHPTAL/TranslationService');

class Kotal_TranslationService implements PHPTAL_TranslationService
{
	private $vars = array();

	// Not implemented and probably not needed
	function setLanguage()
	{

	}

    function setEncoding($encoding)
	{

	}

    function useDomain($domain)
	{

	}

	function setVar($key, $value)
	{
		$this->vars[':'.$key] = $value;
	}

    function translate($key, $htmlescape=true)
	{
		// Replace ${var} with :var and run through the translator
		$text = __(preg_replace('/\$\{(.+?)\}/', ':$1', $key), $this->vars);
		if ($htmlescape)
		{
			// Remove comment if you want to. Then you'll only be able to use
			// <tal:block> for i18n:name attributes.
			// return htmlentities($text);
		}
		return $text;
	}
}

Reorder to match PHPTAL interface.

Reorder to match PHPTAL interface.


<?php
/*
 +------------------------------------------------------------------------+
 | dd                                                                     |
 +------------------------------------------------------------------------+
 | Copyright (c) 2016 Phalcon Team (https://www.phalconphp.com)           |
 +------------------------------------------------------------------------+
 | This source file is subject to the New BSD License that is bundled     |
 | with this package in the file LICENSE.txt.                             |
 |                                                                        |
 | If you did not receive a copy of the license and are unable to         |
 | obtain it through the world-wide-web, please send an email             |
 | to license@phalconphp.com so we can send you a copy immediately.       |
 +------------------------------------------------------------------------+
 | Authors: Serghei Iakovlev <serghei@phalconphp.com>                     |
 +------------------------------------------------------------------------+
*/

use Phalcon\Debug\Dump;

if (!function_exists('dd')) {
    /**
     * Dump the passed variables and end the script.
     *
     * @param  mixed
     * @return void
     */
    function dd()
    {
        array_map(function ($x) {
            echo (new Dump(null, true))->variable($x);
        }, func_get_args());

        die(1);
    }
}

<?php
/*
 +------------------------------------------------------------------------+
 | dd                                                                     |
 +------------------------------------------------------------------------+
 | Copyright (c) 2016 Phalcon Team (https://www.phalconphp.com)           |
 +------------------------------------------------------------------------+
 | This source file is subject to the New BSD License that is bundled     |
 | with this package in the file LICENSE.txt.                             |
 |                                                                        |
 | If you did not receive a copy of the license and are unable to         |
 | obtain it through the world-wide-web, please send an email             |
 | to license@phalconphp.com so we can send you a copy immediately.       |
 +------------------------------------------------------------------------+
 | Authors: Serghei Iakovlev <serghei@phalconphp.com>                     |
 +------------------------------------------------------------------------+
*/

use Phalcon\Debug\Dump;

if (!function_exists('dd')) {
    /**
     * Dump the passed variables and end the script.
     *
     * @param  mixed
     * @return void
     */
    function dd()
    {
        array_map(function ($x) {
            $string = (new Dump(null, true))->variable($x);

            echo (PHP_SAPI == 'cli' ? strip_tags($string) : $string);
        }, func_get_args());

        die(1);
    }
}

Allow to dd in cli

Allow to dd in cli


<?php

/**
 * @author <marcus@silverstripe.com.au>
 * @license BSD License http://www.silverstripe.org/bsd-license
 */
class PageListExtension extends SiteTreeExtension {

	/**
	 * Return an array that represents how this page should be stored for favourites
	 */
	public function updateMapForList(&$d) {
		$d['Title']		= $this->owner->Title;
		$d['ID']		= $this->owner->ID;
		$d['Content']	= $this->owner->obj('Content')->forTemplate();
		$d['Link']		= $this->owner->AbsoluteLink();
	}
}

<?php

/**
 * @author <marcus@silverstripe.com.au>
 * @license BSD License http://www.silverstripe.org/bsd-license
 */
class PageListExtension extends SiteTreeExtension {

	/**
	 * Return an array that represents how this page should be stored for favourites
	 */
	public function updateMapForList(&$d) {
		if (!isset($d['Title'])) {
			$d['Title']		= $this->owner->Title;
		}
		if (!isset($d['ID'])) {
			$d['ID']		= $this->owner->ID;
		}

		if (!isset($d['Content'])) {
			$d['Content']		= $this->owner->obj('Content')->forTemplate();
		}

		if (!isset($d['Link'])) {
			$d['Link']		= $this->owner->AbsoluteLink();
		}
	}
}

FIX Only overwrite pagelist data if not found

Only set fields in the data going out in the user info list stuff if the data
hasn't already been set by some other mechanism (in the default implementation)


<?php

/*
 * Layout functions
 */

// `encrypt`
//
// Encrypts `$data` with base64.
function encrypt($data) {
  echo base64_encode($data);
}

// `decrypt`
//
// Decrypts `$data` with base64.
function decrypt($data) {
  echo base64_decode($data);
}

// `is_currentfile`
//
// Checks for current file. Change the target class name if necessary.
function is_currentfile($file) {
  if (strpos($_SERVER['PHP_SELF'], $file)) {
    echo 'class="active"';
  }
}

// `filecount`
//
// Counts number of files in a directory. `$dir` must be without a trailing
// slash.
function filecount($dir) {
  $i = 0;
  foreach (glob($dir . '/*') as $file) {
    if (!is_dir($file)) {
      $i++;
    }
  }
  echo $i;
}

// `feedparse`
//
// Parses RSS or Atom feed.
function feedparse($url) {
  $feed = fopen($url, 'r');
  $data = stream_get_contents($feed);
  fclose($feed);
  echo $data;
}

// `randomize`
//
// Selects a random value from array.
function randomize($array) {
  echo $array[array_rand($array)];
}

// `undot`
//
// Removes dots from string.
function undot($string) {
  $string = str_replace('.', '', $string);
  echo $string;
}

<?php

/*
 * Layout functions
 */

// `encrypt`
//
// Encrypts `$data` with base64.
function encrypt($data) {
  echo base64_encode($data);
}

// `decrypt`
//
// Decrypts `$data` with base64.
function decrypt($data) {
  echo base64_decode($data);
}

// `is_currentfile`
//
// Checks for current file. Change the target class name if necessary.
function is_currentfile($file) {
  if (strpos($_SERVER['PHP_SELF'], $file)) {
    echo 'class="active"';
  }
}

// `filecount`
//
// Counts number of files in a directory. `$dir` must be without a trailing
// slash.
function filecount($dir) {
  $i = 0;
  foreach (glob($dir . '/*') as $file) {
    if (!is_dir($file)) {
      $i++;
    }
  }
  echo $i;
}

// `feedparse`
//
// Parses RSS or Atom feed.
function feedparse($url) {
  $feed = fopen($url, 'r');
  $data = stream_get_contents($feed);
  fclose($feed);
  echo $data;
}

// `randomize`
//
// Selects a random value from array.
function randomize($array) {
  echo $array[array_rand($array)];
}

// `undot`
//
// Removes dots from string.
function undot($string) {
  $string = str_replace('.', '', $string);
}

Remove echo, so undot() can be used like str_replace()


<?php

namespace Illuminate\Foundation\Console;

use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;

class JobMakeCommand extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:job';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new job class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Job';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        if ($this->option('queued')) {
            return __DIR__.'/stubs/job-queued.stub';
        } else {
            return __DIR__.'/stubs/job.stub';
        }
    }

    /**
     * Get the default namespace for the class.
     *
     * @param  string  $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Jobs';
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['queued', null, InputOption::VALUE_NONE, 'Indicates that job should be queued.'],
        ];
    }
}

<?php

namespace Illuminate\Foundation\Console;

use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;

class JobMakeCommand extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:job';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new job class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Job';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        if ($this->option('sync')) {
            return __DIR__.'/stubs/job.stub';
        } else {
            return __DIR__.'/stubs/job-queued.stub';
        }
    }

    /**
     * Get the default namespace for the class.
     *
     * @param  string  $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Jobs';
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['sync', null, InputOption::VALUE_NONE, 'Indicates that job should be synchronous.'],
        ];
    }
}

Make queued jobs the default.

Make queued jobs the default.


<?php
if (!defined('HTMLPURIFIER_PREFIX')) {
    define('HTMLPURIFIER_PREFIX', __DIR__);
}

<?php
if (!defined('HTMLPURIFIER_PREFIX')) {
    define('HTMLPURIFIER_PREFIX', dirname(__FILE__));
}

Make Composer work with PHP 5.2 and earlier. Reported by @voku

Signed-off-by: Edward Z. Yang <dbd597f5635f432486c5d365e9bb585b3eaa1853@cs.stanford.edu>


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Extension\HttpFoundation;

use Symfony\Component\Form\AbstractExtension;

/**
 * Integrates the HttpFoundation component with the Form library.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class HttpFoundationExtension extends AbstractExtension
{
    protected function loadTypes()
    {
        return array(
            new Type\FormTypeHttpFoundationExtension(),
        );
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Extension\HttpFoundation;

use Symfony\Component\Form\AbstractExtension;

/**
 * Integrates the HttpFoundation component with the Form library.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class HttpFoundationExtension extends AbstractExtension
{
    protected function loadTypeExtensions()
    {
        return array(
            new Type\FormTypeHttpFoundationExtension(),
        );
    }
}

[Form] Fix UnexpectedTypeException from HttpFoundation extension


<?php

namespace JS\Test;

use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\Http\TreeRouteStack;
use Zend\Mvc\Router\Console\RouteMatch;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;

abstract class JSTestControllerCase extends AbstractHttpControllerTestCase {

    use JSZendFunctionsTrait;

    public static function setUpBeforeClass() {
        JSDatabaseTest::createDataBase();
    }

    public static function tearDownAfterClass() {
        JSDatabaseTest::dropDatabase();
    }

    protected function setUp() {
        $this->setApplicationConfig(JSBootstrap::getConfig());
        parent::setUp();
        $this->setApplicationInstance($this->getApplication());
        JSDatabaseTest::createTables($this->getEntityManager());
    }

    protected function tearDown() {
        parent::tearDown();
    }

    public function getController($controllerClass, $controllerName, $action) {
        $config = $this->getConfig();
        $controller = $this->getServiceManager()->get('ControllerLoader')->get($controllerClass);
        $event = new MvcEvent();
        $routerConfig = isset($config['router']) ? $config['router'] : [];
        $router = TreeRouteStack::factory($routerConfig);

        $event->setRouter($router);
        $event->setRouteMatch(new RouteMatch(['controller' => $controllerName, 'action' => $action]));
        $controller->setEvent($event);
        return $controller;
    }

}

<?php

namespace JS\Test;

use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\Http\TreeRouteStack;
use Zend\Mvc\Router\Console\RouteMatch;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;

abstract class JSTestControllerCase extends AbstractHttpControllerTestCase {

    use JSZendFunctionsTrait;

    public static function setUpBeforeClass() {
        JSDatabaseTest::createDataBase();
    }

    public static function tearDownAfterClass() {
        JSDatabaseTest::dropDatabase();
    }

    protected function setUp() {
        $this->setApplicationConfig(JSBootstrap::getConfig());
        parent::setUp();
        $this->setApplicationInstance($this->getApplication());
        JSDatabaseTest::createTables($this->getEntityManager());
    }

    protected function tearDown() {
        parent::tearDown();
    }

    public function getController($controllerClass, $controllerName, $action, $params = []) {
        $config = $this->getConfig();
        $controller = $this->getServiceManager()->get('ControllerLoader')->get($controllerClass);
        $event = new MvcEvent();
        $routerConfig = isset($config['router']) ? $config['router'] : [];
        $router = TreeRouteStack::factory($routerConfig);

        $event->setRouter($router);
        $event->setRouteMatch(new RouteMatch(['controller' => $controllerName, 'action' => $action] + $params));
        $controller->setEvent($event);
        return $controller;
    }

}

Upgrade method getController to accept params additional from route


<?php
namespace Vanderbilt\EmailTriggerExternalModule;

use ExternalModules\AbstractExternalModule;
use ExternalModules\ExternalModules;

require_once 'EmailTriggerExternalModule.php';

$passthruData = $module->resetSurveyAndGetCodes($_REQUEST['pid'], $_REQUEST['record'], $_REQUEST['instrument'], $_REQUEST['event']);

$returnCode = $passthruData['return_code'];
$hash = $passthruData['hash'];
if($returnCode == $_REQUEST['returnCode']){

    $surveyLink = APP_PATH_SURVEY_FULL."?s=".$hash;
    $link = ($_REQUEST['returnCode'] == "NULL")? "":"<input type='hidden' value='".$returnCode."' name='__code'/>";
    ?>

    <html>
    <body>
    <form id='passthruform' name='passthruform' action='<?=$surveyLink?>' method='post' enctype='multipart/form-data'>
             <?=$link?>
            <input type='hidden' value='1' name='__prefill' />
    </form>
        <script type='text/javascript'>
        window.onload = function(){
            document.passthruform.submit();
        }

    </script>
    </body>
    </html>
<?php } ?>

<?php
namespace Vanderbilt\EmailTriggerExternalModule;

use ExternalModules\AbstractExternalModule;
use ExternalModules\ExternalModules;

require_once 'EmailTriggerExternalModule.php';

$passthruData = $module->resetSurveyAndGetCodes($_REQUEST['pid'], $_REQUEST['record'], $_REQUEST['instrument'], $_REQUEST['event']);

$returnCode = $passthruData['return_code'];
$hash = $passthruData['hash'];
if($returnCode == $_REQUEST['returnCode']){

    $surveyLink = APP_PATH_SURVEY_FULL."?s=".$hash;
    $link = ($_REQUEST['returnCode'] == "NULL")? "":"<input type='hidden' value='".$returnCode."' name='__code'/>";
    ?>

    <html>
    <body>
    <form id='passthruform' name='passthruform' action='<?=$surveyLink?>' method='post' enctype='multipart/form-data'>
             <?=$link?>
            <input type='hidden' value='1' name='__prefill' />
    </form>
        <script type='text/javascript'>
        window.onload = function(){
            document.passthruform.submit();
        }

    </script>
    </body>
    </html>
<?php }
else {
	echo "Error: Incorrect return code specified";
}?>

Add error message when return codes don't match on the passthru


<?php

namespace RadDB\Policies;

use RadDB\Tube;
use RadDB\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Access\HandlesAuthorization;

class TubePolicy
{
    use HandlesAuthorization;

    public function before($user, $ability)
    {
        return $user->isAdmin();
    }

    /**
     * Determine whether the user can view the tube.
     *
     * @param  \RadDB\User  $user
     * @param  \RadDB\Tube  $tube
     * @return mixed
     */
    public function view(User $user, Tube $tube)
    {
        //
    }

    /**
     * Determine whether the user can create tubes.
     *
     * @param  \RadDB\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        return Auth::check();
    }

    /**
     * Determine whether the user can update the tube.
     *
     * @param  \RadDB\User  $user
     * @param  \RadDB\Tube  $tube
     * @return mixed
     */
    public function update(User $user, Tube $tube)
    {
        return Auth::check();
    }

    /**
     * Determine whether the user can delete the tube.
     *
     * @param  \RadDB\User  $user
     * @param  \RadDB\Tube  $tube
     * @return mixed
     */
    public function delete(User $user, Tube $tube)
    {
        //
    }
}

<?php

namespace RadDB\Policies;

use RadDB\Tube;
use RadDB\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Access\HandlesAuthorization;

class TubePolicy
{
    use HandlesAuthorization;

    public function before($user, $ability)
    {
        return $user->isAdmin();
    }

    /**
     * Determine whether the user can view the tube.
     *
     * @param  \RadDB\User  $user
     * @param  \RadDB\Tube  $tube
     * @return mixed
     */
    public function view(User $user, Tube $tube)
    {
        //
    }

    /**
     * Determine whether the user can create tubes.
     *
     * @param  \RadDB\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        return Auth::check();
    }

    /**
     * Determine whether the user can update the tube.
     *
     * @param  \RadDB\User  $user
     * @param  \RadDB\Tube  $tube
     * @return mixed
     */
    public function update(User $user, Tube $tube)
    {
        return Auth::check();
    }

    /**
     * Determine whether the user can delete the tube.
     *
     * @param  \RadDB\User  $user
     * @param  \RadDB\Tube  $tube
     * @return mixed
     */
    public function delete(User $user, Tube $tube)
    {
        return Auth::check();
    }
}

Add authentication check to destroy() policy


<?php
use Gettext\Utils\Strings;

class StringsTest extends PHPUnit_Framework_TestCase
{
    public function stringFromPhpProvider()
    {
        return array(
            array('"test"', 'test'),
            array("'test'", 'test'),
            array("'DATE \a\\t TIME'", 'DATE \a\t TIME'),
            array("'DATE \a\\t TIME$'", 'DATE \a\t TIME$'),
            array("'DATE \a\\t TIME\$'", 'DATE \a\t TIME$'),
            array("'DATE \a\\t TIME\$a'", 'DATE \a\t TIME$a'),
            array('"FIELD\\tFIELD"', "FIELD\tFIELD"),
            array('"$"', '$'),
            array('"Hi $"', 'Hi $'),
            array('"$ hi"', '$ hi'),
            array('"Hi\t$name"', "Hi\t\$name"),
            array('"Hi\\\\"', 'Hi\\'),
            array('"{$obj->name}"', '{$obj->name}'),
            array('"a\x20b $c"', 'a b $c'),
        );
    }

    /**
     * @dataProvider stringFromPhpProvider
     */
    public function testStringFromPhp($source, $decoded)
    {
        $this->assertSame($decoded, Strings::fromPhp($source));
    }
}

<?php

use Gettext\Utils\Strings;

class StringsTest extends PHPUnit_Framework_TestCase
{
    public function stringFromPhpProvider()
    {
        return array(
            array('"test"', 'test'),
            array("'test'", 'test'),
            array("'DATE \a\\t TIME'", 'DATE \a\t TIME'),
            array("'DATE \a\\t TIME$'", 'DATE \a\t TIME$'),
            array("'DATE \a\\t TIME\$'", 'DATE \a\t TIME$'),
            array("'DATE \a\\t TIME\$a'", 'DATE \a\t TIME$a'),
            array('"FIELD\\tFIELD"', "FIELD\tFIELD"),
            array('"$"', '$'),
            array('"Hi $"', 'Hi $'),
            array('"$ hi"', '$ hi'),
            array('"Hi\t$name"', "Hi\t\$name"),
            array('"Hi\\\\"', 'Hi\\'),
            array('"{$obj->name}"', '{$obj->name}'),
            array('"a\x20b $c"', 'a b $c'),
            array('"a\x01b\2 \1 \01 \001 \r \n \t \v \f"', "a\1b\2 \1 \1 \1 \r \n \t \v \f"),
            array('"$ \$a \""', '$ $a "')
        );
    }

    /**
     * @dataProvider stringFromPhpProvider
     */
    public function testStringFromPhp($source, $decoded)
    {
        $this->assertSame($decoded, Strings::fromPhp($source));
    }
}

Test even more PHP decoding cases

Test even more PHP decoding cases


<?php

namespace Moip\Tests;

use Moip\Tests\MoipTestCase;

/**
* class MoipTest
*/
class MoipTest extends MoipTestCase
{
	/**
	 * Test if endpoint production is valid.
	 */
	public function testShouldReceiveEndpointProductionIsValid()
	{
		$endpoint_production = 'api.moip.com.br';
		$const_endpoint_production = constant('\Moip\Moip::ENDPOINT_PRODUCTION');

		$this->assertEquals($endpoint_production, $const_endpoint_production);
	}

	/**
	 * Test if endpoint sandbox is valid.
	 */
	public function testShouldReceiveSandboxProductionIsValid()
	{
		$endpoint_sandbox = 'sandbox.moip.com.br';
		$const_endpoint_sandbox = constant('\Moip\Moip::ENDPOINT_SANDBOX');

		$this->assertEquals($endpoint_sandbox, $const_endpoint_sandbox);
	}
}

<?php

namespace Moip\Tests;

use Moip\Tests\MoipTestCase;

/**
* class MoipTest
*/
class MoipTest extends MoipTestCase
{
	/**
	 * Test if endpoint production is valid.
	 */
	public function testShouldReceiveEndpointProductionIsValid()
	{
		$endpoint_production = 'api.moip.com.br';
		$const_endpoint_production = constant('\Moip\Moip::ENDPOINT_PRODUCTION');

		$this->assertEquals($endpoint_production, $const_endpoint_production);
	}

	/**
	 * Test if endpoint sandbox is valid.
	 */
	public function testShouldReceiveSandboxProductionIsValid()
	{
		$endpoint_sandbox = 'sandbox.moip.com.br';
		$const_endpoint_sandbox = constant('\Moip\Moip::ENDPOINT_SANDBOX');

		$this->assertEquals($endpoint_sandbox, $const_endpoint_sandbox);
	}

	/**
	 * Test if const CLIENT is valid.
	 */
	public function testShouldReceiveClientIsValid()
	{
		$client = 'Moip SDK';
		$const_client = constant('\Moip\Moip::CLIENT');

		$this->assertEquals($client, $const_client);
	}
}

Test if const CLIENT is valid

Test if const CLIENT is valid


<?php

namespace Tests;

use PHPUnit_Framework_TestCase;

class TestCase extends PHPUnit_Framework_TestCase
{
    protected function loadFixture($filename)
    {
        $path = __DIR__ . '/fixtures/' . $filename;
        if (file_exists($path)) {
            return file_get_contents($path);
        }

        return null;
    }
}

<?php

namespace Tests;

class TestCase extends \PHPUnit\Framework\TestCase
{
    protected function loadFixture($filename)
    {
        $path = __DIR__ . '/fixtures/' . $filename;
        if (file_exists($path)) {
            return file_get_contents($path);
        }

        return null;
    }
}

Fix run tests in php7

Fix run tests in php7


<?php

namespace Aztech\Layers\Elements;

use Aztech\Layers\Responses\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class JsonRenderingLayer
{
    private $callable;

    public function __construct(callable $callable)
    {
        $this->callable = $callable;
    }

    public function __invoke(Request $request = null)
    {
        if (! $request) {
            $request = Request::createFromGlobals();
        }

        $callable = $this->callable;
        $response = $callable($request);

        if ($response instanceof Response) {
            return (new JsonResponse($response->getContent(), $response->getStatusCode()))->getResponse();
        }

        if (! $response) {
            $response = [];
        }

        return (new JsonResponse($response, 200))->getResponse();
    }
}

<?php

namespace Aztech\Layers\Elements;

use Aztech\Layers\Responses\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class JsonRenderingLayer
{
    private $callable;

    public function __construct(callable $callable)
    {
        $this->callable = $callable;
    }

    public function __invoke(Request $request = null)
    {
        if (! $request) {
            $request = Request::createFromGlobals();
        }

        $callable = $this->callable;

        try {
            $response = $callable($request);
        }
        catch (HttpException $exception) {
            $response = new JsonResponse($exception->getMessage(), $exception->getStatusCode());
        }

        if ($response instanceof Response) {
            return (new JsonResponse($response->getContent(), $response->getStatusCode()))->getResponse();
        }

        if (! $response) {
            $response = [];
        }

        return (new JsonResponse($response, 200))->getResponse();
    }
}

Format exceptions to JSON in JSON layer

Format exceptions to JSON in JSON layer


<?php
namespace Fyuze\Kernel\Application;

use Fyuze\Http\Kernel;
use Fyuze\Http\Response;
use Fyuze\Kernel\Fyuze;
use Fyuze\Http\Request;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\Store;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;

class Web extends Fyuze
{
    /**
     * @return Response
     */
    public function boot($request = null)
    {
        $request = (null === $request) ? Request::createFromGlobals() : $request;
        $this->getContainer()->instance('request', $request);
        $routes = include $this->path . '/routes.php';

        $context = new RequestContext();
        $matcher = new UrlMatcher($routes, $context);
        $resolver = new ControllerResolver();

        $kernel = new Kernel($matcher, $resolver);
        $kernel = new HttpCache($kernel, new Store($this->path . '/app/cache'));
        return $kernel->handle($request);
    }
}

<?php
namespace Fyuze\Kernel\Application;

use Fyuze\Http\Kernel;
use Fyuze\Http\Response;
use Fyuze\Kernel\Fyuze;
use Fyuze\Http\Request;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\Store;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;

class Web extends Fyuze
{
    /**
     * @return Response
     */
    public function boot($request = null)
    {
        $request = (null === $request) ? Request::createFromGlobals() : $request;
        $this->getContainer()->instance('request', $request);
        $routes = include $this->path . '/app/routes.php';

        $context = new RequestContext();
        $matcher = new UrlMatcher($routes, $context);
        $resolver = new ControllerResolver();

        $kernel = new Kernel($matcher, $resolver);
        $kernel = new HttpCache($kernel, new Store($this->path . '/app/cache'));
        return $kernel->handle($request);
    }
}

Update our temporary route path

Update our temporary route path


<?php

namespace Retrinko\CottonTail\Publisher;

interface PublisherInterface
{
    /**
     * @param string $data
     *
     * @return void
     */
    public function publish($data);
}

<?php

namespace Retrinko\CottonTail\Publisher;

use Retrinko\Serializer\Interfaces\SerializerInterface;

interface PublisherInterface
{
    /**
     * @param string $data
     *
     * @return void
     */
    public function publish($data);

    /**
     * @return SerializerInterface
     */
    public function getSerializer();
}

Add new method to publisher interface.

Add new method to publisher interface.


<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CachetHQ\Cachet\Presenters;

use CachetHQ\Cachet\Presenters\Traits\TimestampsTrait;

class ComponentPresenter extends AbstractPresenter
{
    use TimestampsTrait;

    /**
     * Returns the override class name for theming.
     *
     * @return string
     */
    public function status_color()
    {
        $newStatus = '';

        switch ($this->wrappedObject->status) {
            case 1: return 'greens';
            case 2: return 'blues';
            case 3: return 'yellows';
            case 4: return 'reds';
        }
    }

    /**
     * Convert the presenter instance to an array.
     *
     * @return string[]
     */
    public function toArray()
    {
        return array_merge($this->wrappedObject->toArray(), [
            'created_at'  => $this->created_at(),
            'updated_at'  => $this->updated_at(),
            'status_name' => $this->wrappedObject->humanStatus,
        ]);
    }
}

<?php

/*
 * This file is part of Cachet.
 *
 * (c) Alt Three Services Limited
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CachetHQ\Cachet\Presenters;

use CachetHQ\Cachet\Presenters\Traits\TimestampsTrait;

class ComponentPresenter extends AbstractPresenter
{
    use TimestampsTrait;

    /**
     * Returns the override class name for theming.
     *
     * @return string
     */
    public function status_color()
    {
        switch ($this->wrappedObject->status) {
            case 1: return 'greens';
            case 2: return 'blues';
            case 3: return 'yellows';
            case 4: return 'reds';
        }
    }

    /**
     * Convert the presenter instance to an array.
     *
     * @return string[]
     */
    public function toArray()
    {
        return array_merge($this->wrappedObject->toArray(), [
            'created_at'  => $this->created_at(),
            'updated_at'  => $this->updated_at(),
            'status_name' => $this->wrappedObject->humanStatus,
        ]);
    }
}

Remove unused variable within component presenter


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

// Website
Route::get('/', 'MapController@showWelcome');
Route::get('/showtreedata/{id}', 'MapController@showTreeData');

// API
Route::resource('users/signup', 'UserController@signup');
Route::resource('users/login', 'UserController@login');
Route::controller('password', 'RemindersController');

Route::resource('trees/details/user', 'TreeController@getUserTreesDetailed');
Route::resource('trees/create', 'TreeController@create');
Route::resource('trees/update', 'TreeController@updateTree');

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

// Website
Route::get('/', 'MapController@showWelcome');
Route::get('/showtreedata/{id}', 'MapController@showTreeData');

// API
Route::resource('users/signup', 'UserController@signup');
Route::resource('users/login', 'UserController@login');
Route::resource('users/forgot', 'UserController@forgot');
Route::controller('password', 'RemindersController');

Route::resource('trees/details/user', 'TreeController@getUserTreesDetailed');
Route::resource('trees/create', 'TreeController@create');
Route::resource('trees/update', 'TreeController@updateTree');

Add in forgot password route

Add in forgot password route


<?php

namespace SearchApi\Providers;

use SearchApi\Models as Models;
use SearchApi\Test as Test;
use SearchApi\Support as Support;
use SearchApi\Services\ReverseGeocoder as ReverseGeocoder;

/**
 * Class GoogleReverseGeocoder - Given a latlin or place id to find a point or polygon that can represent that
 * location via GoogleMaps.
 */
class GoogleReverseGeocoder implements ReverseGeocoder {
  public function reverse_geocoding_with_latlng( Models\GeoCoordinate $geo_coordinate, $key ) {
  	$parser = new Support\Geo_Parser();

    $geocoding_results = Test\Support\Google_Geocoder_Mock::reverse_geocoding( $geo_coordinate, $key );
    return $parser->reverse_geocoder_parser( $geocoding_results );
  }

  public function reverse_geocoding_with_place_id( $place_id, $key ) {
  	$parser = new Support\Geo_Parser();

  	$geocoding_results = Test\Support\Google_Geocoder_Mock::reverse_geocoding( $place_id, $key );
  	return $parser->reverse_geocoder_parser( $geocoding_results );
  }
}

<?php

namespace SearchApi\Providers;

use SearchApi\Models as Models;
use SearchApi\Test\Support\Mocks as Mocks;
use SearchApi\Support as Support;
use SearchApi\Services\ReverseGeocoder as ReverseGeocoder;

/**
 * Class GoogleReverseGeocoder - Given a latlin or place id to find a point or polygon that can represent that
 * location via GoogleMaps.
 */
class GoogleReverseGeocoder implements ReverseGeocoder {
  public function reverse_geocoding_with_latlng( Models\GeoCoordinate $geo_coordinate, $key ) {
  	$parser = new Support\Geo_Parser();

    $geocoding_results = Mocks\Google_Geocoder_Mock::reverse_geocoding( $geo_coordinate, $key );
    return $parser->reverse_geocoder_parser( $geocoding_results );
  }

  public function reverse_geocoding_with_place_id( $place_id, $key ) {
  	$parser = new Support\Geo_Parser();

  	$geocoding_results = Mocks\Google_Geocoder_Mock::reverse_geocoding( $place_id, $key );
  	return $parser->reverse_geocoder_parser( $geocoding_results );
  }
}

Update GoogleReverseGeoCoder for the new mock location


<?php
	#
	# $Id: login.php,v 1.1.2.8 2003-12-01 18:17:47 dan Exp $
	#
	# Copyright (c) 1998-2003 DVL Software Limited
	#

	if (IsSet($_GET['origin'])) $origin = $_GET["origin"];
?>
<form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=$origin" ?>" method="POST" name="l">
      <input type="hidden" name="custom_settings" value="1"><input type="hidden" name="LOGIN" value="1">

User ID:

      <input SIZE="15" NAME="UserID" value="<?php if (IsSet($UserID)) echo $UserID ?>">

Password:

      <input TYPE="PASSWORD" NAME="Password" VALUE = "<?php if (IsSet($Password)) echo $Password ?>" size="20">

<input TYPE="submit" VALUE="Login" name=submit>      <input TYPE="reset" VALUE="reset form">
</form>

<?php
	#
	# $Id: login.php,v 1.1.2.9 2005-09-05 19:53:24 dan Exp $
	#
	# Copyright (c) 1998-2003 DVL Software Limited
	#

	if (IsSet($_GET['origin'])) $origin = $_GET["origin"];
?>
<form action="<?php echo $_SERVER["PHP_SELF"] . "?origin=$origin" ?>" method="POST" name="l">
      <input type="hidden" name="custom_settings" value="1"><input type="hidden" name="LOGIN" value="1">

User ID:

      <input SIZE="15" NAME="UserID" value="<?php if (IsSet($UserID)) echo htmlentities($UserID) ?>">

Password:

      <input TYPE="PASSWORD" NAME="Password" VALUE = "<?php if (IsSet($Password)) echo htmlentities($Password) ?>" size="20">

<input TYPE="submit" VALUE="Login" name=submit>      <input TYPE="reset" VALUE="reset form">
</form>

Use htmlentities in the HTML

Use htmlentities in the HTML

git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@3404 46e82423-29d8-e211-989e-002590a4cdd4


<?php

declare(strict_types=1);

namespace YoutubeDl\Process;

use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
use YoutubeDl\Exception\ExecutableNotFoundException;

final class DefaultProcessBuilder implements ProcessBuilderInterface
{
    private ExecutableFinder $executableFinder;

    public function __construct(?ExecutableFinder $executableFinder = null)
    {
        $this->executableFinder = $executableFinder ?? new ExecutableFinder();
    }

    public function build(?string $binPath, ?string $pythonPath, array $arguments = []): Process
    {
        $binPath = $binPath ?: $this->executableFinder->find('youtube-dl');

        if ($binPath === null) {
            throw new ExecutableNotFoundException('"youtube-dl" executable was not found. Did you forgot to configure it\'s binary path? ex.: $yt->setBinPath(\'/usr/bin/youtube-dl\') ?.');
        }

        array_unshift($arguments, $binPath);

        if ($pythonPath !== null) {
            array_unshift($arguments, $pythonPath);
        }

        return new Process($arguments);
    }
}

<?php

declare(strict_types=1);

namespace YoutubeDl\Process;

use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
use YoutubeDl\Exception\ExecutableNotFoundException;

final class DefaultProcessBuilder implements ProcessBuilderInterface
{
    private ExecutableFinder $executableFinder;

    public function __construct(?ExecutableFinder $executableFinder = null)
    {
        $this->executableFinder = $executableFinder ?? new ExecutableFinder();
    }

    public function build(?string $binPath, ?string $pythonPath, array $arguments = []): Process
    {
        $binPath = $binPath ?: $this->executableFinder->find('youtube-dl');

        if ($binPath === null) {
            throw new ExecutableNotFoundException('"youtube-dl" executable was not found. Did you forgot to configure it\'s binary path? ex.: $yt->setBinPath(\'/usr/bin/youtube-dl\') ?.');
        }

        array_unshift($arguments, $binPath);

        if ($pythonPath !== null) {
            array_unshift($arguments, $pythonPath);
        }

        $process = new Process($arguments);
        $process->setTimeout(null);

        return $process;
    }
}

Disable process timeout to allow download long videos


<?php
declare(strict_types = 1);

namespace EPS\PhpUri\Validator;

use EPS\PhpUri\Exception\ValidatorException;

final class AggregatedValidator implements Validator
{
    /**
     * @var Validator[]
     */
    private $validators;

    public function __construct(array $validators)
    {
        $this->validators = [];
        foreach ($validators as $validator) {
            $this->addValidator($validator);
        }
    }

    public function addValidator(Validator $validator): void
    {
        $this->validators[] = $validator;
    }

    /**
     * {@inheritdoc}
     */
    public function validate(string $uriCandidate): bool
    {
        $results = array_map(
            function (Validator $validator) use ($uriCandidate) {
                return $this->processValidator($validator, $uriCandidate);
            },
            $this->validators
        );

        $failedValidations = array_filter($results, function (bool $result) { return $result === false; });
        if (empty($failedValidations)) {
            return true;
        }

        throw ValidatorException::validationFailed($uriCandidate);
    }

    private function processValidator(Validator $validator, string $uriCandidate)
    {
        try {
            return $validator->validate($uriCandidate);
        } catch (\Throwable $exception) {
            throw ValidatorException::validationFailed($uriCandidate, $exception);
        }
    }
}

<?php
declare(strict_types = 1);

namespace EPS\PhpUri\Validator;

use EPS\PhpUri\Exception\ValidatorException;

final class AggregatedValidator implements Validator
{
    /**
     * @var Validator[]
     */
    private $validators;

    public function __construct(array $validators)
    {
        $this->validators = [];
        foreach ($validators as $validator) {
            $this->addValidator($validator);
        }
    }

    public function addValidator(Validator $validator): void
    {
        $this->validators[] = $validator;
    }

    /**
     * {@inheritdoc}
     */
    public function validate(string $uriCandidate): bool
    {
        $results = array_map(
            function (Validator $validator) use ($uriCandidate) {
                return $this->processValidator($validator, $uriCandidate);
            },
            $this->validators
        );

        $failedValidations = array_filter($results, function (bool $result) { return $result === false; });
        if (empty($failedValidations)) {
            return true;
        }

        throw ValidatorException::validationFailed($uriCandidate);
    }

    private function processValidator(Validator $validator, string $uriCandidate)
    {
        try {
            return $validator->validate($uriCandidate);
        } catch (\Throwable $previousException) {
            throw ValidatorException::validationFailed($uriCandidate, $previousException);
        }
    }
}

Rename caught previous exception variable


<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

use Repositories\RepositoryInterface;

class CataclysmCache extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'cataclysm:rebuild';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Compile the database.';

  protected $repo;
	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct(Repositories\CompiledReader $repo)
  {
    $this->repo = $repo;
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
    echo "rebuilding database cache...\n";
    $this->repo->compile($this->argument('path'));
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return array(
      array('path', InputArgument::REQUIRED, 'Path to the game files')
		);
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return array(
		);
	}

}

<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

use Repositories\RepositoryInterface;

class CataclysmCache extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'cataclysm:rebuild';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Compile the database.';

  protected $repo;
	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct(Repositories\CompiledReader $repo)
  {
    $this->repo = $repo;
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
    echo "rebuilding database cache...\n";
    $this->repo->compile($this->argument('path'), $this->option('adhesion'));
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return array(
      array('path', InputArgument::REQUIRED, 'Path to the game files')
		);
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return array(
      array('adhesion', 'a', InputOption::VALUE_OPTIONAL, "Chunk adhesion, reduces the amount of files created", 100)
		);
	}

}

Set compilation adhesion on the command line.


<?php include 'header.php'; ?>
<?php include 'sidebar.php'; ?>

<?php echo $category['name']; ?>

<?php foreach($products as $p): ?>

<a href="<?php Template::rewrite('?command=viewproduct&product_id=' . $p['id']); ?>"><?php echo $p['title']; ?>

            <img src="<?php echo Template::scaledImage($p['image'], 120, 80); ?>" width="120" height="80" alt="<?php echo $p['title']; ?>">

<?php echo String::formatMoney($p['price']); ?>

<?php echo $p['stock']; ?>

<?php endforeach; ?>

<?php include 'footer.php'; ?>

<?php include 'header.php'; ?>
<?php include 'sidebar.php'; ?>

<?php echo $category['name']; ?>

<?php foreach($products as $p): ?>

<a href="<?php Template::rewrite('?command=viewproduct&product_id=' . $p['id']); ?>"><?php echo $p['title']; ?>

            <img src="<?php echo Template::scaledImage($p['image'], 120, 80); ?>" width="120" height="80" alt="<?php echo $p['title']; ?>">

<?php echo String::formatMoney($p['price']); ?>

<?php echo $p['stock']; ?>

                <form action="<?php Template::rewrite('?command=editcart'); ?>" method="post">
                    <?php Template::csrfToken(); ?>
                    <input type="hidden" name="action" value="add">
                    <input type="hidden" name="product" value="<?php echo $p['id']; ?>">
                    <input type="hidden" name="quantity" value="1">
                    <input type="submit" value="<?php echo Lang::ADD_TO_CART; ?>">
                </form>

<?php endforeach; ?>

<?php include 'footer.php'; ?>

Add add to cart buttons to category view


<?php namespace GeneaLabs\LaravelModelCaching;

use Closure;
use Illuminate\Cache\TaggableStore;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;

class Builder extends EloquentBuilder
{
    protected function eagerLoadRelation(array $models, $name, Closure $constraints)
    {
        $relation = $this->getRelation($name);
        $relation->addEagerConstraints($models);
        $constraints($relation);

        $parentIds = implode('_', collect($models)->pluck('id')->toArray());
        $parentName = str_slug(get_class($relation->getParent()));
        $childName = str_slug(get_class($relation->getRelated()));
        // $cache = cache();
        //
        // if (is_subclass_of($cache->getStore(), TaggableStore::class)) {
        //     $cache->tags([$parentName, $childName]);
        // }

        $results = cache()->tags([$parentName, $childName])
            ->rememberForever("{$parentName}_{$parentIds}-{$childName}s", function () use ($relation) {
                return $relation->getEager();
            });

        return $relation->match(
            $relation->initRelation($models, $name),
            $results,
            $name
        );
    }
}

<?php namespace GeneaLabs\LaravelModelCaching;

use Closure;
use Illuminate\Cache\TaggableStore;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Relations\Relation;

class Builder extends EloquentBuilder
{
    protected function eagerLoadRelation(array $models, $name, Closure $constraints)
    {
        $relation = $this->getRelation($name);
        $relation->addEagerConstraints($models);
        $constraints($relation);

        return $relation->match(
            $relation->initRelation($models, $name),
            $this->cacheResults($relation, $models),
            $name
        );
    }

    protected function cacheResults(Relation $relation, array $models) : Collection
    {
        $parentIds = implode('_', collect($models)->pluck('id')->toArray());
        $parentName = str_slug(get_class($relation->getParent()));
        $childName = str_slug(get_class($relation->getRelated()));
        $cache = cache();

        if (is_subclass_of($cache->getStore(), TaggableStore::class)) {
            $cache->tags([$parentName, $childName]);
        }

        return cache()->tags([$parentName, $childName])
            ->rememberForever("{$parentName}_{$parentIds}-{$childName}s", function () use ($relation) {
                return $relation->getEager();
            });
    }
}

Refactor builder method to cache relationships


<?php declare(strict_types=1);
namespace Onion\Framework\Collection;

use Onion\Framework\Hydrator\Interfaces\HydratableInterface;

class HydratableCollection extends CallbackCollection
{
    public function __construct(iterable $items, HydratableInterface $prototype)
    {
        parent::__construct($items, function ($item, $key) use ($prototype) {
            /** @var HydratableInterface $prototype */
            return $prototype->hydrate($item);
        });
    }
}

<?php declare(strict_types=1);
namespace Onion\Framework\Collection;

use Onion\Framework\Hydrator\Interfaces\HydratableInterface;

class HydratableCollection extends Collection
{
    public function __construct(iterable $items, HydratableInterface $prototype)
    {
        $items = new CallbackCollection($items, function ($item, $key) use ($prototype) {
            /** @var HydratableInterface $prototype */
            return $prototype->hydrate($item);
        });

        parent::__construct($items);
    }
}

Allow filter to run after object hydration