<?php

namespace Bolt\Extension;

use Pimple as Container;

/**
 * Storage helpers.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
trait StorageTrait
{
    /**
     * Return a list of entities to map to repositories.
     *
     * <pre>
     *  return [
     *      'alias' => [\Entity\Class\Name => \Repository\Class\Name],
     *  ];
     * </pre>
     *
     * @return array
     */
    protected function registerRepositoryMappings()
    {
        return [];
    }

    /**
     * Call this in register method.
     *
     * @internal
     */
    final protected function extendRepositoryMapping()
    {
        $app = $this->getContainer();

        $app['storage.metadata'] = $app->share(
            $app->extend(
                'storage.metadata',
                function ($storageMetadata) use ($app) {
                    foreach ($this->registerRepositoryMappings() as $alias => $map) {
                        $storageMetadata->setDefaultAlias($app['schema.prefix'] . $alias, key($map));
                    }

                    return $storageMetadata;
                }
            )
        );

        $app['storage'] = $app->share(
            $app->extend(
                'storage',
                function ($entityManager) use ($app) {
                    foreach ($this->registerRepositoryMappings() as $alias => $map) {
                        $app['storage.repositories'] += $map;
                        $entityManager->setRepository(key($map), current($map));
                    }

                    return $entityManager;
                }
            )
        );
    }

    /** @return Container */
    abstract protected function getContainer();
}

<?php

namespace Bolt\Extension;

use Pimple as Container;

/**
 * Storage helpers.
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
trait StorageTrait
{
    /**
     * Return a list of entities to map to repositories.
     *
     * <pre>
     *  return [
     *      'alias' => [\Entity\Class\Name => \Repository\Class\Name],
     *  ];
     * </pre>
     *
     * @return array
     */
    protected function registerRepositoryMappings()
    {
        return [];
    }

    /**
     * Call this in register method.
     *
     * @internal
     */
    final protected function extendRepositoryMapping()
    {
        $app = $this->getContainer();

        $app['storage'] = $app->share(
            $app->extend(
                'storage',
                function ($entityManager) use ($app) {
                    foreach ($this->registerRepositoryMappings() as $alias => $map) {
                        $app['storage.repositories'] += $map;
                        $app['storage.metadata']->setDefaultAlias($app['schema.prefix'] . $alias, key($map));
                        $entityManager->setRepository(key($map), current($map));
                    }

                    return $entityManager;
                }
            )
        );
    }

    /** @return Container */
    abstract protected function getContainer();
}

Move $app['storage.metadata']->setDefaultAlias into storage extend


<?php

namespace AppBundle\RestApi;

use Doctrine\DBAL\Connection;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Routing\ClassResourceInterface;

class HostelController extends FOSRestController implements ClassResourceInterface
{
    public function cgetAction()
    {
        $db = $this->getConnection();
        return $db->fetchAll("select * from hostel");
    }

    public function getAction($slug)
    {
        $db = $this->getConnection();
        return $db->fetchAssoc("select * from hostel where slug = :slug", [
            "slug" => $slug
        ]);
    }

    private function getConnection(): Connection
    {
        return $connection = $this->get("database_connection");
    }

    private function getRepository()
    {
        return $this->getDoctrine()->getRepository('AppBundle:Hostel');
    }
}

<?php

namespace AppBundle\RestApi;

use Doctrine\DBAL\Connection;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Routing\ClassResourceInterface;

class HostelController extends FOSRestController implements ClassResourceInterface
{
    public function cgetAction()
    {
        $db = $this->getConnection();
        return $db->fetchAll("select * from hostel");
    }

    public function getAction($slug)
    {
        $db = $this->getConnection();
        return $db->fetchAssoc("select * from hostel where slug = :slug", [
            "slug" => $slug
        ]);
    }

    public function getRoomsAction($slug)
    {
        $db = $this->getConnection();
        $sql = "select * from room where hostel_id = (select id from hostel where slug = :slug)";
        return $db->fetchAll($sql, [
            "slug" => $slug
        ]);
    }

    private function getConnection(): Connection
    {
        return $connection = $this->get("database_connection");
    }

    private function getRepository()
    {
        return $this->getDoctrine()->getRepository('AppBundle:Hostel');
    }
}

Add Api method for getting rooms of a hostel


<?php

namespace Gitiki\Event\Listener;

use Gitiki\Event\Events;

use Symfony\Component\EventDispatcher\EventSubscriberInterface,
    Symfony\Component\EventDispatcher\GenericEvent as Event;

class WikiLink implements EventSubscriberInterface
{
    protected $wikiDir;

    protected $baseUri;

    public function __construct($wikiDir, $baseUri)
    {
        $this->wikiDir = $wikiDir;

        $this->baseUri = $baseUri;
    }

    public function onContent(Event $event)
    {
        $page = $event->getSubject();

        $doc = new \DOMDocument();
        $doc->loadHTML($page->getContent());

        foreach ($doc->getElementsByTagName('a') as $link) {
            $href = $link->getAttribute('href');

            $url = parse_url($href);
            if (isset($url['host'])) {
                continue;
            }

            if (!is_file($this->wikiDir.'/'.$url['path'].'.md')) {
                $link->setAttribute('class', 'new');
            }

            $link->setAttribute('href', $this->baseUri.$href);
        }

        $page->setContent($doc->saveHTML());
    }

    public static function getSubscribedEvents()
    {
        return [
            Events::PAGE_CONTENT => ['onContent', 512],
        ];
    }
}

<?php

namespace Gitiki\Event\Listener;

use Gitiki\Event\Events;

use Symfony\Component\EventDispatcher\EventSubscriberInterface,
    Symfony\Component\EventDispatcher\GenericEvent as Event;

class WikiLink implements EventSubscriberInterface
{
    protected $wikiDir;

    protected $baseUri;

    public function __construct($wikiDir, $baseUri)
    {
        $this->wikiDir = $wikiDir;

        $this->baseUri = $baseUri;
    }

    public function onContent(Event $event)
    {
        $page = $event->getSubject();

        $doc = new \DOMDocument();
        $doc->loadHTML($page->getContent(), LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);

        foreach ($doc->getElementsByTagName('a') as $link) {
            $href = $link->getAttribute('href');

            $url = parse_url($href);
            if (isset($url['host'])) {
                continue;
            }

            if (!is_file($this->wikiDir.'/'.$url['path'].'.md')) {
                $link->setAttribute('class', 'new');
            }

            $link->setAttribute('href', $this->baseUri.$href);
        }

        $page->setContent($doc->saveHTML());
    }

    public static function getSubscribedEvents()
    {
        return [
            Events::PAGE_CONTENT => ['onContent', 512],
        ];
    }
}

Disable output of doctype, html and body elements


<?php

namespace Coral\SiteBundle\Twig;

use Symfony\Component\HttpFoundation\RequestStack;
use Coral\SiteBundle\Content\Node;

class PathExtension extends \Twig_Extension
{
    /**
     * Request stack
     *
     * @var RequestStack
     */
    protected $requestStack;

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

    /**
     * @codeCoverageIgnore
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('coral_path', array($this, 'path')),
        );
    }

    public function path(Node $node)
    {
        if($node->hasProperty('redirect'))
        {
            return $node->getProperty('redirect');
        }
        $request = $this->requestStack->getCurrentRequest();
        $path = $node->getUri();
        $scriptName = $request->getScriptName();

        if(strpos($scriptName, '_') !== false)
        {
            return $scriptName . $path;
        }

        return $path;
    }

    public function getName()
    {
        return 'path_extension';
    }
}

<?php

namespace Coral\SiteBundle\Twig;

use Symfony\Component\HttpFoundation\RequestStack;
use Coral\SiteBundle\Content\Node;

class PathExtension extends \Twig_Extension
{
    /**
     * Request stack
     *
     * @var RequestStack
     */
    protected $requestStack;

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

    /**
     * @codeCoverageIgnore
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('coral_path', array($this, 'path')),
        );
    }

    public function path(Node $node)
    {
        if($node->hasProperty('redirect'))
        {
            return $node->getProperty('redirect');
        }
        $request = $this->requestStack->getCurrentRequest();
        $path = $node->getUri();
        $scriptName = $request->getScriptName();

        if((strpos($scriptName, '_dev') !== false) || ((strpos($scriptName, '_test') !== false)))
        {
            return $scriptName . $path;
        }

        return $path;
    }

    public function getName()
    {
        return 'path_extension';
    }
}

Fix of detection of dev and test script names


<?php namespace Pingpong\Twitter;

use Codebird\Codebird;
use Illuminate\Support\ServiceProvider;

class TwitterServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Boot the package.
	 *
	 * @return void
	 */
	public function boot()
	{
		$configPath = config_path('twitter.php');

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

		$this->mergeConfigFrom($configPath, 'twitter');
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['twitter'] = $this->app->share(function($app)
		{
			$api = new Api;

            $config = $app['config']->get('twitter');

			return new Twitter(
                $api,
                $app['session.store'],
                $app['config'],
                $app['request'],
                $app['redirect'],
                $config['consumer_key'],
                $config['consumer_secret'],
                $config['oauth_token'],
                $config['oauth_token_secret'],
                $config['bearer_token'],
                $config['callback_url'],
                $config['fallback_url']
            );
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return ['twitter'];
	}

}

<?php namespace Pingpong\Twitter;

use Codebird\Codebird;
use Illuminate\Support\ServiceProvider;

class TwitterServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Boot the package.
	 *
	 * @return void
	 */
	public function boot()
	{
		$configPath = config_path('twitter.php');

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

		if (is_file($configPath)) {
			$this->mergeConfigFrom($configPath, 'twitter');
		}
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['twitter'] = $this->app->share(function($app)
		{
			$api = new Api;

            $config = $app['config']->get('twitter');

			return new Twitter(
                $api,
                $app['session.store'],
                $app['config'],
                $app['request'],
                $app['redirect'],
                $config['consumer_key'],
                $config['consumer_secret'],
                $config['oauth_token'],
                $config['oauth_token_secret'],
                $config['bearer_token'],
                $config['callback_url'],
                $config['fallback_url']
            );
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return ['twitter'];
	}

}

Fix publish for first installation

Fix publish for first installation


<?php

namespace Concrete\Tests\Update;

use Concrete\TestHelpers\DockerTrait;
use PHPUnit_Framework_TestCase;

/**
 * @group docker
 */
class InstallUpdateTest extends PHPUnit_Framework_TestCase
{
    use DockerTrait;

    public function testFullInstallation()
    {
        $this->runScriptInDocker('mlocati/docker5:8.5.2-full', 'run-install.sh');
    }

    public function testUpdatePreviousInstallation()
    {
        $this->runScriptInDocker('mlocati/docker5:5.7.5.13-full', 'run-update.sh');
    }
}

<?php

namespace Concrete\Tests\Update;

use Concrete\TestHelpers\DockerTrait;
use PHPUnit_Framework_TestCase;

/**
 * @group docker
 */
class InstallUpdateTest extends PHPUnit_Framework_TestCase
{
    use DockerTrait;

    public function testFullInstallation()
    {
        $this->runScriptInDocker('mlocati/docker5:8.5.2-full', 'run-install.sh');
    }

    public function testUpdate5_7_5_13()
    {
        $this->runScriptInDocker('mlocati/docker5:5.7.5.13-full', 'run-update.sh');
    }

    public function testUpdate8_5_2()
    {
        $this->runScriptInDocker('mlocati/docker5:8.5.2-full', 'run-update.sh');
    }
}

Test upgrading from concrete5 8.5.2

Test upgrading from concrete5 8.5.2


<?php
/**
 * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace OCP\BackgroundJob;

interface IJob {
	/**
	 * @param \OCP\BackgroundJob\IJobList $jobList
	 * @param \OC\Log $logger
	 */
	public function execute($jobList, $logger = null);

	public function setId($id);

	public function setLastRun($lastRun);

	public function setArgument($argument);

	public function getId();

	public function getLastRun();

	public function getArgument();
}

<?php
/**
 * Copyright (c) 2014 Robin Appelman <icewind@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

namespace OCP\BackgroundJob;

interface IJob {
	/**
	 * @param \OCP\BackgroundJob\IJobList $jobList
	 * @param \OC\Log $logger
	 */
	public function execute($jobList, $logger = null);

	public function getId();

	public function getLastRun();

	public function getArgument();
}

Remove internal methods from the public interface


<?php

/**
 * Show a warning to an user about the SP requesting SSO a short time after
 * doing it previously.
 *
 * @package SimpleSAMLphp
 */

if (!array_key_exists('StateId', $_REQUEST)) {
    throw new \SimpleSAML\Error\BadRequest('Missing required StateId query parameter.');
}
$id = $_REQUEST['StateId'];
$state = \SimpleSAML\Auth\State::loadState($id, 'core:short_sso_interval');
$session = \SimpleSAML\Session::getSessionFromRequest();

if (array_key_exists('continue', $_REQUEST)) {
    // The user has pressed the continue/retry-button
    \SimpleSAML\Auth\ProcessingChain::resumeProcessing($state);
}

$globalConfig = \SimpleSAML\Configuration::getInstance();
$t = new \SimpleSAML\XHTML\Template($globalConfig, 'core:short_sso_interval.php');
$t->data['target'] = \SimpleSAML\Module::getModuleURL('core/short_sso_interval.php');
$t->data['params'] = ['StateId' => $id];
$t->data['trackId'] = $session->getTrackID();
$this->data['header'] = $this->t('{core:short_sso_interval:warning_header}');
$this->data['autofocus'] = 'contbutton';
$t->show();

<?php

/**
 * Show a warning to an user about the SP requesting SSO a short time after
 * doing it previously.
 *
 * @package SimpleSAMLphp
 */

if (!array_key_exists('StateId', $_REQUEST)) {
    throw new \SimpleSAML\Error\BadRequest('Missing required StateId query parameter.');
}
$id = $_REQUEST['StateId'];
$state = \SimpleSAML\Auth\State::loadState($id, 'core:short_sso_interval');
$session = \SimpleSAML\Session::getSessionFromRequest();

if (array_key_exists('continue', $_REQUEST)) {
    // The user has pressed the continue/retry-button
    \SimpleSAML\Auth\ProcessingChain::resumeProcessing($state);
}

$globalConfig = \SimpleSAML\Configuration::getInstance();
$t = new \SimpleSAML\XHTML\Template($globalConfig, 'core:short_sso_interval.php');
$translator = $t->getTranslator();
$t->data['target'] = \SimpleSAML\Module::getModuleURL('core/short_sso_interval.php');
$t->data['params'] = ['StateId' => $id];
$t->data['trackId'] = $session->getTrackID();
$t->data['header'] = $translator->t('{core:short_sso_interval:warning_header}');
$t->data['autofocus'] = 'contbutton';
$t->show();

Fix invalid use of $this

Fix invalid use of $this


<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier {

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		return parent::handle($request, $next);
	}

}

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier {

	/**
	 * The URIs that should be excluded from CSRF verification.
	 *
	 * @var array
	 */
	protected $except = [
		'api/*'
	];

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		return parent::handle($request, $next);
	}

}

Disable CSRF protection for REST API

Disable CSRF protection for REST API

CSRF protection doesn't make sense for completely stateless APIs like
this one.


@section("field")
    <div class="select2-tags">
        <select name="{{ $prefixed_field_name }}[]" class="form-control" id="{{ $field_id }}" multiple>
            @foreach((array) $field_value as $value)
                <option value="{{ $value }}" selected>{{ $value }}</option>
            @endforeach
        </select>
    </div>
@overwrite

@section('footer.js')
    @parent
    <script>
        $(function(){
            $('#{{ $field_id }}').select2({
                tags: true,
                multiple: true,
                //dropdownCssClass: 'hide',
                {!! app('soda.form')->buildJsParams($field_parameters['settings']) !!}
            });
        });
    </script>
@stop

@section("field")
    <div class="select2-tags">
        <select name="{{ $prefixed_field_name }}[]" class="form-control" id="{{ $field_id }}" multiple>
            @foreach((array) $field_value as $value)
                <option value="{{ $value }}" selected>{{ $value }}</option>
            @endforeach
        </select>
    </div>
@overwrite

@section('footer.js')
    @parent
    <script>
        $(function(){
            $('#{{ $field_id }}').select2({
                tags: true,
                multiple: true,
                selectOnClose: true,
                matcher: function(searchParams, data) {
                    // This bit taken from Select2's default matcher
                    var match = $.extend(true, {}, data);

                    // Don't partial match tags, otherwise if a user has a tag 'abc' it is
                    // impossible to then create a tag 'ab'.
                    if (searchParams.term === data.text)
                        return match;
                    return null;
                },
                dropdownCssClass: 'hide',
                {!! app('soda.form')->buildJsParams($field_parameters['settings']) !!}
            });

            $('#{{ $field_id }}').on('select2:unselect', function(e){
                $(e.params.data.element).remove();
            });
        });
    </script>
@stop

Fix select2 tags, keeping the dropdown hidden


Change URL log viewer on navigation

Change URL log viewer on navigation


<?php

namespace WP_CLI;

/**
 * Class AutoloadSplitter.
 *
 * This class is used to provide the splitting logic to the
 * `wp-cli/autoload-splitter` Composer plugin.
 *
 * @package WP_CLI
 */
class AutoloadSplitter {

	/**
	 * Check whether the current class should be split out into a separate
	 * autoloader.
	 *
	 * Note: `class` in this context refers to all PHP autoloadable elements:
	 *    - classes
	 *    - interfaces
	 *    - traits
	 *
	 * @param string $class Fully qualified name of the current class.
	 * @param string $code  Path to the code file that declares the class.
	 *
	 * @return bool Whether to split out the class into a separate autoloader.
	 */
	public function __invoke( $class, $code ) {
		return 1 === preg_match( '/.*\/wp-cli\/\w*-command\/.*/', $code )
			|| 1 === preg_match( '/.*\/php\/commands\/src\/.*/', $code );
	}
}

<?php

namespace WP_CLI;

/**
 * Class AutoloadSplitter.
 *
 * This class is used to provide the splitting logic to the
 * `wp-cli/autoload-splitter` Composer plugin.
 *
 * @package WP_CLI
 */
class AutoloadSplitter {

	/**
	 * Check whether the current class should be split out into a separate
	 * autoloader.
	 *
	 * Note: `class` in this context refers to all PHP autoloadable elements:
	 *    - classes
	 *    - interfaces
	 *    - traits
	 *
	 * @param string $class Fully qualified name of the current class.
	 * @param string $code  Path to the code file that declares the class.
	 *
	 * @return bool Whether to split out the class into a separate autoloader.
	 */
	public function __invoke( $class, $code ) {
		return 1 === preg_match( '/.*\/wp-cli\/\w*(?:-\w*)*-command\/.*/', $code )
			|| 1 === preg_match( '/.*\/php\/commands\/src\/.*/', $code );
	}
}

Improve regex to detect commands by allowing multiple sections separated with a dash.


<?php
$config['db']['host']           = "";
$config['db']['user']           = "";
$config['db']['pass']           = "";
$config['db']['name']           = "";

$config['captcha']['pub']       = "";
$config['captcha']['priv']      = "";

$config['twilio']['sid']        = "";
$config['twilio']['token']      = "";
$config['twilio']['number']     = "";

$pdo = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['name'] .
                                                ';charset=utf8', $config['db']['user'], $config['db']['pass']);

<?php
$config['db']['host']           = "";
$config['db']['user']           = "";
$config['db']['pass']           = "";
$config['db']['name']           = "";

$config['captcha']['pub']       = "";
$config['captcha']['priv']      = "";

$config['twilio']['sid']        = "";
$config['twilio']['token']      = "";
$config['twilio']['number']     = "";

//$pdo = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['name'] . ';charset=utf8', $config['db']['user'], $config['db']['pass']);

Comment out db for testing

Comment out db for testing


<?php namespace Kironuniversity\Git\Controllers;

use BackendMenu;
use Backend\Classes\Controller;
use GitWrapper\GitWrapper;
use Flash;
/**
 * Deploy Back-end Controller
 */
class Deploy extends Controller
{

    public function __construct()
    {
        parent::__construct();

        BackendMenu::setContext('Kironuniversity.Git', 'git', 'deploy');
    }

    public function index(){
      $wrapper = new GitWrapper('git');
      $git =  $wrapper->workingCopy('.');
      $this->vars['changed'] = $git->hasChanges();
      $this->vars['changes'] = nl2br($git->status(['porcelain' => true,
      'u' => true])->getOutput());
    }

    public function onPush(){
      $wrapper = new GitWrapper('git');
      $wrapper->git('config --global push.default simple');
      $git =  $wrapper->workingCopy('.');
      $git->checkout('dev');
      $pushLog =  '';
      $mergeLog = '';
      if($git->hasChanges()){
        $pushLog =  nl2br($git->add(env('GITDIR'))->commit('content updates')->pull()->push()->getOutput());
        $mergeLog = nl2br($git->checkout('master')->merge('dev')->push()->checkout('dev')->getOutput());
      }
      Flash::success('Done');
      return ['#output' => '
'.$pushLog.'

'.$mergeLog.'
'];
    }
}

<?php namespace Kironuniversity\Git\Controllers;

use BackendMenu;
use Backend\Classes\Controller;
use GitWrapper\GitWrapper;
use Flash;
/**
 * Deploy Back-end Controller
 */
class Deploy extends Controller
{

    public function __construct()
    {
        parent::__construct();

        BackendMenu::setContext('Kironuniversity.Git', 'git', 'deploy');
    }

    public function index(){
      $wrapper = new GitWrapper('git');
      $git =  $wrapper->workingCopy('.');
      $this->vars['changed'] = $git->hasChanges();
      $this->vars['changes'] = nl2br($git->status(['porcelain' => true,
      'u' => true])->getOutput());
    }

    public function onPush(){
      $wrapper = new GitWrapper('git');
      $wrapper->git('config --global push.default simple');
      $git =  $wrapper->workingCopy('.');
      $git->checkout('dev');
      $pushLog =  '';
      $mergeLog = '';
      if($git->hasChanges()){
        $pushLog =  nl2br($git->add(env('GITDIR'))->commit('content updates')->pull()->push()->getOutput());
        $mergeLog = nl2br($git->checkout('master')->pull()->merge('dev')->->push()->checkout('dev')->getOutput());
      }
      Flash::success('Done');
      return ['#output' => '
'.$pushLog.'

'.$mergeLog.'
'];
    }
}

Add pull before pushing to master

Add pull before pushing to master


<?php

namespace estvoyage\data\tests\units\consumer;

require __DIR__ . '/../../runner.php';

use
	estvoyage\data\tests\units,
	estvoyage\data,
	mock\estvoyage\data as mockOfData
;

class blackhole extends units\test
{
	function testClass()
	{
		$this->testedClass
			->implements('estvoyage\data\consumer')
			->isFinal
		;
	}

	function testNewData()
	{
		$this
			->given(
				$data = new data\data
			)
			->if(
				$this->newTestedInstance
			)
			->then
				->object($this->testedInstance->newData($data))->isTestedInstance
		;
	}

	function testNoMoreData()
	{
		$this->object($this->testedInstance->noMoreData($data))->isTestedInstance;
	}

	function testDataProviderIs()
	{
		$this
			->given(
				$dataProvider = new mockOfData\provider
			)
			->if(
				$this->newTestedInstance
			)
			->then
				->object($this->testedInstance->dataProviderIs($dataProvider))->isTestedInstance
				->mock($dataProvider)
					->didNotReceiveAnyMessage
		;
	}
}

<?php

namespace estvoyage\data\tests\units\consumer;

require __DIR__ . '/../../runner.php';

use
	estvoyage\data\tests\units,
	estvoyage\data,
	mock\estvoyage\data as mockOfData
;

class blackhole extends units\test
{
	function testClass()
	{
		$this->testedClass
			->implements('estvoyage\data\consumer')
			->isFinal
		;
	}

	function testNewData()
	{
		$this
			->given(
				$data = new data\data
			)
			->if(
				$this->newTestedInstance
			)
			->then
				->object($this->testedInstance->newData($data))->isTestedInstance
		;
	}

	function testNoMoreData()
	{
		$this->object($this->newTestedInstance->noMoreData())->isTestedInstance;
	}

	function testDataProviderIs()
	{
		$this
			->given(
				$dataProvider = new mockOfData\provider
			)
			->if(
				$this->newTestedInstance
			)
			->then
				->object($this->testedInstance->dataProviderIs($dataProvider))->isTestedInstance
				->mock($dataProvider)
					->didNotReceiveAnyMessage
		;
	}
}

Remove bug in unit test.

Remove bug in unit test.


<?php
namespace Thatdamnqa\MancMetFeed;
require_once 'config/config.php';

use Thatdamnqa\MancMetFeed\Services\TwitterNotifierClientFactory;
require __DIR__ . '/../vendor/autoload.php';

$tweetClass = new Tweet(TwitterNotifierClientFactory::getClient());
$metrolinkClass = new Metrolink(new \DateTimeImmutable());
$websiteHandlerClass = new WebsiteHandler(MMS_API_URL);
$statusClass = new Status($websiteHandlerClass, $metrolinkClass);

$statusString = $statusClass->getStatusString();

$tweets = $tweetClass->generate($statusString);

if (null == $tweets) {
} else {
    $first_tweet_id = null;
    foreach ($tweets as $key => $t) {
        $tweetid = $tweetClass->post($t, $first_tweet_id);

        if ($key == 0 && $tweetid) {
            $first_tweet_id = $tweetid;
        }

        if (MMS_DEBUG === true) {
            echo "---\n";
        }
    }
}

<?php
namespace Thatdamnqa\MancMetFeed;
require_once '../config/config.php';

use Thatdamnqa\MancMetFeed\Services\TwitterNotifierClientFactory;
require __DIR__ . '/../vendor/autoload.php';

$tweetClass = new Tweet(TwitterNotifierClientFactory::getClient());
$metrolinkClass = new Metrolink(new \DateTimeImmutable());
$websiteHandlerClass = new WebsiteHandler(MMS_API_URL);
$statusClass = new Status($websiteHandlerClass, $metrolinkClass);

$statusString = $statusClass->getStatusString();

$tweets = $tweetClass->generate($statusString);

if (null == $tweets) {
} else {
    $first_tweet_id = null;
    foreach ($tweets as $key => $t) {
        $tweetid = $tweetClass->post($t, $first_tweet_id);

        if ($key == 0 && $tweetid) {
            $first_tweet_id = $tweetid;
        }

        if (MMS_DEBUG === true) {
            echo "---\n";
        }
    }
}

Correct the path to the config file

Correct the path to the config file


<?php

namespace Asynit\Parser;

use Asynit\Test;
use Asynit\TestCase;
use Symfony\Component\Finder\Finder;

class TestsFinder
{
    public function findTests(string $path): array
    {
        if (\is_file($path)) {
            return $this->doFindTests([$path]);
        }

        $finder = Finder::create()
            ->files()
            ->name('*.php')
            ->in($path)
        ;

        return $this->doFindTests($finder);
    }

    private function doFindTests($files): array
    {
        foreach ($files as $file) {
            $existingClasses = get_declared_classes();
            $path = $file;

            if ($path instanceof \SplFileInfo) {
                $path = $path->getRealPath();
            }

            require_once $path;

            $newClasses = array_diff(get_declared_classes(), $existingClasses);

            foreach ($newClasses as $class) {
                if (!is_subclass_of($class, TestCase::class)) {
                    continue;
                }

                foreach (get_class_methods($class) as $method) {
                    if (!preg_match('/^test(.+)$/', $method)) {
                        continue;
                    }

                    $test = new Test(new \ReflectionMethod($class, $method));
                    $methods[$test->getIdentifier()] = $test;
                }
            }
        }

        return $methods;
    }
}

<?php

namespace Asynit\Parser;

use Asynit\Test;
use Asynit\TestCase;
use Symfony\Component\Finder\Finder;

class TestsFinder
{
    public function findTests(string $path): array
    {
        if (\is_file($path)) {
            return $this->doFindTests([$path]);
        }

        $finder = Finder::create()
            ->files()
            ->name('*.php')
            ->in($path)
        ;

        return $this->doFindTests($finder);
    }

    private function doFindTests($files): array
    {
        $methods = [];

        foreach ($files as $file) {
            $existingClasses = get_declared_classes();
            $path = $file;

            if ($path instanceof \SplFileInfo) {
                $path = $path->getRealPath();
            }

            require_once $path;

            $newClasses = array_diff(get_declared_classes(), $existingClasses);

            foreach ($newClasses as $class) {
                if (!is_subclass_of($class, TestCase::class)) {
                    continue;
                }

                foreach (get_class_methods($class) as $method) {
                    if (!preg_match('/^test(.+)$/', $method)) {
                        continue;
                    }

                    $test = new Test(new \ReflectionMethod($class, $method));
                    $methods[$test->getIdentifier()] = $test;
                }
            }
        }

        return $methods;
    }
}

Declare vars before using it

Declare vars before using it

If there are not tests, then an exception occurs:

```
PHP Notice:  Undefined variable: methods in PROJECT/vendor/jolicode/asynit/src/Parser/TestsFinder.php on line 56
PHP Fatal error:  Uncaught TypeError: Return value of Asynit\Parser\TestsFinder::doFindTests() must be of the type array, null returned in PROJECT/vendor/jolicode/asynit/src/Parser/TestsFinder.php:56
Stack trace:
#0 PROJECT/vendor/jolicode/asynit/src/Parser/TestsFinder.php(14): Asynit\Parser\TestsFinder->doFindTests(Array)
#1 PROJECT/vendor/jolicode/asynit/src/Command/AsynitCommand.php(62): Asynit\Parser\TestsFinder->findTests('Api/UserOrganiz...')
#2 PROJECT/vendor/symfony/console/Command/Command.php(252): Asynit\Command\AsynitCommand->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#3 PROJECT/vendor/symfony/console/Application.php(938): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#4 PROJECT/vendor/symfony/console/Application.php(240): Symfony\Component\Console\Application->doRunCo in PROJECT/vendor/jolicode/asynit/src/Parser/TestsFinder.php on line 56
```


<?php
// use this to display a message across the whole site; should be used sparingly.
?>

LATEST NEWS:

The multi science bar crawl is coming up soon; it's always one of the best nights out of the year and is definitely not to be missed.

You can pre-book your t-shirt and ticket right here!

Add bannerLink class to links

Add bannerLink class to links


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCountryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('country', function (Blueprint $table) {
            $table->increments('id');

            // Non-translated content
            $table->string('url_name')->unique(); // Name in URL
            $table->integer('image_id')->unsigned()->nullable(); // ID of image

            // Timestamps
            $table->timestamps();
            $table->softDeletes();

            // When deleted image, set image_id to null
            $table->foreign('image_id')->references('id')->on('image')->onDelete('set null');
        });
        Schema::create('country_translation', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('country_id')->unsigned();
            $table->string('language')->index();
            $table->boolean('complete');

            // Translated content
            $table->string('name');
            $table->text('content');

            $table->timestamps();

            // Unique and foreign key
            // When deleting country model, also delete all translation models
            $table->unique(['country_id','language']);
            $table->foreign('country_id')->references('id')->on('country')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('country_translation');
        Schema::drop('country');
    }
}

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCountryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('country', function (Blueprint $table) {
            $table->increments('id');

            // Non-translated content
            $table->string('url_name')->unique(); // Name in URL
            $table->integer('image_id')->unsigned()->nullable(); // ID of image
            $table->string('country_code')->unique(); // Name in URL

            // Timestamps
            $table->timestamps();
            $table->softDeletes();

            // When deleted image, set image_id to null
            $table->foreign('image_id')->references('id')->on('image')->onDelete('set null');
        });
        Schema::create('country_translation', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('country_id')->unsigned();
            $table->string('language')->index();
            $table->boolean('complete');

            // Translated content
            $table->string('name');
            $table->text('content');

            $table->timestamps();

            // Unique and foreign key
            // When deleting country model, also delete all translation models
            $table->unique(['country_id','language']);
            $table->foreign('country_id')->references('id')->on('country')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('country_translation');
        Schema::drop('country');
    }
}

Add country code to country table.

Add country code to country table.


<?php

namespace Pterodactyl\Transformers\Api\Client;

use Illuminate\Support\Arr;

class StatsTransformer extends BaseClientTransformer
{
    public function getResourceName(): string
    {
        return 'stats';
    }

    /**
     * Transform stats from the daemon into a result set that can be used in
     * the client API.
     *
     * @return array
     */
    public function transform(array $data)
    {
        return [
            'current_state' => Arr::get($data, 'state', 'stopped'),
            'is_suspended' => Arr::get($data, 'suspended', false),
            'resources' => [
                'memory_bytes' => Arr::get($data, 'memory_bytes', 0),
                'cpu_absolute' => Arr::get($data, 'cpu_absolute', 0),
                'disk_bytes' => Arr::get($data, 'disk_bytes', 0),
                'network_rx_bytes' => Arr::get($data, 'network.rx_bytes', 0),
                'network_tx_bytes' => Arr::get($data, 'network.tx_bytes', 0),
            ],
        ];
    }
}

<?php

namespace Pterodactyl\Transformers\Api\Client;

use Illuminate\Support\Arr;

class StatsTransformer extends BaseClientTransformer
{
    public function getResourceName(): string
    {
        return 'stats';
    }

    /**
     * Transform stats from the daemon into a result set that can be used in
     * the client API.
     *
     * @return array
     */
    public function transform(array $data)
    {
        return [
            'current_state' => Arr::get($data, 'state', 'stopped'),
            'is_suspended' => Arr::get($data, 'is_suspended', false),
            'resources' => [
                'memory_bytes' => Arr::get($data, 'utilization.memory_bytes', 0),
                'cpu_absolute' => Arr::get($data, 'utilization.cpu_absolute', 0),
                'disk_bytes' => Arr::get($data, 'utilization.disk_bytes', 0),
                'network_rx_bytes' => Arr::get($data, 'utilization.network.rx_bytes', 0),
                'network_tx_bytes' => Arr::get($data, 'utilization.network.tx_bytes', 0),
            ],
        ];
    }
}

Use updated response from wings

Use updated response from wings


<?php
namespace Grav\Common;

/**
 * Simple wrapper for the very simple parse_user_agent() function
 */
class Browser {

    protected $useragent;

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

    public function getBrowser()
    {
        return strtolower($this->useragent['browser']);
    }

    public function getPlatform()
    {
        return strtolower($this->useragent['platform']);
    }

    public function getLongVersion()
    {
        return $this->useragent['version'];
    }

    public function getVersion()
    {
        $version = explode('.', $this->getLongVersion());
        return intval($version[0]);
    }
}

<?php
namespace Grav\Common;

/**
 * Simple wrapper for the very simple parse_user_agent() function
 */
class Browser
{

    protected $useragent = [];

    public function __construct()
    {
        try {
            $this->useragent = parse_user_agent();
        } catch (\InvalidArgumentException $e) {
            $this->useragent = parse_user_agent("Mozilla/5.0 (compatible; Unknown;)");
        }
    }

    public function getBrowser()
    {
        return strtolower($this->useragent['browser']);
    }

    public function getPlatform()
    {
        return strtolower($this->useragent['platform']);
    }

    public function getLongVersion()
    {
        return $this->useragent['version'];
    }

    public function getVersion()
    {
        $version = explode('.', $this->getLongVersion());
        return intval($version[0]);
    }
}

Fix attempt for invalid/missing user agent string


<?php

namespace Sympla\Auth\Laravel;

use GuzzleHttp\Client as Guzzle;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use Sympla\Auth\Laravel\OAuthUserProvider;
use Sympla\Auth\PasswordClient;

class ServiceProvider extends BaseServiceProvider
{
    public function boot()
    {
        $this->publishes([$this->configPath() => config_path('sympla.php')]);

        $auth = $this->app->make('auth');

        $auth->provider('oauth', function ($app, array $config) {
            return new OAuthUserProvider(
                $app->make('sympla.oauth.password_client'),
                $config,
                $app->make('request')
            );
        });
    }

    public function register()
    {
        $this->mergeConfigFrom($this->configPath(), 'sympla');

        $this->app->bind('sympla.oauth.password_client', function ($app) {
            $config = $app->config['sympla']['oauth'];

            return new PasswordClient(
                new Guzzle(),
                $config['client_id'],
                $config['client_secret'],
                $config['user_endpoint'],
                $config['token_endpoint'],
                $config['auth_method']
            );
        });
    }

    protected function configPath()
    {
        return __DIR__ . '/../../config/sympla.php';
    }
}

<?php

namespace Sympla\Auth\Laravel;

use GuzzleHttp\Client as Guzzle;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use Sympla\Auth\Laravel\OAuthUserProvider;
use Sympla\Auth\PasswordClient;

class ServiceProvider extends BaseServiceProvider
{
    public function boot()
    {
        $this->publishes([$this->configPath() => config_path('sympla.php')]);

        $auth = $this->app->make('auth');

        $auth->provider('oauth', function ($app, array $config) {
            return new OAuthUserProvider(
                $app->make('sympla.oauth.password_client'),
                $config,
                $app->make('request')
            );
        });
    }

    public function register()
    {
        $this->mergeConfigFrom($this->configPath(), 'sympla');

        $this->app->bind('sympla.oauth.password_client', function ($app) {
            $config = $app->config['sympla']['oauth'];

            return new PasswordClient(
                new Guzzle(),
                $config['client_id'],
                $config['client_secret'],
                $config['user_endpoint'],
                $config['token_endpoint'],
                $config['auth_method'],
                $config['client_provider'],
                $config['client_domain'],
                $config['client_service_account']
            );
        });
    }

    protected function configPath()
    {
        return __DIR__ . '/../../config/sympla.php';
    }
}

Fix checkprovider - parameters on service provider missing


<?php
namespace League\Tactician\Doctrine\ORM;

use Doctrine\ORM\EntityManagerInterface;
use League\Tactician\Command;
use Error;
use Exception;
use League\Tactician\Middleware;

/**
 * Wraps command execution inside a Doctrine ORM transaction
 */
class TransactionMiddleware implements Middleware
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * @param EntityManagerInterface $entityManager
     */
    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * Executes the given command and optionally returns a value
     *
     * @param object $command
     * @param callable $next
     * @return mixed
     * @throws Exception
     */
    public function execute($command, callable $next)
    {
        $this->entityManager->beginTransaction();

        try {
            $returnValue = $next($command);

            $this->entityManager->flush();
            $this->entityManager->commit();
        } catch (Exception $e) {
            $this->entityManager->close();
            $this->entityManager->rollback();
            throw $e;
        } catch (Error $e) {
            $this->entityManager->close();
            $this->entityManager->rollback();
            throw $e;
        }

        return $returnValue;
    }
}

<?php
namespace League\Tactician\Doctrine\ORM;

use Doctrine\ORM\EntityManagerInterface;
use League\Tactician\Command;
use Exception;
use League\Tactician\Middleware;
use Throwable;

/**
 * Wraps command execution inside a Doctrine ORM transaction
 */
class TransactionMiddleware implements Middleware
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * @param EntityManagerInterface $entityManager
     */
    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * Executes the given command and optionally returns a value
     *
     * @param object $command
     * @param callable $next
     * @return mixed
     * @throws Throwable
     */
    public function execute($command, callable $next)
    {
        $this->entityManager->beginTransaction();

        try {
            $returnValue = $next($command);

            $this->entityManager->flush();
            $this->entityManager->commit();
        } catch (Exception $e) {
            $this->entityManager->close();
            $this->entityManager->rollback();
            throw $e;
        } catch (Throwable $e) {
            $this->entityManager->close();
            $this->entityManager->rollback();
            throw $e;
        }

        return $returnValue;
    }
}

Use Throwable and fixed throws annotation


<?php

namespace HeyUpdate\EmojiBundle\Twig\Extension;

use HeyUpdate\Emoji\Emoji;

class EmojiExtension extends \Twig_Extension
{
    protected $emoji;

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

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('emoji', [$this->emoji, 'replaceEmojiWithImages'], [
                'is_safe' => ['html'],
            ]),
            new \Twig_SimpleFunction('emoji_name_image', [$this->emoji, 'getEmojiImageByName'], [
                'is_safe' => ['html'],
            ]),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('emoji', [$this->emoji, 'replaceEmojiWithImages'], [
                'is_safe' => ['html'],
            ]),
            new \Twig_SimpleFilter('emoji_name_image', [$this->emoji, 'getEmojiImageByName'], [
                'is_safe' => ['html'],
            ]),
        ];
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'emoji';
    }
}

<?php

namespace HeyUpdate\EmojiBundle\Twig\Extension;

use HeyUpdate\Emoji\Emoji;

class EmojiExtension extends \Twig_Extension
{
    protected $emoji;

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

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('emoji', [$this->emoji, 'replaceEmojiWithImages'], [
                'is_safe' => ['html'],
            ]),
            new \Twig_SimpleFunction('emoji_name_image', [$this->emoji, 'getEmojiImageByName'], [
                'is_safe' => ['html'],
            ]),
            new \Twig_SimpleFunction('emoji_unicode_image', [$this->emoji, 'getEmojiImageByUnicode'], [
                'is_safe' => ['html'],
            ]),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('emoji', [$this->emoji, 'replaceEmojiWithImages'], [
                'is_safe' => ['html'],
            ]),
            new \Twig_SimpleFilter('emoji_name_image', [$this->emoji, 'getEmojiImageByName'], [
                'is_safe' => ['html'],
            ]),
            new \Twig_SimpleFilter('emoji_unicode_image', [$this->emoji, 'getEmojiImageByUnicode'], [
                'is_safe' => ['html'],
            ]),
        ];
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'emoji';
    }
}

Add unicode to image helpers

Add unicode to image helpers


<?php
class ControllerExtensionModuleV2pagecache extends Controller {
    public function index() {
       ;
    }
    public function set_cookie() {
        $fp=fopen("/tmp/sclog.txt","a");
        fwrite($fp,"event called\n");
        $cart=$this->registry->get('cart');
        global $v2pcresponse;
        $v2pcresponse=$this->registry->get('response');
        //$rdump=print_r($this->registry,1);
        //$cdump=print_r($cart,1);
        //fwrite($fp,"cdump [$cdump]\n");
        if ($cart->hasProducts()) {
            $_SESSION['carthasitems']=1;
        } else {
            unset($_SESSION['carthasitems']);
        }
        fclose($fp);
    }
}

<?php
class ControllerExtensionModuleV2pagecache extends Controller {
    public function index() {
       ;
    }
    public function set_cookie() {
        $cart=$this->registry->get('cart');
        global $v2pcresponse;
        $v2pcresponse=$this->registry->get('response');
        if ($cart->hasProducts()) {
            $_SESSION['carthasitems']=1;
        } else {
            unset($_SESSION['carthasitems']);
        }
    }
}

Remove logging code from event

Remove logging code from event


<?php
    namespace Library;

    class Session
    {
        /**
         * Default session expire is 1 day
         *
         * @var int
         */
        private $expire = 86400;

        /**
         * Session that have long Expiration
         *
         * @var int
         */
        private $longExpire = 31536000;

        public function set($name, $value, $persist=false)
        {
            setcookie($name, $value, time()+($persist?$this->longExpire:$this->expire),
                page()->uri->subdir());
        }

        public function remove($name)
        {
            setcookie($name, '', -1, page()->uri->subdir());
        }
    }

?>

<?php
    namespace Library;

    class Session
    {
        /**
         * Default session expire is 1 day
         *
         * @var int
         */
        private $expire = 86400;

        /**
         * Session that have long Expiration
         *
         * @var int
         */
        private $longExpire = 31536000;

        /**
         * Set session
         *
         * @param string $name    Session name
         * @param string $value   Session value
         * @param bool   $persist Set if session is persistent (have long expire time), or not.
         */
        public function set($name, $value, $persist=false)
        {
            setcookie($name, $value, time()+($persist?$this->longExpire:$this->expire),
                page()->uri->subdir());
        }

        /**
         * Remove session
         *
         * @param  string $name Session name
         */
        public function remove($name)
        {
            setcookie($name, '', -1, page()->uri->subdir());
        }
    }

?>

Add doc to session class method

Add doc to session class method


<?php

namespace Pheasant\Tests;

class EnumeratorTest extends \Pheasant\Tests\MysqlTestCase
{
    public function setUp()
    {
        parent::setUp();
    }

    public function testEnumerating()
    {
        $dir = __DIR__.'/examples';
        $files = array_map(function($f) { return substr(basename($f),0,-4); },
            glob($dir.'/*.php'));

        $enumerator = new \Pheasant\Migrate\Enumerator($dir);
        $objects = iterator_to_array($enumerator);

        foreach($files as $file)
            $this->assertContains('\\Pheasant\\Tests\\Examples\\'.$file, $objects);
    }
}

<?php

namespace Pheasant\Tests;

class EnumeratorTest extends \Pheasant\Tests\MysqlTestCase
{
    public function setUp()
    {
        parent::setUp();
    }

    public function testEnumerating()
    {
        $dir = __DIR__.'/Examples';
        $files = array_map(function($f) { return substr(basename($f),0,-4); },
            glob($dir.'/*.php'));

        $enumerator = new \Pheasant\Migrate\Enumerator($dir);
        $objects = iterator_to_array($enumerator);

        foreach($files as $file)
            $this->assertContains('\\Pheasant\\Tests\\Examples\\'.$file, $objects);
    }
}

Fix bug with incorrect case in path, damn you HFS


<?php

namespace BitWasp\Bitcoin\Tests;

use BitWasp\Bitcoin\Bitcoin;
use BitWasp\Bitcoin\Crypto\EcAdapter\PhpEcc;
use BitWasp\Bitcoin\Crypto\EcAdapter\Secp256k1;

class AbstractTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @return array
     */
    public function getEcAdapters()
    {
        $math = Bitcoin::getMath();
        $generator = Bitcoin::getGenerator();

        $adapters = array(
            [new PhpEcc($math, $generator)]
        );

        if (extension_loaded('secp256k1')) {
            $adapters[] = [new Secp256k1($math, $generator)];
        }

        return $adapters;
    }
}

<?php

namespace BitWasp\Bitcoin\Tests;

use BitWasp\Bitcoin\Bitcoin;
use BitWasp\Bitcoin\Crypto\EcAdapter\PhpEcc;
use BitWasp\Bitcoin\Crypto\EcAdapter\Secp256k1;

class AbstractTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @return array
     */
    public function getEcAdapters()
    {
        $math = Bitcoin::getMath();
        $generator = Bitcoin::getGenerator();

        $adapters = array(
            [new PhpEcc($math, $generator)]
        );

        if (!defined('HHVM_VERSION') && extension_loaded('secp256k1')) {
            $adapters[] = [new Secp256k1($math, $generator)];
        }

        return $adapters;
    }
}

Disable secp256k1 tests on hhvm

Disable secp256k1 tests on hhvm


<?php

/**
 * This file is part of the Spryker Demoshop.
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Pyz\Yves\Category\ResourceCreator;

use Pyz\Yves\Collector\Creator\AbstractResourceCreator;
use Silex\Application;
use Spryker\Yves\Kernel\BundleControllerAction;
use Spryker\Yves\Kernel\Controller\BundleControllerActionRouteNameResolver;
use Spryker\Zed\Category\CategoryConfig;

class CategoryResourceCreator extends AbstractResourceCreator
{
    /**
     * @return string
     */
    public function getType()
    {
        return CategoryConfig::RESOURCE_TYPE_CATEGORY_NODE;
    }

    /**
     * @param \Silex\Application $application
     * @param array $data
     *
     * @return array
     */
    public function createResource(Application $application, array $data)
    {
        $bundleControllerAction = new BundleControllerAction('Catalog', 'Catalog', 'index');
        $routeResolver = new BundleControllerActionRouteNameResolver($bundleControllerAction);

        $service = $this->createServiceForController($application, $bundleControllerAction, $routeResolver);

        return [
            '_controller' => $service,
            '_route' => $routeResolver->resolve(),
            'categoryNode' => $data,
        ];
    }
}

<?php

/**
 * This file is part of the Spryker Demoshop.
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Pyz\Yves\Category\ResourceCreator;

use Pyz\Yves\Collector\Creator\AbstractResourceCreator;
use Silex\Application;
use Spryker\Shared\Category\CategoryConfig;
use Spryker\Yves\Kernel\BundleControllerAction;
use Spryker\Yves\Kernel\Controller\BundleControllerActionRouteNameResolver;

class CategoryResourceCreator extends AbstractResourceCreator
{
    /**
     * @return string
     */
    public function getType()
    {
        return CategoryConfig::RESOURCE_TYPE_CATEGORY_NODE;
    }

    /**
     * @param \Silex\Application $application
     * @param array $data
     *
     * @return array
     */
    public function createResource(Application $application, array $data)
    {
        $bundleControllerAction = new BundleControllerAction('Catalog', 'Catalog', 'index');
        $routeResolver = new BundleControllerActionRouteNameResolver($bundleControllerAction);

        $service = $this->createServiceForController($application, $bundleControllerAction, $routeResolver);

        return [
            '_controller' => $service,
            '_route' => $routeResolver->resolve(),
            'categoryNode' => $data,
        ];
    }
}

Fix wrong Zed in Yves usage.

Fix wrong Zed in Yves usage.


<?php
namespace ZendTest\Barcode\Object\TestAsset;

class BarcodeTest extends \Zend\Barcode\Object\AbstractObject
{

    protected function _calculateBarcodeWidth()
    {
        return 1;
    }

    public function validateText($value)
    {}

    protected function _prepareBarcode()
    {
        return array();
    }

    protected function _checkParams()
    {}

    public function addInstruction(array $instruction)
    {
        $this->_addInstruction($instruction);
    }

    public function addPolygon(array $points, $color = null, $filled = true)
    {
        $this->_addPolygon($points, $color, $filled);
    }

    public function addText($text, $size, $position, $font, $color, $alignment = 'center', $orientation = 0)
    {
        $this->_addText($text, $size, $position, $font, $color, $alignment, $orientation);
    }
}

<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * 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@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Barcode
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

namespace ZendTest\Barcode\Object\TestAsset;

/**
 * @category   Zend
 * @package    Zend_Barcode
 * @subpackage UnitTests
 * @group      Zend_Barcode
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class BarcodeTest extends \Zend\Barcode\Object\AbstractObject
{

    protected function _calculateBarcodeWidth()
    {
        return 1;
    }

    public function validateText($value)
    {}

    protected function _prepareBarcode()
    {
        return array();
    }

    protected function _checkParams()
    {}

    public function addInstruction(array $instruction)
    {
        $this->_addInstruction($instruction);
    }

    public function addPolygon(array $points, $color = null, $filled = true)
    {
        $this->_addPolygon($points, $color, $filled);
    }

    public function addText($text, $size, $position, $font, $color, $alignment = 'center', $orientation = 0)
    {
        $this->_addText($text, $size, $position, $font, $color, $alignment, $orientation);
    }
}

Fix unit tests, they were not working because of namespace changes and class refactoring.


<?php

namespace BinSoul\Common\I18n;

/**
 * Formats decimal numbers.
 */
interface NumberFormatter
{
    /**
     * Formats a decimal number.
     *
     * @param float $value
     * @param int   $decimals maximum number of fractional digits
     *
     * @return string
     */
    public function formatDecimal($value, $decimals = null);

    /**
     * Formats a decimal number as a percent value.
     *
     * @param float $value
     * @param int   $decimals maximum number of fractional digits
     *
     * @return string
     */
    public function formatPercent($value, $decimals = null);

    /**
     * Formats a decimal number as a currency value.
     *
     * @param float  $value
     * @param string $currencyCode ISO3 code of the currency
     *
     * @return string
     */
    public function formatCurrency($value, $currencyCode);

    /**
     * Returns a new instance with the given locale.
     *
     * @param Locale $locale
     *
     * @return self
     */
    public function withLocale(Locale $locale);
}

<?php

namespace BinSoul\Common\I18n;

/**
 * Formats decimal numbers.
 */
interface NumberFormatter
{
    /**
     * Formats a decimal number.
     *
     * @param float $value
     * @param int   $decimals maximum number of fractional digits
     *
     * @return string
     */
    public function formatDecimal($value, $decimals = null);

    /**
     * Formats a decimal number as a percent value.
     *
     * @param float $value
     * @param int   $decimals maximum number of fractional digits
     *
     * @return string
     */
    public function formatPercent($value, $decimals = null);

    /**
     * Formats a decimal number as a currency value.
     *
     * @param float  $value
     * @param string $currencyCode ISO3 code of the currency
     *
     * @return string
     */
    public function formatCurrency($value, $currencyCode = '');

    /**
     * Returns a new instance with the given locale.
     *
     * @param Locale $locale
     *
     * @return self
     */
    public function withLocale(Locale $locale);
}

Make currency code parameter optional

Make currency code parameter optional


<?php

OC::$CLASSPATH['OC_RoundCube_AuthHelper'] = OC_App::getAppPath('roundcube') . '/lib/RoundCubeAuthHelper.class.php';

$this->create('roundcube_refresh', '/refresh')->post()->action('OC_RoundCube_AuthHelper', 'refresh');
$this->create('roundcube_index', '/')->action(
		function($params){
			require '/../index.php';
		}
);

<?php

OC::$CLASSPATH['OC_RoundCube_AuthHelper'] = OC_App::getAppPath('roundcube') . '/lib/RoundCubeAuthHelper.class.php';

$this->create('roundcube_refresh', '/refresh')->post()->action('OC_RoundCube_AuthHelper', 'refresh');

$this->create('roundcube_index', '/')->action(
		function($params){
			require OC_App::getAppPath('roundcube').'/index.php';
		}
);

Use correct path for index page

Use correct path for index page

see #301


<?php

use PHPUnit\Framework\TestCase;
use Ratchet\Client\Connector;
use React\EventLoop\Factory;
use React\Promise\RejectedPromise;
use React\Socket\ConnectorInterface as ReactConnector;

class ConnectorTest extends TestCase
{
    public function uriDataProvider() {
        return [
            ['ws://127.0.0.1', 'tcp://127.0.0.1:80'],
            ['wss://127.0.0.1', 'tls://127.0.0.1:443'],
            ['ws://127.0.0.1:1234', 'tcp://127.0.0.1:1234'],
            ['wss://127.0.0.1:4321', 'tls://127.0.0.1:4321']
        ];
    }

    /**
     * @requires PHP 5.5
     * @dataProvider uriDataProvider
     */
    public function testSecureConnectionUsesTlsScheme($uri, $expectedConnectorUri) {
        $loop = Factory::create();

        $connector = $this->getMock(ReactConnector::class);

        $connector->expects($this->once())
            ->method('connect')
            ->with($this->callback(function ($uri) use ($expectedConnectorUri) {
                return $uri === $expectedConnectorUri;
            }))
            // reject the promise so that we don't have to mock a connection here
            ->willReturn(new RejectedPromise(new Exception('')));

        $pawlConnector = new Connector($loop, $connector);

        $pawlConnector($uri);
    }
}

<?php

use PHPUnit\Framework\TestCase;
use Ratchet\Client\Connector;
use React\EventLoop\Factory;
use React\Promise\RejectedPromise;

class ConnectorTest extends TestCase
{
    public function uriDataProvider() {
        return [
            ['ws://127.0.0.1', 'tcp://127.0.0.1:80'],
            ['wss://127.0.0.1', 'tls://127.0.0.1:443'],
            ['ws://127.0.0.1:1234', 'tcp://127.0.0.1:1234'],
            ['wss://127.0.0.1:4321', 'tls://127.0.0.1:4321']
        ];
    }

    /**
     * @dataProvider uriDataProvider
     */
    public function testSecureConnectionUsesTlsScheme($uri, $expectedConnectorUri) {
        $loop = Factory::create();

        $connector = $this->getMock('React\Socket\ConnectorInterface');

        $connector->expects($this->once())
            ->method('connect')
            ->with($this->callback(function ($uri) use ($expectedConnectorUri) {
                return $uri === $expectedConnectorUri;
            }))
            // reject the promise so that we don't have to mock a connection here
            ->willReturn(new RejectedPromise(new Exception('')));

        $pawlConnector = new Connector($loop, $connector);

        $pawlConnector($uri);
    }
}

Make tests work with php 5.4

Make tests work with php 5.4


<?php

Yii::import('bootstrap.widgets.TbMenu');

class MlLanguageMenu extends TbMenu
{
	/**
	 * Initializes the widget.
	 */
	public function init()
	{
		$languages = Yii::app()->getLanguages();
		$activeLocale = Yii::app()->language;

		$items = array(array('label'=>'Language'));

		foreach ($languages as $locale => $language)
		{
			if ($locale === $activeLocale)
				$activeLanguage = $language;

			$items[] = array(
				'label' => $language,
				'url' => array('/site/changeLanguage', 'locale'=>$locale),
				'active' => $locale === $activeLocale,
			);
		}

		$label = isset($activeLanguage) ? $activeLanguage : 'Unknown';
		$this->items = array_merge(array(array('label'=> $label, 'items'=>$items)), $this->items);

		parent::init();
	}
}

<?php

Yii::import('bootstrap.widgets.TbNav');

class MlLanguageMenu extends TbNav
{
	/**
	 * Initializes the widget.
	 */
	public function init()
	{
		$languages = Yii::app()->getLanguages();
		$activeLocale = Yii::app()->language;

		$items = array(array('label'=>'Language'));

		foreach ($languages as $locale => $language)
		{
			if ($locale === $activeLocale)
				$activeLanguage = $language;

			$items[] = array(
				'label' => $language,
				'url' => array('/site/changeLanguage', 'locale'=>$locale),
				'active' => $locale === $activeLocale,
			);
		}

		$label = isset($activeLanguage) ? $activeLanguage : 'Unknown';
		$this->items = array_merge(array(array('label'=> $label, 'items'=>$items)), $this->items);

		parent::init();
	}
}

Upgrade menu widget to use yiistrap

Upgrade menu widget to use yiistrap


<?php

namespace Czogori\DamiBundle\Helper;

use Symfony\Component\Finder\Finder;
use Symfony\Component\Filesystem\Filesystem;

class PreparationMigrationDirectory
{
    private $baseDirectory;
    private $bundles;

    /**
     * Constructor
     *
     * @param string                                                $baseDirectory Base directory for migrations.
     * @param Symfony\Component\HttpKernel\Bundle\BundleInterface[] $bundles       Array of BunleInterface instances.
     */
    public function __construct($baseDirectory, $bundles)
    {
        $this->baseDirectory = $baseDirectory;
        $this->bundles = $bundles;
        $this->fileSystem = new Filesystem();
    }

    /**
     * Prepare migration directory to use.
     *
     * @return void
     */
    public function prepare()
    {
        $migrationDirectory = $this->baseDirectory;
        $this->fileSystem->mkdir($migrationDirectory);

        foreach ($this->bundles as $bundle) {
            $bundleMigrationDirectory = $bundle->getPath() . '/Resources/migrations';
            if (file_exists($bundleMigrationDirectory)) {
                $finder = new Finder();
                $finder->files('*.php')->in($bundleMigrationDirectory);
                foreach ($finder as $file) {
                   $this->fileSystem->copy($file->getRealpath(), $migrationDirectory . '/' . $file->getFilename(), true);
                }
            }
        }
    }
}

<?php

namespace Czogori\DamiBundle\Helper;

use Symfony\Component\Finder\Finder;
use Symfony\Component\Filesystem\Filesystem;

class PreparationMigrationDirectory
{
    private $baseDirectory;
    private $bundles;

    /**
     * Constructor
     *
     * @param string                                                $baseDirectory Base directory for migrations.
     * @param Symfony\Component\HttpKernel\Bundle\BundleInterface[] $bundles       Array of BunleInterface instances.
     */
    public function __construct($baseDirectory, $bundles)
    {
        $this->baseDirectory = $baseDirectory;
        $this->bundles = $bundles;
        $this->fileSystem = new Filesystem();
    }

    /**
     * Prepare migration directory to use.
     *
     * @return void
     */
    public function prepare()
    {
        $migrationDirectory = $this->baseDirectory;
        if ($this->fileSystem->exists($migrationDirectory)) {
            $this->fileSystem->remove(array($migrationDirectory));
        }
        $this->fileSystem->mkdir($migrationDirectory);

        foreach ($this->bundles as $bundle) {
            $bundleMigrationDirectory = $bundle->getPath() . '/Resources/migrations';
            if (file_exists($bundleMigrationDirectory)) {
                $finder = new Finder();
                $finder->files('*.php')->in($bundleMigrationDirectory);
                foreach ($finder as $file) {
                   $this->fileSystem->copy($file->getRealpath(), $migrationDirectory . '/' . $file->getFilename(), true);
                }
            }
        }
    }
}

Remove cache dir before command execute

Remove cache dir before command execute


<?php namespace Orchestra\Support;

use Illuminate\Support\ServiceProvider;

class SupportServiceProvider extends ServiceProvider {

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->registerMessages();
		$this->registerDecorator();
	}

	/**
	 * Register the service provider for Decorator.
	 *
	 * @return void
	 */
	protected function registerDecorator()
	{
		$this->app['orchestra.decorator'] = $this->app->share(function($app)
		{
			return new Decorator;
		});
	}

	/**
	 * Register the service provider for Messages.
	 *
	 * @return void
	 */
	protected function registerMessages()
	{
		$this->app['orchestra.messages'] = $this->app->share(function($app)
		{
			return new Messages;
		});
	}

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->registerMessagesEvents();
	}

	/**
	 * Register the events needed for messages.
	 *
	 * @return void
	 */
	protected function registerMessagesEvents()
	{
		$app = $this->app;

		$app->after(function($request, $response) use ($app)
		{
			$app['orchestra.messages']->shutdown();
		});
	}
}

<?php namespace Orchestra\Support;

use Illuminate\Support\ServiceProvider;

class SupportServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = true;

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->registerMessages();
		$this->registerDecorator();
	}

	/**
	 * Register the service provider for Decorator.
	 *
	 * @return void
	 */
	protected function registerDecorator()
	{
		$this->app['orchestra.decorator'] = $this->app->share(function($app)
		{
			return new Decorator;
		});
	}

	/**
	 * Register the service provider for Messages.
	 *
	 * @return void
	 */
	protected function registerMessages()
	{
		$this->app['orchestra.messages'] = $this->app->share(function($app)
		{
			return new Messages;
		});
	}

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->registerMessagesEvents();
	}

	/**
	 * Register the events needed for messages.
	 *
	 * @return void
	 */
	protected function registerMessagesEvents()
	{
		$app = $this->app;

		$app->after(function($request, $response) use ($app)
		{
			$app->make('orchestra.messages')->shutdown();
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array('orchestra.decorator', 'orchestra.messages');
	}
}

Add provides since this service is deferred.

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php
namespace Imbo\EventListener\AccessToken;

use Imbo\EventListener\AccessToken\AccessTokenGenerator,
    Imbo\EventListener\AccessToken\SHA256;

class MultipleAccessTokenGenerators extends AccessTokenGenerator {
    /**
     * The params array for this generator allows you to define a set of access token signature generators to be used
     * for different url parameters if present. Each will be tried in the sequence defined.
     *
     * 'generators' => [
     *     'accessToken' => new SHA256(),
     *     'dummy' => new Dummy(),
     * ]
     *
     * .. will first try the SHA256() generator if the 'accessToken' parameter is present in the URL, before trying
     * the Dummy generator if the first authentication attempt fails. This allows you to introduce new access token
     * validation schemes while keeping backwards compatible signature algorithms valid.
     *
     * @param array $params Parameters to the MultipleAccessTokenGenerators.
     */
    public function __construct(array $params = []) {
        if (!$params['generators']) {
            $params['generators'] = [];
        }

        parent::__construct($params);
    }

    public function generateSignature($argumentKey, $data, $privateKey) {
        return $this->params['generators'][$argumentKey]->generateSignature($argumentKey, $data, $privateKey);
    }

    public function getArgumentKeys() {
        return array_keys($this->params['generators']);
    }
}

<?php
namespace Imbo\EventListener\AccessToken;

use Imbo\EventListener\AccessToken\AccessTokenGenerator,
    Imbo\EventListener\AccessToken\SHA256;

class MultipleAccessTokenGenerators extends AccessTokenGenerator {
    /**
     * The params array for this generator allows you to define a set of access token signature generators to be used
     * for different url parameters if present. Each will be tried in the sequence defined.
     *
     * 'generators' => [
     *     'accessToken' => new SHA256(),
     *     'dummy' => new Dummy(),
     * ]
     *
     * .. will first try the SHA256() generator if the 'accessToken' parameter is present in the URL, before trying
     * the Dummy generator if the first authentication attempt fails. This allows you to introduce new access token
     * validation schemes while keeping backwards compatible signature algorithms valid.
     *
     * @param array $params Parameters to the MultipleAccessTokenGenerators.
     */
    public function __construct(array $params = []) {
        if (!isset($params['generators'])) {
            $params['generators'] = [];
        }

        parent::__construct($params);
    }

    public function generateSignature($argumentKey, $data, $privateKey) {
        return $this->params['generators'][$argumentKey]->generateSignature($argumentKey, $data, $privateKey);
    }

    public function getArgumentKeys() {
        return array_keys($this->params['generators']);
    }
}

Add missing isset() when checking for generators


<?php

class CustomisableProductShoppingCart extends Extension {

    /**
     * Augment setup to get item price
     *
     */
    public function augmentSetup() {
        foreach($this->owner->Items as $item) {
            if($item->Customisations && is_array($item->Customisations)) {
                $base_price = $item->Price->RAW();
                $customisations = ArrayList::create();

                foreach($item->Customisations as $customisation) {
                    if($customisation['Price'])
                        $base_price += $customisation['Price'];

                    $customisations->add($customisation);
                }

                $item->Customisations = $customisations;
                $item->Price->setValue($base_price);
            }

            // If tax rate set work out tax
            if($item->TaxRate) {
                $tax = new Currency("Tax");
                $tax->setValue(($item->Price->RAW() / 100) * $item->TaxRate);
                $item->Tax = $tax;
            }
        }
    }

    public function onBeforeSave($items) {
        // Convert customisations back to an array
        foreach($this->owner->items as $item) {
            if($item->Customisations && is_object($item->Customisations)) {
                $customisations = array();

                foreach($item->Customisations as $customisation) {
                    $customisations[] = array(
                        "Title" => $customisation->Title,
                        "Value" => $customisation->Value,
                        "Price" => $customisation->Price
                    );
                }

                $item->Customisations = $customisations;
            }
        }
    }
}

<?php

class CustomisableProductShoppingCart extends Extension {

    /**
     * Augment setup to get item price
     *
     */
    public function augmentSetup() {
        foreach($this->owner->Items as $item) {
            if($item->Customisations && is_array($item->Customisations)) {
                $base_price = $item->Price->RAW();
                $customisations = ArrayList::create();

                foreach($item->Customisations as $customisation) {
                    if($customisation['Price'])
                        $base_price += $customisation['Price'];

                    $customisations->add($customisation);
                }

                $item->Customisations = $customisations;
                $item->Price->setValue($base_price);
            }

            // If tax rate set work out tax
            if($item->TaxRate) {
                $item->Tax = new Currency("Tax");
                $item->Tax->setValue((($item->Price->RAW() - $item->Discount->RAW()) / 100) * $item->TaxRate);
            }
        }
    }

    public function onBeforeSave($items) {
        // Convert customisations back to an array
        foreach($this->owner->items as $item) {
            if($item->Customisations && is_object($item->Customisations)) {
                $customisations = array();

                foreach($item->Customisations as $customisation) {
                    $customisations[] = array(
                        "Title" => $customisation->Title,
                        "Value" => $customisation->Value,
                        "Price" => $customisation->Price
                    );
                }

                $item->Customisations = $customisations;
            }
        }
    }
}

Update shoppingcart setup to use updated tax calculation


<?php

namespace EXS\GeoipProvider\Providers;

use Pimple\ServiceProviderInterface;
use Pimple\Container;

/**
 * Abstract services for Maxmind GeopIp Country Detection
 *
 * Created 1-May-2015
 * @author Damien Demessence <damiend@ex-situ.com>
 * @copyright   Copyright 2015 ExSitu Marketing.
 */
class GeoipProvider implements ServiceProviderInterface
{
    public function register(Container $container)
    {
        $container['exs.serv.geoip'] = ( function ($container) {
            return new \EXS\GeoipProvider\Services\GeoIPService($container['maxmind.database.file']);
        });
    }
}

<?php

namespace EXS\GeoipProvider\Providers;

use Pimple\ServiceProviderInterface;
use Pimple\Container;

/**
 * Abstract services for Maxmind GeopIp Country Detection
 *
 * Created 1-May-2015
 * @author Damien Demessence <damiend@ex-situ.com>
 * @copyright   Copyright 2015 ExSitu Marketing.
 */
class GeoipProvider implements ServiceProviderInterface
{
    public function register(Container $container)
    {
        $container['exs.serv.geoip'] = ( function ($container) {
            return new \EXS\GeoipProvider\Services\GeoipService($container['maxmind.database.file']);
        });
    }
}

Update notes: - typo errors fixed

Update notes:
- typo errors fixed


<?php

  //A PHP script to fetch, return and possibly store the latest headlines from the /r/onion and /r/notonion subreddits.

function getTitles() {
	$feed = implode(file('http://reddit.com/r/nottheonion.rss?limit=100'));
	$xml = simplexml_load_string($feed);
	$json = json_encode($xml);
	$array = json_decode($json,TRUE);
	$feed = implode(file('http://reddit.com/r/theonion.rss?limit=100'));
	$xml = simplexml_load_string($feed);
	$json = json_encode($xml);
	$array2 = json_decode($json,TRUE);

	for ($i = 1; $i < count(array2['channel']['item']); $i++) {
		array_push($array['channel']['item'], $array2['channel']['item'][$i]);
	}

	return $array;
}

	function getArticle() {

	}

?>

<?php

  //A PHP script to fetch, return and possibly store the latest headlines from the /r/onion and /r/notonion subreddits.

function getTitles() {
	$feed = implode(file('http://reddit.com/r/nottheonion.rss?limit=100'));
	$xml = simplexml_load_string($feed);
	$json = json_encode($xml);
	$array = json_decode($json,TRUE);
	$feed = implode(file('http://reddit.com/r/theonion.rss?limit=100'));
	$xml = simplexml_load_string($feed);
	$json = json_encode($xml);
	$array2 = json_decode($json,TRUE);

	for ($i = 1; $i < count(array2['channel']['item']); $i++) {
		array_push($array['channel']['item'], $array2['channel']['item'][$i]);
	}

	return $array;
}

function getArticle() { //Fetch article, display to user.
	$conn = new mysqli("127.0.0.1", "database", "Password1234567890", "articles");
	$query = "SELECT column FROM `allowed`
	ORDER BY RAND()
	LIMIT 1";

	$result = $conn->query($query);
	print_r($result);
}

?>

UPDATE - Started work. Debugging atm

UPDATE - Started work. Debugging atm


<?php

# Copyright (c) 2012 John Reese
# Licensed under the MIT license

form_security_validate( 'plugin_Source_repo_delete' );
access_ensure_global_level( plugin_config_get( 'manage_threshold' ) );

$f_repo_id = gpc_get_string( 'id' );

$t_repo = SourceRepo::load( $f_repo_id );

helper_ensure_confirmed( sprintf( plugin_lang_get( 'ensure_delete' ), $t_repo->name ), plugin_lang_get( 'delete_repository' ) );

SourceRepo::delete( $t_repo->id );

form_security_purge( 'plugin_Source_repo_delete' );
print_successful_redirect( plugin_page( 'index', true ) );

<?php

# Copyright (c) 2012 John Reese
# Licensed under the MIT license

form_security_validate( 'plugin_Source_repo_delete' );
access_ensure_global_level( plugin_config_get( 'manage_threshold' ) );

$f_repo_id = gpc_get_string( 'id' );

$t_repo = SourceRepo::load( $f_repo_id );

$t_message = sprintf( plugin_lang_get( 'ensure_delete' ), string_attribute( $t_repo->name ) );
helper_ensure_confirmed( $t_message, plugin_lang_get( 'delete_repository' ) );

SourceRepo::delete( $t_repo->id );

form_security_purge( 'plugin_Source_repo_delete' );
print_successful_redirect( plugin_page( 'index', true ) );

Fix XSS in Delete Repository page

Fix XSS in Delete Repository page

Fixes #338


<?php

if (isset($group) && $group instanceof Strimoid\Models\Group)
    $url = action('ContentController@showAddForm', ['group' => $group->urlname]);
else
    $url = action('ContentController@showAddForm');

?>

         Dodaj link
         Dodaj treść

Fix icons in add content widget

Fix icons in add content widget


<?php
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Bruno P. Kinoshita, Peter Florijn
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

$factory->define(Nestor\Entities\Projects::class, function (Faker\Generator $faker) {
    return [
        'id' => $faker->numberBetween(1, 1000),
        'name' => $faker->name,
        'description' => $faker->text,
        'project_statuses_id' => $$faker->numberBetween(1, 10),
        'created_by' => $faker->name
    ];
});

<?php
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Bruno P. Kinoshita, Peter Florijn
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

$factory->define(Nestor\Entities\Projects::class, function (Faker\Generator $faker) {
    return [
        'id' => $faker->numberBetween(1, 1000),
        'name' => $faker->name,
        'description' => $faker->text,
        'project_statuses_id' => $faker->numberBetween(1, 10),
        'created_by' => $faker->name
    ];
});

Remove double $ from variable

Remove double $ from variable


<?php

namespace mcordingley\Regression\Algorithm\GradientDescent\Gradient;

final class Linear implements Gradient
{
    /** @var int */
    private $power;

    /**
     * @param int $power
     */
    public function __construct($power = 2)
    {
        $this->power = $power;
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @param float $outcome
     * @return float
     */
    public function cost(array $coefficients, array $features, $outcome)
    {
        return pow(abs($this->predicted($coefficients, $features) - $outcome), $this->power);
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @return float
     */
    private function predicted(array $coefficients, array $features)
    {
        return array_sum(array_map(function ($coefficient, $feature) {
            return $coefficient * $feature;
        }, $coefficients, $features));
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @param float $outcome
     * @return array
     */
    public function gradient(array $coefficients, array $features, $outcome)
    {
        $gradient = [];
        $predicted = $this->predicted($coefficients, $features);

        foreach ($features as $feature) {
            $gradient[] = $this->power * pow(abs($predicted - $outcome), $this->power - 1) * $feature;
        }

        return $gradient;
    }
}

<?php

namespace mcordingley\Regression\Algorithm\GradientDescent\Gradient;

final class Linear implements Gradient
{
    /** @var int */
    private $power;

    /**
     * @param int $power
     */
    public function __construct($power = 2)
    {
        $this->power = $power;
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @param float $outcome
     * @return float
     */
    public function cost(array $coefficients, array $features, $outcome)
    {
        return pow(abs($this->predicted($coefficients, $features) - $outcome), $this->power);
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @return float
     */
    private function predicted(array $coefficients, array $features)
    {
        return array_sum(array_map(function ($coefficient, $feature) {
            return $coefficient * $feature;
        }, $coefficients, $features));
    }

    /**
     * @param array $coefficients
     * @param array $features
     * @param float $outcome
     * @return array
     */
    public function gradient(array $coefficients, array $features, $outcome)
    {
        $gradient = [];
        $iterationConstant = $this->power * pow(abs($this->predicted($coefficients, $features) - $outcome), $this->power - 1);

        foreach ($features as $feature) {
            $gradient[] = $iterationConstant * $feature;
        }

        return $gradient;
    }
}

Move logic out of the loop.

Move logic out of the loop.


<?php namespace Hydrarulz\LaravelMixpanel;

use Illuminate\Support\Facades\Config;
use Mixpanel;

class LaravelMixpanel extends Mixpanel {

    protected $token;

    private static $_instance;

    /**
     * @param array $token
     * @param array $options
     */
    public function __construct($token, array $options = array())
    {
        $this->setToken($token);

        self::$_instance = parent::__construct($this->token, $options = array());
    }

    /**
     * @param bool  $token
     * @param array $options
     * @return LaravelMixpanel
     */
    public static function getInstance($token = false, $options = array())
    {
        if (!$token)
        {
            $token = Config::get('laravel-mixpanel.token');
        }

        /**
         * Init the library and use the generated cookie by the Javascript to identify the user.
         */
        if (!isset(self::$_instance))
        {
            self::$_instance = new LaravelMixpanel($token, $options);

            $mixpanel_cookie = json_decode($_COOKIE['mp_'. $token .'_mixpanel']);
            self::$_instance->identify($mixpanel_cookie->distinct_id);
        }
        return self::$_instance;
    }

    /**
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * @param mixed $token
     */
    public function setToken($token)
    {
        $this->token = $token;
    }
}

<?php namespace Hydrarulz\LaravelMixpanel;

use Illuminate\Support\Facades\Config;
use Mixpanel;

class LaravelMixpanel extends Mixpanel {

    protected $token;

    private static $_instance;

    /**
     * @param array $token
     * @param array $options
     */
    public function __construct($token, array $options = array())
    {
        $this->setToken($token);

        self::$_instance = parent::__construct($this->token, $options = array());
    }

    private static function getUniqueId()
    {
        if (isset($_COOKIE['mp_'. self::getToken() .'_mixpanel']))
        {
            $mixpanel_cookie = json_decode($_COOKIE['mp_'. $token .'_mixpanel']);
            return $mixpanel_cookie->distinct_id;
        }

        return false;
    }

    /**
     * @param bool  $token
     * @param array $options
     * @return LaravelMixpanel
     */
    public static function getInstance($token = false, $options = array())
    {
        if (!$token)
        {
            $token = Config::get('laravel-mixpanel.token');
        }

        /**
         * Init the library and use the generated cookie by the Javascript to identify the user.
         */
        if (!isset(self::$_instance))
        {
            self::$_instance = new LaravelMixpanel($token, $options);

            if (self::getUniqueId())
            {
                self::$_instance->identify(self::getUniqueId());
            }
        }
        return self::$_instance;
    }

    /**
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * @param mixed $token
     */
    public function setToken($token)
    {
        $this->token = $token;
    }
}

Check if the cookie exists before accessing it. Little bit of refactoring also.


<?php

namespace NS\ImportBundle\Linker;

class CaseLinkerRegistry
{
    /**
     * @var array
     */
    private $caseLinkers;

    /**
     * CaseLinkerRegistry constructor.
     * @param $caseLinkers
     */
    public function __construct($caseLinkers = array())
    {
        foreach($caseLinkers as $id => $linker) {
            $this->addLinker($id,$linker);
        }
    }

    /**
     * @param $id
     * @param CaseLinkerInterface $linker
     */
    public function addLinker($id, CaseLinkerInterface $linker)
    {
        $this->caseLinkers[$id] = $linker;
    }

    /**
     * @param $linkerName
     * @return CaseLinkerInterface
     * @throws CaseLinkerNotFoundException
     */
    public function getLinker($linkerName)
    {
        if(isset($this->caseLinkers[$linkerName])) {
            return $this->caseLinkers[$linkerName];
        }

        throw new CaseLinkerNotFoundException('Unable to locate case linker with id %s');
    }

}

<?php

namespace NS\ImportBundle\Linker;

use NS\ImportBundle\Exceptions\CaseLinkerNotFoundException;

class CaseLinkerRegistry
{
    /**
     * @var array
     */
    private $caseLinkers;

    /**
     * CaseLinkerRegistry constructor.
     * @param $caseLinkers
     */
    public function __construct($caseLinkers = array())
    {
        foreach($caseLinkers as $id => $linker) {
            $this->addLinker($id,$linker);
        }
    }

    /**
     * @param $id
     * @param CaseLinkerInterface $linker
     */
    public function addLinker($id, CaseLinkerInterface $linker)
    {
        $this->caseLinkers[$id] = $linker;
    }

    /**
     * @param $linkerName
     * @return CaseLinkerInterface
     * @throws CaseLinkerNotFoundException
     */
    public function getLinker($linkerName)
    {
        if(isset($this->caseLinkers[$linkerName])) {
            return $this->caseLinkers[$linkerName];
        }

        throw new CaseLinkerNotFoundException($linkerName);
    }

}

Fix case linker exception throwing

Fix case linker exception throwing


<?php
namespace NoughtsAndCrosses\NeuralNetwork\Layer;
use NoughtsAndCrosses\NeuralNetwork\Neuron\NeuronInterface;

/**
 * Interface for Abstract Layer.
 *
 * @package noughtsandcrosses
 */
interface Layer_AbstractInterface
{
    /**
     * Returns number of neurons.
     *
     * @return int
     */
    public function getNeurons();

    /**
     * Sets the number of neurons.
     *
     * @param  int   $number Number of neurons.
     * @return int
     */
    public function setNeurons($neurons);
}

<?php
namespace NoughtsAndCrosses\NeuralNetwork\Layer;
use NoughtsAndCrosses\NeuralNetwork\Neuron\NeuronInterface;

/**
 * Interface for Abstract Layer.
 *
 * @package noughtsandcrosses
 */
interface Layer_AbstractInterface
{
    /**
     * Returns total number of neurons in layer.
     *
     * @return int
     */
    public function getNeurons();

    /**
     * Sets the number of neurons in the layer.
     *
     * @param  int $number Number of neurons.
     * @return int
     */
    public function setNeurons($neurons);
}

Edit "Returns total number of neurons in layer."


<?php

namespace SymfonyDay\Bundle\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    /**
     * @Route("/hello/{name}")
     *
     */
    public function indexAction($name)
    {
        return new Response('Hello '. $name .'!');
    }
}

<?php

namespace SymfonyDay\Bundle\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    /**
     * @Route("/hello/{name}")
     *
     */
    public function indexAction($name)
    {
        return $this->render(
	        'SymfonyDayBlogBundle:Default:index.html.twig',
	        array('name' => $name)
	    );
    }
}

Use template for blog bundle controller

Use template for blog bundle controller


<?php

$config['jsonapi'] = array(

    // JSONAPI connection settings
    'host' => 'localhost',
    'port' => '20059',
    'username' => 'craftshop',
    'password' => '',
    'salt' => ''
)
;

$config['itemapi'] = array(

    'urls' => array(
        'image' => 'http://static.adminiumapp.com/data_values/images/%1$u.png',
        'list' => 'http://static.adminiumapp.com/data_values/cache.json'
    )

);

<?php

$config['jsonapi'] = array(

    // JSONAPI connection settings
    'host' => 'localhost',
    'port' => '20059',
    'username' => 'craftshop',
    'password' => '',
    'salt' => ''
)
;

$config['itemapi'] = array(

    'urls' => array(
        'image' => 'http://static.adminiumapp.com/data_values/images/%1$u-%2$u.png',
        'list' => 'http://static.adminiumapp.com/data_values/cache.json'
    )

);

Fix Minecraft item image hosting URL

Fix Minecraft item image hosting URL

Signed-off-by: JWhy <6a9f7c06e789f829524fd1a3a38b8c7d794c3a1f@jwhy.de>