<?php

namespace Laravel\Lumen\Providers;

use Illuminate\Support\ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event handler mappings for the application.
     *
     * @var array
     */
    protected $listen = [];

    /**
     * The subscriber classes to register.
     *
     * @var array
     */
    protected $subscribe = [];

    /**
     * Register the application's event listeners.
     *
     * @return void
     */
    public function boot()
    {
        $events = app('events');

        foreach ($this->listen as $event => $listeners) {
            foreach ($listeners as $listener) {
                $events->listen($event, $listener);
            }
        }

        foreach ($this->subscribe as $subscriber) {
            $events->subscribe($subscriber);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function register()
    {
        //
    }

    /**
     * Get the events and handlers.
     *
     * @return array
     */
    public function listens()
    {
        return $this->listen;
    }
}

<?php

namespace Laravel\Lumen\Providers;

use Illuminate\Support\ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event handler mappings for the application.
     *
     * @var array
     */
    protected $listen = [];

    /**
     * The subscriber classes to register.
     *
     * @var array
     */
    protected $subscribe = [];

    /**
     * {@inheritdoc}
     */
    public function register()
    {
        //
    }

    /**
     * Register the application's event listeners.
     *
     * @return void
     */
    public function boot()
    {
        $events = app('events');

        foreach ($this->listen as $event => $listeners) {
            foreach ($listeners as $listener) {
                $events->listen($event, $listener);
            }
        }

        foreach ($this->subscribe as $subscriber) {
            $events->subscribe($subscriber);
        }
    }

    /**
     * Get the events and handlers.
     *
     * @return array
     */
    public function listens()
    {
        return $this->listen;
    }
}

Reorder register and boot methods

Reorder register and boot methods


<?php
    global $mysqli,$route;
    require_once "Modules/dashboard/dashboard_model.php";
    $dashboard = new Dashboard($mysqli);

    $location = 'view';
    $sess = (isset($session['write']) && $session['write'] ? 'write':(isset($session['read']) && $session['read'] ? 'read':''));
    if (isset($session['profile']) && $session['profile']==1) {
        $dashpath = $session['username'];
        $sess= 'all';
    } else {
        if ($route->action == "edit" && $session['write']) $location = 'edit';
        $dashpath = 'dashboard/'.$location;
    }

    // Contains a list for the drop down with dashboards available for user session type
    $listmenu = $dashboard->build_menu_array($location);

    $domain = "messages";
    bindtextdomain($domain, "Modules/dashboard/locale");
    bind_textdomain_codeset($domain, 'UTF-8');

    $menu_left[] = array('name'=> dgettext($domain, "Dashboards"), 'path'=>$dashpath , 'session'=>$sess, 'order' => 4, 'dropdown'=>$listmenu);

<?php
    global $mysqli,$route,$session;
    require_once "Modules/dashboard/dashboard_model.php";
    $dashboard = new Dashboard($mysqli);

    $location = 'view';
    $sess = (isset($session['write']) && $session['write'] ? 'write':(isset($session['read']) && $session['read'] ? 'read':''));
    if (isset($session['profile']) && $session['profile']==1) {
        $dashpath = $session['username'];
        $sess= 'all';
    } else {
        if ($route->action == "edit" && $session['write']) $location = 'edit';
        $dashpath = 'dashboard/'.$location;
    }

    // Contains a list for the drop down with dashboards available for user session type
    $listmenu = $dashboard->build_menu_array($location);

    $domain = "messages";
    bindtextdomain($domain, "Modules/dashboard/locale");
    bind_textdomain_codeset($domain, 'UTF-8');

    $menu_left[] = array('name'=> dgettext($domain, "Dashboards"), 'path'=>$dashpath , 'session'=>$sess, 'order' => 4, 'dropdown'=>$listmenu);

Fix dashboard menu for older php version.


<?php
class C03_Station_PlaylistsCest extends CestAbstract
{
    /**
     * @before setupComplete
     * @before login
     */
    public function editPlaylists(FunctionalTester $I)
    {
        $I->wantTo('Create a station playlist.');

        $station_id = $this->test_station->getId();
        $I->amOnPage('/station/'.$station_id.'/playlists');

        $I->see('Playlists');
        $I->click('add', '#content');

        $I->submitForm('.form', [
            'name'          => 'Default Playlist',
        ]);

        $I->seeCurrentUrlEquals('/station/'.$station_id.'/playlists');

        $I->see('Default Playlist');

        $I->click(\Codeception\Util\Locator::lastElement('.btn-danger'));

        $I->seeCurrentUrlEquals('/station/'.$station_id.'/playlists');

        $I->dontSee('Default Playlist');
    }
}

<?php

class C03_Station_PlaylistsCest extends CestAbstract
{
    /**
     * @before setupComplete
     * @before login
     */
    public function editPlaylists(FunctionalTester $I)
    {
        $I->wantTo('Create a station playlist.');

        $station_id = $this->test_station->getId();
        $I->amOnPage('/station/' . $station_id . '/playlists');

        $I->see('Playlists');
    }
}

Remove previous Playlists pages from test suite.


<?php if ( ! defined('BASEPATH')) exit('Invalid file request.');

/**
 * OmniLog module tests.
 *
 * @author          Stephen Lewis <stephen@experienceinternet.co.uk>
 * @copyright       Experience Internet
 * @package         Omnilog
 */

require_once PATH_THIRD .'omnilog/mcp.omnilog.php';
require_once PATH_THIRD .'omnilog/tests/mocks/mock.omnilog_model.php';

class Test_omnilog extends Testee_unit_test_case {

    private $_model;
    private $_subject;

    /* --------------------------------------------------------------
     * PUBLIC METHODS
     * ------------------------------------------------------------ */

    /**
     * Constructor.
     *
     * @access  public
     * @return  void
     */
    public function setUp()
    {
        parent::setUp();

        Mock::generate('Mock_omnilog_model', get_class($this) .'_mock_model');
        $this->_ee->omnilog_model = $this->_get_mock('model');
        $this->_model   = $this->_ee->omnilog_model;
        $this->_subject = new Omnilog();
    }

}

/* End of file      : test.mod_omnilog.php */
/* File location    : third_party/omnilog/tests/test.mod_omnilog.php */

<?php if ( ! defined('BASEPATH')) exit('Invalid file request.');

/**
 * OmniLog module tests.
 *
 * @author        Stephen Lewis <stephen@experienceinternet.co.uk>
 * @copyright     Experience Internet
 * @package       Omnilog
 */

require_once dirname(__FILE__) .'/../mcp.omnilog.php';
require_once dirname(__FILE__) .'/../models/omnilog_model.php';

class Test_omnilog extends Testee_unit_test_case {

    private $_model;
    private $_subject;

    /* --------------------------------------------------------------
     * PUBLIC METHODS
     * ------------------------------------------------------------ */

    /**
     * Constructor.
     *
     * @access  public
     * @return  void
     */
    public function setUp()
    {
        parent::setUp();

        Mock::generate('Mock_omnilog_model', get_class($this) .'_mock_model');
        $this->_ee->omnilog_model = $this->_get_mock('model');
        $this->_model   = $this->_ee->omnilog_model;
        $this->_subject = new Omnilog();
    }

}

/* End of file      : test.mod_omnilog.php */
/* File location    : third_party/omnilog/tests/test.mod_omnilog.php */

Use relative paths for includes.

Use relative paths for includes.


<?
include '../scat.php';
include '../lib/person.php';

if (!defined('LOYALTY')) exit;

$person_id= (int)$_REQUEST['person'];

$person= person_load($db, $person_id);
if (!$person) {
  die_jsonp("No such person.");
}

$q= "SELECT item_id, cost, code, name, retail_price
       FROM loyalty_reward
       JOIN item ON item.id = item_id
      WHERE cost <= {$person['points_available']}
      ORDER BY cost DESC";

$r= $db->query($q)
  or die_query($db, $q);

$rewards= array();
while ($row= $r->fetch_assoc()) {
  $rewards[]= $row;
}

echo jsonp(array("rewards" => $rewards));

<?
include '../scat.php';
include '../lib/person.php';

if (!defined('LOYALTY')) exit;

$person_id= (int)$_REQUEST['person'];

$person= person_load($db, $person_id);
if (!$person) {
  die_jsonp("No such person.");
}

$points= (int)$person['points_available']; // might be NULL

$q= "SELECT item_id, cost, code, name, retail_price
       FROM loyalty_reward
       JOIN item ON item.id = item_id
      WHERE cost <= $points
      ORDER BY cost DESC";

$r= $db->query($q)
  or die_query($db, $q);

$rewards= array();
while ($row= $r->fetch_assoc()) {
  $rewards[]= $row;
}

echo jsonp(array("rewards" => $rewards));

Handle people without points yet

Handle people without points yet


<?php

namespace Coyote\Services\Parser\Parsers;

use Coyote\Repositories\Contracts\WordRepositoryInterface as WordRepository;
use TRegx\SafeRegex\Exception\PregException;
use TRegx\SafeRegex\preg;

class Censore extends Parser implements ParserInterface
{
    public function __construct(private WordRepository $word)
    {
    }

    public function parse(string $text): string
    {
        static $result;

        $text = $this->hashBlock($text, ['code', 'a']);
        $text = $this->hashInline($text, 'img');

        if ($result === null) {
            $result = $this->word->allWords();
        }
        $words = [];

        foreach ($result as $row) {
            $word = '#(?<![\p{L}\p{N}_])' . str_replace('\*', '(\p{L}*?)', preg_quote($row->word)) . '(?![\p{L}\p{N}_])#iu';
            $words[$word] = $row->replacement;
        }

        try {
            $text = preg::replace(array_keys($words), array_values($words), $text);
        } catch (PregException $ignored) {
        }

        $text = $this->unhash($text);

        return $text;
    }
}

<?php

namespace Coyote\Services\Parser\Parsers;

use Coyote\Repositories\Contracts\WordRepositoryInterface as WordRepository;
use TRegx\CleanRegex\Pattern;
use TRegx\SafeRegex\Exception\PregException;
use TRegx\SafeRegex\preg;

class Censore extends Parser implements ParserInterface
{
    public function __construct(private WordRepository $word)
    {
    }

    public function parse(string $text): string
    {
        static $result;

        $text = $this->hashBlock($text, ['code', 'a']);
        $text = $this->hashInline($text, 'img');

        if ($result === null) {
            $template = Pattern::template('(?<![\p{L}\p{N}_])@(?![\p{L}\p{N}_])', 'iu');

            foreach ($this->word->allWords() as $word) {
                $pattern = $template->mask($word->word, ['*' => '(\p{L}*?)']);
                $result["$pattern"] = $word->replacement;
            }
        }

        try {
            $text = preg::replace(array_keys($result), array_values($result), $text);
        } catch (PregException $ignored) {
        }

        $text = $this->unhash($text);

        return $text;
    }
}

Use Pattern::template() instead of string concatenation


<?php
/**
 * @version     $Id$
 * @category	Koowa
 * @package     Koowa_Event
 * @copyright   Copyright (C) 2007 - 2010 Johan Janssens and Mathias Verraes. All rights reserved.
 * @license     GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
 * @link        http://www.koowa.org
 */

/**
 * Class to handle events.
 *
 * @author 		Johan Janssens <johan@koowa.org>
 * @category	Koowa
 * @package 	Koowa_Event
 */
class KEventHandler extends KObject implements KPatternObserver, KObjectIdentifiable
{
	/**
	 * Get the object identifier
	 *
	 * @return	KIdentifier
	 * @see 	KObjectIdentifiable
	 */
	public function getIdentifier()
	{
		return $this->_identifier;
	}

	/**
	 * Method to trigger events
	 *
	 * @param  object	The event arguments
	 * @return mixed Routine return value
	 */
	public function update(ArrayObject $args)
	{
		if (in_array($args['event'], $this->getMethods())) {
			return $this->{$args['event']}($args);
		}

		return null;
	}
}

<?php
/**
 * @version     $Id$
 * @category	Koowa
 * @package     Koowa_Event
 * @copyright   Copyright (C) 2007 - 2010 Johan Janssens and Mathias Verraes. All rights reserved.
 * @license     GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
 * @link        http://www.koowa.org
 */

/**
 * Class to handle events.
 *
 * @author 		Johan Janssens <johan@koowa.org>
 * @category	Koowa
 * @package 	Koowa_Event
 */
class KEventHandler extends KObject implements KPatternObserver, KObjectIdentifiable
{
	/**
	 * Get the object identifier
	 *
	 * @return	KIdentifier
	 * @see 	KObjectIdentifiable
	 */
	public function getIdentifier()
	{
		return $this->_identifier;
	}

	/**
	 * Method to trigger events
	 *
	 * @param  object	The event arguments
	 * @return mixed Routine return value
	 */
	public function update(KConfig $args)
	{
		if (in_array($args->event, $this->getMethods())) {
			return $this->{$args->event}($args);
		}

		return null;
	}
}

Update method should use KConfig instead of ArrayObject as parameter.


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

namespace KawaiiGherkin\Formatter;

/**
 * @author Jefersson Nathan  <malukenho@phpse.net>
 * @license MIT
 */
final class FeatureDescription extends AbstractFormatter
{
    public function format($shortDescription, array $descriptionLines)
    {
        $shortDesc   = 'Feature: ' . $shortDescription . PHP_EOL;
        $longDesc    =  implode(
            array_map(
                function ($descriptionLine) {
                    return $this->indent() . trim($descriptionLine) . PHP_EOL;
                },
                $descriptionLines
            )
        );

        return $shortDesc . rtrim($longDesc);
    }
}

<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

namespace KawaiiGherkin\Formatter;

/**
 * @author Jefersson Nathan  <malukenho@phpse.net>
 * @license MIT
 */
final class FeatureDescription extends AbstractFormatter
{
    /**
     * @param string $shortDescription
     * @param array  $descriptionLines
     *
     * @return string
     */
    public function format($shortDescription, array $descriptionLines)
    {
        // TODO: get keyword here, can't say `feature` hardcoded
        $shortDesc   = 'Feature: ' . $shortDescription . PHP_EOL;
        $longDesc    =  implode(
            array_map(
                function ($descriptionLine) {
                    return $this->indent() . trim($descriptionLine) . PHP_EOL;
                },
                $descriptionLines
            )
        );

        return $shortDesc . rtrim($longDesc);
    }
}

Add dock block and todo task

Add dock block and todo task


<?php

class SPM_ShopyMind_Test_Observer
{
    public function beforeTestStart()
    {
        if (Mage::app()->getStore()->isAdmin()) {
            $store = Mage::getModel('core/store')->load(1);
            if (!$store->isEmpty()) {
                $this->_setStore($store->getCode());
            }
        }

        if ($this->_shouldRunWithFlatCatalog()) {
            $this->_enableFlatCatalog();
            $this->_reindexFlatCatalog();
        }
    }

    protected function _setStoreConfig($path, $value)
    {
        Mage::app()->getStore()
            ->setConfig($path, $value);
    }

    protected function _shouldRunWithFlatCatalog()
    {
        return getenv('USE_FLAT_CATALOG');
    }

    protected function _enableFlatCatalog()
    {
        $this->_setStoreConfig('catalog/frontend/flat_catalog_product', '1');
        $this->_setStoreConfig('catalog/frontend/flat_catalog_category', '1');
    }

    protected function _reindexFlatCatalog()
    {
        foreach (array('catalog_product_flat', 'catalog_category_flat') as $indexer) {
            Mage::getSingleton('index/indexer')
                ->getProcessByCode($indexer)
                ->reindexAll();
        }
    }

    protected function _setStore($store)
    {
        EcomDev_PHPUnit_Test_Case_Util::setCurrentStore($store);
    }
}

<?php

class SPM_ShopyMind_Test_Observer
{
    public function beforeTestStart()
    {
        if (Mage::app()->getStore()->isAdmin()) {
            $store = Mage::getModel('core/store')->load(1);
            if (!$store->isEmpty()) {
                $this->_setStore($store->getCode());
            }
        }

        if ($this->_shouldRunWithFlatCatalog()) {
            $this->_enableFlatCatalog();
            $this->_reindexFlatCatalog();
        }
    }

    protected function _setStoreConfig($path, $value)
    {
        Mage::app()->getStore()
            ->setConfig($path, $value);
    }

    protected function _shouldRunWithFlatCatalog()
    {
        return getenv('USE_FLAT_CATALOG');
    }

    protected function _enableFlatCatalog()
    {
        $this->_setStoreConfig('catalog/frontend/flat_catalog_product', '1');
        $this->_setStoreConfig('catalog/frontend/flat_catalog_category', '1');
    }

    protected function _reindexFlatCatalog()
    {
        Mage::getResourceModel('catalog/product_flat_indexer')->rebuild();
        Mage::getResourceModel('catalog/category_flat')->rebuild();
    }

    protected function _setStore($store)
    {
        EcomDev_PHPUnit_Test_Case_Util::setCurrentStore($store);
    }
}

Use an indexation method that works even for Magento <= 1.7


<?php

namespace Hub\Client\Common;

use Hub\Client\Exception\BadRequestException;
use Hub\Client\Exception\NotFoundException;
use Hub\Client\Exception\NotAuthorizedException;
use RuntimeException;

class ErrorResponseHandler
{
    public static function handle($response)
    {
        if ($response->getStatusCode() == 401) {
            throw new NotAuthorizedException('NOT_AUTHORIZED', 'Basic auth failed');
        }

        $xml = $response->getBody();
        $rootNode = @simplexml_load_string($xml);
        if ($rootNode) {
            if ($rootNode->getName()=='error') {
                switch ((string)$rootNode->status) {
                    case 400:
                        throw new BadRequestException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    case 404:
                        throw new NotFoundException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    case 403:
                        throw new NotAuthorizedException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    default:
                        throw new RuntimeException(
                            "Unsupported response status code returned: " .
                            (string)$rootNode->status . ' / ' . (string)$rootNode->code
                        );
                        break;
                }
            }
            throw new RuntimeException(
                "Failed to parse response. It's valid XML, but not the expected error root element"
            );
        }

        throw new RuntimeException("Failed to parse response: " . $xml);
    }
}

<?php

namespace Hub\Client\Common;

use Hub\Client\Exception\BadRequestException;
use Hub\Client\Exception\NotFoundException;
use Hub\Client\Exception\NotAuthorizedException;
use RuntimeException;

class ErrorResponseHandler
{
    public static function handle($response)
    {
        if ($response->getStatusCode() == 401) {
            throw new NotAuthorizedException('NOT_AUTHORIZED', 'Basic auth failed');
        }

        $xml = $response->getBody();
        $rootNode = @simplexml_load_string($xml);
        if ($rootNode) {
            if ($rootNode->getName()=='error') {
                switch ((string)$rootNode->status) {
                    case 400:
                        throw new BadRequestException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    case 404:
                        throw new NotFoundException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    case 403:
                        throw new NotAuthorizedException((string)$rootNode->code, (string)$rootNode->message);
                        break;
                    default:
                        throw new RuntimeException(
                            "Unsupported response status code returned: " .
                            (string)$rootNode->code . ': ' .
                            (string)$rootNode->messsage .
                            " (" . (string)$rootNode->details . ")"
                        );
                        break;
                }
            }
            throw new RuntimeException(
                "Failed to parse response. It's valid XML, but not the expected error root element"
            );
        }

        throw new RuntimeException("Failed to parse response: " . $xml);
    }
}

Enhance error messaging on exception

Enhance error messaging on exception


<?php
/**
 * @author      Alex Bilbie <hello@alexbilbie.com>
 * @copyright   Copyright (c) Alex Bilbie
 * @license     http://mit-license.org/
 *
 * @link        https://github.com/thephpleague/oauth2-server
 */

namespace League\OAuth2\Server\Entities\Traits;

trait ClientTrait
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @var string|string[]
     */
    protected $redirectUri;

    /**
     * @var bool
     */
    protected $isConfidential;

    /**
     * Get the client's name.
     *
     * @return string
     * @codeCoverageIgnore
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Returns the registered redirect URI (as a string).
     *
     * Alternatively return an indexed array of redirect URIs.
     *
     * @return string|string[]
     */
    public function getRedirectUri()
    {
        return $this->redirectUri;
    }

    /**
     * Returns true if the client is confidential.
     *
     * @return bool
     */
    public function isConfidential()
    {
        return $this->isConfidential;
    }
}

<?php
/**
 * @author      Alex Bilbie <hello@alexbilbie.com>
 * @copyright   Copyright (c) Alex Bilbie
 * @license     http://mit-license.org/
 *
 * @link        https://github.com/thephpleague/oauth2-server
 */

namespace League\OAuth2\Server\Entities\Traits;

trait ClientTrait
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @var string|string[]
     */
    protected $redirectUri;

    /**
     * @var bool
     */
    protected $isConfidential = false;

    /**
     * Get the client's name.
     *
     * @return string
     * @codeCoverageIgnore
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Returns the registered redirect URI (as a string).
     *
     * Alternatively return an indexed array of redirect URIs.
     *
     * @return string|string[]
     */
    public function getRedirectUri()
    {
        return $this->redirectUri;
    }

    /**
     * Returns true if the client is confidential.
     *
     * @return bool
     */
    public function isConfidential()
    {
        return $this->isConfidential;
    }
}

Set default isConfidential to false for client entity


@extends('layouts.app')

@section('title', '新增ApiKey')

@section('content')

新增ApiKey

                    {{ Form::open(['route' => 'api-key.store']) }}

has('api_key') ? ' has-danger' : '' }}">
                        ApiKey

                            {{ Form::text('api_key', null, ['class' => 'form-control']) }}
                            @if ($errors->has('api_key'))

                                    {{ $errors->first('api_key') }}

                            @endif

                            <button type="submit" class="btn btn-primary"> 確認</button>
                            返回列表

                    {{ Form::close() }}

@endsection

@extends('layouts.app')

@section('title', '新增ApiKey')

@section('content')

新增ApiKey

                    {{ Form::open(['route' => 'api-key.store']) }}

has('api_key') ? ' has-danger' : '' }}">
                        ApiKey

                            {{ Form::text('api_key', null, ['class' => 'form-control', 'required']) }}
                            @if ($errors->has('api_key'))

                                    {{ $errors->first('api_key') }}

                            @endif

                            <button type="submit" class="btn btn-primary"> 確認</button>
                            返回列表

                    {{ Form::close() }}

@endsection

Make api_key of ApiKey required

Make api_key of ApiKey required


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>
            @section('title')
                {{ Lang::get('messages.page-title') }}
            @stop
        </title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.css">
        @yield('css')
    </head>
    <body>
        <div class="container">
            @yield('body')
        </div>
        @yield('js')
    </body>
</html>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>
            @section('title')
                {{ Lang::get('messages.page-title') }}
            @stop
        </title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.2/united/bootstrap.min.css">
        <style>
            body {
                padding-top: 60px;
                padding-bottom: 80px;
            }
        </style>
        @yield('css')
    </head>
    <body>
        <div class="container">
            @yield('body')
        </div>
        @yield('js')
    </body>
</html>

Use a theme instead of vanilla twbs. Add padding.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\UserRegistrationRequest;

class UserRegistrationRequestController extends Controller
{
  public function __construct()
  {
    $this->middleware('auth:api');
    $this->middleware('admin');
  }

  public function index(Request $request)
  {
    if (isset($request->key))
      return response()->json(UserRegistrationRequest::where('id', 'LIKE', '%' . $request->key . '%')->offset($request->skip)->limit($request->take)->orderBy('id')->get());
    else
      return response()->json(UserRegistrationRequest::offset($request->skip)->limit($request->take)->orderBy('id')->get());
  }

  public function store(Request $request)
  {
    $this->validate($request, [
      'new_student_id' => 'required|integer|max:9999999|min:1000000|unique:user_registration_requests,id',
    ]);

    $user       = new UserRegistrationRequest();
    $user->id   = $request->new_student_id;
    $user->code = strtoupper(substr(md5(time()), 0, 5) . '-' . substr(md5($request->new_student_id), 0, 5) . '-' . str_random(5));
    $user->save();

    return response()->json($user);
  }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\UserRegistrationRequest;

class UserRegistrationRequestController extends Controller
{
  public function __construct()
  {
    $this->middleware('auth:api');
    $this->middleware('admin');
  }

  public function index(Request $request)
  {
    if (isset($request->key))
      return response()->json(UserRegistrationRequest::where('id', 'LIKE', '%' . $request->key . '%')->offset($request->skip)->limit($request->take)->orderBy('created_at', 'desc')->get());
    else
      return response()->json(UserRegistrationRequest::offset($request->skip)->limit($request->take)->orderBy('created_at', 'desc')->get());
  }

  public function store(Request $request)
  {
    $this->validate($request, [
      'new_student_id' => 'required|integer|max:9999999|min:1000000|unique:user_registration_requests,id',
    ]);

    $user       = new UserRegistrationRequest();
    $user->id   = $request->new_student_id;
    $user->code = strtoupper(substr(md5(time()), 0, 5) . '-' . substr(md5($request->new_student_id), 0, 5) . '-' . str_random(5));
    $user->save();

    return response()->json($user);
  }
}

Make 'UserRegistrationRequest' order by 'created_at'


<?php

echo 'Hello from PHP '.$_GET['customerID'];

<?php

// Connect to the database
$dbc = new mysqli('localhost', 'root', '', 'ajax_customers');

// Filter the ID
$customerID = $dbc->real_escape_string( $_GET['customerID'] );

// Prepare the SQL
$sql = "SELECT phone, email
		FROM customers
		WHERE id = $customerID";

// Run the query
$resultDB = $dbc->query($sql);

// If there was a result
if( $resultDB->num_rows == 1 ) {

	// Convert the result into an associative array
	$resultASSOC = $resultDB->fetch_assoc();

	// Convert the result into JSON
	$resultJSON = json_encode($resultASSOC);

	// Set up the header so JavaScript knows that we are sending JSON
	header('Content-Type: application/json');

	// Send the data back to JavaScript
	echo $resultJSON;

} else {

}

Add PHP that queries the Database for a user based on ID and return JSON


<?php
namespace Flubber;

define('FLIB', dirname(__FILE__).'/');
define('FLVERSION', 2.0);

// Load the core functions
require_once 'Functions.php';

use Flubber\Datastore as Datastore,
    Flubber\Request as Request,
    Flubber\FLException as FLException,
    Flubber\Locale as Locale,
    Flubber\Session as Session;

// Load All Locale strings.
Locale::autoload();

// Load datastore
Datastore::init();

// Load Session
Session::init();

// Initialize request
Request::init();

class Flubber {

    protected $request = null;

    function __construct() { }

    /*
     * Initialize Main application
     */
    public function start() {
        global $FLRequest;
        // Run module passing the request to get appropriate response
        try {
            $module = gethandler($FLRequest->handler);
            call_user_func_array(
                    array($module, $FLRequest->method), $FLRequest->params);
        } catch (FLException $e) {
            $FLRequest->exception = $e;
            $FLRequest->handler = 'Error';
            $error = gethandler($FLRequest->handler);
            $error->notify();
        } catch (\Exception $e) {
            echo $e->getmessage();
        } finally {
            return true;
        }
    }
}

?>

<?php
namespace Flubber;

define('FLIB', dirname(__FILE__).'/');
define('FLVERSION', 2.0);

// Load the core functions
require_once 'Functions.php';

use Flubber\FLException as FLException,
    Flubber\Datastore as Datastore,
    Flubber\Request as Request,
    Flubber\Locale as Locale,
    Flubber\Session as Session;

// Load All Locale strings.
Locale::autoload();

// Load datastore
Datastore::init();

// Load Session
Session::init();

// Initialize request
Request::init();

class Flubber {

    protected $request = null;

    function __construct() { }

    /*
     * Initialize Main application
     */
    public function start() {
        global $FLRequest;
        // Run module passing the request to get appropriate response
        try {
            if ($FLRequest->handler == null) {
                throw new FLException('Not Found', array('status' => 404));
            }
            $module = gethandler($FLRequest->handler);
            call_user_func_array(
                    array($module, $FLRequest->method), $FLRequest->params);
        } catch (FLException $e) {
            $FLRequest->exception = $e;
            $FLRequest->handler = 'Error';
            $error = null;
            if (file_exists(HANDLER_PATH.'/Error.php')) {
                $error = gethandler('Error');
            } else {
                $error = ( new ErrorHandler() );
            }
            $error->notify();
        } catch (\Exception $e) {
            echo $e->getmessage();
        } finally {
            return true;
        }
    }
}

?>

Handle Errors by default by checking error handlers


<?php namespace Exolnet\Html;
/**
 * Copyright © 2014 eXolnet Inc. All rights reserved. (http://www.exolnet.com)
 *
 * This file contains copyrighted code that is the sole property of eXolnet Inc.
 * You may not use this file except with a written agreement.
 *
 * This code is distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, AND EXOLNET INC. HEREBY DISCLAIMS ALL SUCH
 * WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 *
 * @package    Exolnet
 * @subpackage Html
 * @author     eXolnet Inc. <info@exolnet.com>
 */

use \Illuminate\Html\HtmlBuilder as LaravelHtmlBuilder;

class HtmlHelper {
	/**
	 * Obfuscate all mailto in the HTML source provided.
	 *
	 * @param $value
	 * @return mixed
	 */
	public static function obfuscateMailtos($html)
	{
		return preg_replace_callback('#("|\')(mailto:.+?)(\1)#', function($match) {
			//dd($match);
			return $match[1]. \HTML::obfuscate($match[2]).$match[3];
		}, $html);
	}
}

<?php namespace Exolnet\Html;
/**
 * Copyright © 2014 eXolnet Inc. All rights reserved. (http://www.exolnet.com)
 *
 * This file contains copyrighted code that is the sole property of eXolnet Inc.
 * You may not use this file except with a written agreement.
 *
 * This code is distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, AND EXOLNET INC. HEREBY DISCLAIMS ALL SUCH
 * WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 *
 * @package    Exolnet
 * @subpackage Html
 * @author     eXolnet Inc. <info@exolnet.com>
 */

use \Illuminate\Html\HtmlBuilder as LaravelHtmlBuilder;

class HtmlHelper {
	/**
	 * Obfuscate all mailto in the HTML source provided.
	 *
	 * @param $value
	 * @return mixed
	 */
	public static function obfuscateEmails($html)
	{
		return preg_replace_callback('#(mailto:)?[a-z0-9_.+-]+@[a-z0-9-]+\.[a-z0-9-.]+#i', function($match) {
			return \HTML::email($match[0]);
		}, $html);
	}
}

@noref: Fix email obfuscate when they contain a subject


<?php
namespace Morilog\Acl\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Contracts\Config\Repository;
use Morilog\Acl\Managers\Interfaces\RoleManagerInterface;

class AddDefaultRoles extends Command
{
    protected $signature = 'morilog:acl:add-roles';

    protected $description = 'Insert default Roles to database.';

    /**
     * @var RoleManagerInterface
     */
    protected $roleManager;

    /**
     * @var Repository
     */
    private $config;

    public function __construct(RoleManagerInterface $roleManager, Repository $config)
    {
        parent::__construct();

        $this->roleManger = $roleManager;
        $this->config = $config;
    }

    public function handle()
    {
        try {
            $defaultRoles = $this->config->get('acl.default_roles', []);

            foreach ($defaultRoles as $roleName) {
                $newRole = $this->roleManager->createRoleByName($roleName);

                $this->info(sprintf('Role %s has beed added successfully.', $newRole->getName()));
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

    }

}

<?php
namespace Morilog\Acl\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Contracts\Config\Repository;
use Morilog\Acl\Managers\Interfaces\RoleManagerInterface;

class AddDefaultRoles extends Command
{
    protected $signature = 'morilog:acl:add-roles';

    protected $description = 'Insert default Roles to database.';

    /**
     * @var RoleManagerInterface
     */
    protected $roleManager;

    /**
     * @var Repository
     */
    private $config;

    public function __construct(RoleManagerInterface $roleManager, Repository $config)
    {
        parent::__construct();

        $this->roleManager = $roleManager;
        $this->config = $config;
    }

    public function handle()
    {
        try {
            $defaultRoles = $this->config->get('acl.default_roles', []);

            foreach ($defaultRoles as $roleName) {
                $newRole = $this->roleManager->createRoleByName($roleName);

                $this->info(sprintf('Role %s has beed added successfully.', $newRole->getName()));
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

    }

}

Fix fucking creazy bug :((((

Fix fucking creazy bug :((((


<?php namespace Way\Generators\Syntax;

class AddToTable extends Table {

    /**
     * Add syntax for table addition
     *
     * @param $migrationData
     * @param array $fields
     * @return mixed
     */
    public function add($migrationData, array $fields)
    {
        if ( ! isset($migrationData['method']))
        {
            $migrationData['method'] = 'table';
        }

        $compiled = $this->compiler->compile($this->getTemplate(), $migrationData);

        return $this->replaceFieldsWith($this->addColumns($fields), $compiled);
    }

    /**
     * Return string for adding all columns
     *
     * @param $fields
     * @return array
     */
    protected function addColumns($fields)
    {
        $schema = [];

        foreach($fields as $property => $type)
        {
            $schema[] = $this->addColumn($property, $type);
        }

        return $schema;
    }

    /**
     * Return string for adding a column
     *
     * @param $property
     * @param $type
     * @return string
     */
    private function addColumn($property, $type)
    {
        return "\$table->$type('$property');";
    }

}

<?php namespace Way\Generators\Syntax;

class AddToTable extends Table {

    /**
     * Add syntax for table addition
     *
     * @param $migrationData
     * @param array $fields
     * @return mixed
     */
    public function add($migrationData, array $fields)
    {
        if ( ! isset($migrationData['method']))
        {
            $migrationData['method'] = 'table';
        }

        $compiled = $this->compiler->compile($this->getTemplate(), $migrationData);

        return $this->replaceFieldsWith($this->addColumns($fields), $compiled);
    }

    /**
     * Return string for adding all columns
     *
     * @param $fields
     * @return array
     */
    protected function addColumns($fields)
    {
        $schema = [];

        foreach($fields as $property => $details)
        {
            $schema[] = $this->addColumn($property, $details);
        }

        return $schema;
    }

    /**
     * Return string for adding a column
     *
     * @param $property
     * @param $details
     * @return string
     */
    private function addColumn($property, $details)
    {
        $type = $details['type'];
        $output = "\$table->$type('$property')";

        if (isset($details['decorators']))
        {
            $output .= $this->addDecorators($details['decorators']);
        }

        return $output . ';';
    }

    /**
     * @param $decorators
     * @return string
     */
    protected function addDecorators($decorators)
    {
        $output = '';

        foreach ($decorators as $decorator) {
            $output .= "->$decorator";

            // Do we need to tack on the parens?
            if (strpos($decorator, '(') === false) {
                $output .= '()';
            }
        }

        return $output;
    }

}

Add decorator support to schema creation


<?php

use Illuminate\Database\Seeder;

class BookmarksTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Bookmark::class, 10)->create()->each(function ($bookmark) {
            $bookmark->tag()->save(factory(App\Tag::class)->make());
        });
    }
}

<?php

use Illuminate\Database\Seeder;

class BookmarksTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Bookmark::class, 10)->create()->each(function ($bookmark) {
            $bookmark->tags()->save(factory(App\Tag::class)->make());
        });
    }
}

Use the correct method name when saving a tag


<?php

namespace Predis\Commands;

abstract class ScriptedCommand extends ServerEval {
    public abstract function getScript();

    protected function keysCount() {
        // The default behaviour is to use the first argument as the only value
        // for KEYS and the rest of the arguments (if any) for ARGV. When -1 is
        // returned, all the arguments are considered as values for KEYS.
        return 1;
    }

    protected function filterArguments(Array $arguments) {
        if (($keys = $this->keysCount()) === -1) {
            $keys = count($arguments);
        }
        return array_merge(array($this->getScript(), $keys), $arguments);
    }

    protected function getKeys() {
        $arguments = $this->getArguments();
        if (($keys = $this->keysCount()) === -1) {
            return array_slice($arguments, 2);
        }
        return array_slice($arguments, 2, $keys);
    }
}

<?php

namespace Predis\Commands;

abstract class ScriptedCommand extends ServerEval {
    public abstract function getScript();

    protected function keysCount() {
        // The default behaviour for the base class is to use all the arguments
        // passed to a scripted command to populate the KEYS table in Lua.
        return count($this->getArguments());
    }

    protected function filterArguments(Array $arguments) {
        return array_merge(array($this->getScript(), $this->keysCount()), $arguments);
    }

    protected function getKeys() {
        return array_slice($this->getArguments(), 2, $this->keysCount());
    }
}

Change the default value for the number of arguments used to populate KEYS.


<?php
namespace Sil\PhpEnv;

class Env
{
    /**
     * Retrieve the value of the specified environment variable, translating
     * values of 'true', 'false', and 'null' to their actual non-string values.
     *
     * PHP's built-in "getenv()" function returns a string (or false, if the
     * environment variable is not set). If the value is 'false', then it will
     * be returned as the string "false", which evaluates to true. This function
     * is to check for that kind of string value and return the actual value
     * that it refers to.
     *
     * NOTE: If the specified environment variable is not set and no default
     * value was provided, this function returns null (rather returning false
     * the way getenv() does).
     *
     * @param string $name The name of the desired environment variable.
     * @param mixed $default The default value to return if no such environment
     *     variable exists.
     * @return mixed The resulting value (if set), or the given default value
     *     (if any, otherwise null).
     */
    public static function get($name, $default = null)
    {
        $value = \getenv($name);

        if ($value === false) {
            return $default;
        } elseif($value == 'false') {
            return false;
        } elseif($value == 'true') {
            return true;
        } elseif($value == 'null') {
            return null;
        } else {
            return $value;
        }
    }
}

<?php
namespace Sil\PhpEnv;

class Env
{
    /**
     * Retrieve the value of the specified environment variable, translating
     * values of 'true', 'false', and 'null' to their actual non-string values.
     *
     * PHP's built-in "getenv()" function returns a string (or false, if the
     * environment variable is not set). If the value is 'false', then it will
     * be returned as the string "false", which evaluates to true. This function
     * is to check for that kind of string value and return the actual value
     * that it refers to.
     *
     * NOTE: If the specified environment variable is not set and no default
     * value was provided, this function returns null (rather returning false
     * the way getenv() does).
     *
     * @param string $name The name of the desired environment variable.
     * @param mixed $default The default value to return if no such environment
     *     variable exists.
     * @return mixed The resulting value (if set), or the given default value
     *     (if any, otherwise null).
     */
    public static function get($name, $default = null)
    {
        $value = \getenv($name);

        if ($value === false) {
            return $default;
        } elseif ($value == 'false') {
            return false;
        } elseif ($value == 'true') {
            return true;
        } elseif ($value == 'null') {
            return null;
        } else {
            return $value;
        }
    }
}

Add space before each elseif opening parenthesis.


<?php

return [
    '401.title' => 'Non identifié',
    '403.title' => 'Non autorisé',
    'command.confirm.title' => 'Confirmer',
    'command.info.title' => 'Information',
    'state.422.title' => "Impossible de modifier l'état",
    'cropper.title' => 'Transformer l’image'
];

<?php

return [
    '401.title' => 'Non identifié',
    '403.title' => 'Non autorisé',
    'command.confirm.title' => 'Confirmer',
    'command.info.title' => 'Information',
    'state.422.title' => "Impossible de modifier l'état",
    'cropper.title' => 'Transformer l’image',
    'ok_button' => 'Ok',
    'cancel_button' => 'Annuler'
];

Add missing FR keys in locales

Add missing FR keys in locales


<?php

namespace ProcessWire\GraphQL;

class Cache
{
  private static $store = [];

  public static function &type(string $name, $build = null)
  {
    if (isset(self::$store[$name])) {
      return self::$store[$name];
    }

    if (is_null($build) || !is_callable($build)) {
      throw \Exception('The second argument for Cache::type() should be a callable.');
    }

    self::$store[$name] = Utils::placeholder();
    self::$store[$name] = $build();
    return self::$store[$name];
  }

  public static function clear()
  {
    self::$store = [];
  }
}

<?php

namespace ProcessWire\GraphQL;

class Cache
{
  private static function &cache(string $methodName, $store, string $key, $build = null)
  {
    if (isset($store[$key])) {
      return $store[$key];
    }

    if (is_null($build) || !is_callable($build)) {
      throw \Exception("The second argument for Cache::$methodName() should be a callable.");
    }

    $store[$key] = Utils::placeholder();
    $store[$key] = $build();
    return $store[$key];
  }

  /**
   * Type caching
   */
  private static $typeStore = [];

  public static function &type(string $name, $build = null)
  {
    $type =& self::cache('type', self::$typeStore, $name, $build);
    return $type;
  }

  public static function clearType()
  {
    self::$typeStore = [];
  }

  /**
   * Field caching
   */
  private static $fieldStore = [];

  public static function &field(string $name, $build = null)
  {
    $field =& self::cache('field', self::$fieldStore, $name, $build);
    return $field;
  }

  public static function clearField()
  {
    self::$fieldStore = [];
  }

  public static function clear()
  {
    self::$typeStore = [];
    self::$fieldStore = [];
  }
}

Create seperate cache store for types and fields.


<?php

namespace Tests\Feature;

use App\User;
use App\Space;
use App\Tag;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class TagTest extends TestCase {
    public function testAuthorizedUserCanEditTag() {
        $user = factory(User::class)->create();

        $space = factory(Space::class)->create();

        $user->spaces()->sync([$space->id]);

        $tag = factory(Tag::class)->create([
            'space_id' => $space->id
        ]);

        $this->actingAs($user);

        $response = $this->get('/tags/' . $tag->id . '/edit');

        $response->assertStatus(200);
    }

    public function testUnauthorizedUserCantEditTag() {
        $user = factory(User::class)->create();

        $space = factory(Space::class)->create();

        $tag = factory(Tag::class)->create([
            'space_id' => $space->id
        ]);

        $this->actingAs($user);

        $response = $this->get('/tags/' . $tag->id . '/edit');

        $response->assertStatus(403);
    }
}

<?php

namespace Tests\Feature;

use App\User;
use App\Space;
use App\Tag;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class TagTest extends TestCase {
    // Edit
    public function testAuthorizedUserCanEditTag() {
        $user = factory(User::class)->create();

        $space = factory(Space::class)->create();

        $user->spaces()->sync([$space->id]);

        $tag = factory(Tag::class)->create([
            'space_id' => $space->id
        ]);

        $this->actingAs($user);

        $response = $this->get('/tags/' . $tag->id . '/edit');

        $response->assertStatus(200);
    }

    public function testUnauthorizedUserCantEditTag() {
        $user = factory(User::class)->create();

        $space = factory(Space::class)->create();

        $tag = factory(Tag::class)->create([
            'space_id' => $space->id
        ]);

        $this->actingAs($user);

        $response = $this->get('/tags/' . $tag->id . '/edit');

        $response->assertStatus(403);
    }

    // Update
    public function testUpdateTag() {
        $user = factory(User::class)->create();

        $space = factory(Space::class)->create();

        $user->spaces()->sync([$space->id]);

        $tag = factory(Tag::class)->create([
            'space_id' => $space->id,
            'name' => 'Before'
        ]);

        $this->actingAs($user);

        $this->patch('/tags/' . $tag->id, [
            'name' => 'After'
        ]);

        $this->assertEquals(Tag::find($tag->id)->name,'After');
    }
}

Add HTTP/feature test for updating tags

Add HTTP/feature test for updating tags


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Core\Dashboard;

use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Repository\CustomerRepositoryInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class DashboardStatisticsProvider implements DashboardStatisticsProviderInterface
{
    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepository;

    /**
     * @param OrderRepositoryInterface $orderRepository
     * @param CustomerRepositoryInterface $customerRepository
     */
    public function __construct(
        OrderRepositoryInterface $orderRepository,
        CustomerRepositoryInterface $customerRepository
    ) {
        $this->orderRepository = $orderRepository;
        $this->customerRepository = $customerRepository;
    }

    /**
     * {@inheritdoc}
     */
    public function getStatisticsForChannel(ChannelInterface $channel): DashboardStatistics
    {
        return new DashboardStatistics(
            $this->orderRepository->getTotalSalesForChannel($channel),
            $this->orderRepository->countFulfilledByChannel($channel),
            $this->customerRepository->count()
        );
    }
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Core\Dashboard;

use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Repository\CustomerRepositoryInterface;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class DashboardStatisticsProvider implements DashboardStatisticsProviderInterface
{
    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepository;

    /**
     * @param OrderRepositoryInterface $orderRepository
     * @param CustomerRepositoryInterface $customerRepository
     */
    public function __construct(
        OrderRepositoryInterface $orderRepository,
        CustomerRepositoryInterface $customerRepository
    ) {
        $this->orderRepository = $orderRepository;
        $this->customerRepository = $customerRepository;
    }

    /**
     * {@inheritdoc}
     */
    public function getStatisticsForChannel(ChannelInterface $channel): DashboardStatistics
    {
        return new DashboardStatistics(
            $this->orderRepository->getTotalSalesForChannel($channel),
            $this->orderRepository->countFulfilledByChannel($channel),
            $this->customerRepository->countCustomers()
        );
    }
}

[Customer][Core] Rename DashboardStatistic customers count() method to countCustomers()


<?php
namespace PhpBrew\Command;
use PhpBrew\Config;

class EnvCommand extends \CLIFramework\Command
{
    public function brief() { return 'export environment variables'; }

    public function execute($version = null)
    {
        // get current version
        if( ! $version )
            $version = getenv('PHPBREW_PHP');

        // $currentVersion;
        $root = Config::getPhpbrewRoot();
        $buildDir = Config::getBuildDir();

        // $versionBuildPrefix = Config::getVersionBuildPrefix($version);
        // $versionBinPath     = Config::getVersionBinPath($version);

        echo 'export PHPBREW_ROOT=' . $root . "\n";
        echo 'export PHPBREW_HOME=' . $root . "\n";

        echo 'export PHPBREW_PHP='  . $version . "\n";
        echo 'export PHPBREW_PATH=' . ($version ? Config::getVersionBinPath($version) : '') . "\n";
    }

}

<?php
namespace PhpBrew\Command;
use PhpBrew\Config;

class EnvCommand extends \CLIFramework\Command
{
    public function brief() { return 'export environment variables'; }

    public function execute($version = null)
    {
        // get current version
        if( ! $version )
            $version = getenv('PHPBREW_PHP');

        // $currentVersion;
        $root = Config::getPhpbrewRoot();
        $home = Config::getPhpbrewHome();
        $buildDir = Config::getBuildDir();

        // $versionBuildPrefix = Config::getVersionBuildPrefix($version);
        // $versionBinPath     = Config::getVersionBinPath($version);

        echo 'export PHPBREW_ROOT=' . $root . "\n";
        echo 'export PHPBREW_HOME=' . $home . "\n";

        echo 'export PHPBREW_PHP='  . $version . "\n";
        echo 'export PHPBREW_PATH=' . ($version ? Config::getVersionBinPath($version) : '') . "\n";
    }

}

Fix Env command for switching php

Fix Env command for switching php


<?php

namespace WyriHaximus\React\Cake\Orm;

class AsyncTable
{
    /**
     * @var Pool
     */
    protected $pool;

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

    /**
     * @param Pool $pool
     * @param string $tableName
     */
    public function __construct(Pool $pool, $tableName)
    {
        $this->pool = $pool;
        $this->tableName = $tableName;
    }

    public function __call($function, array $arguments = [])
    {
        $unSerialize = function ($input) {
            return unserialize($input);
        };
        return $this->pool->call($this->tableName, $function, $arguments)->then($unSerialize, $unSerialize, $unSerialize);
    }
}

<?php

namespace WyriHaximus\React\Cake\Orm;

use Cake\ORM\TableRegistry;

class AsyncTable
{
    /**
     * @var Pool
     */
    protected $pool;

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

    /**
     * @param Pool $pool
     * @param string $tableName
     */
    public function __construct(Pool $pool, $tableName)
    {
        $this->pool = $pool;
        $this->tableName = $tableName;
    }

    public function __call($function, array $arguments = [])
    {
        return $this->callAsync($function, $arguments);
    }

    protected function callSync($function, array $arguments = [])
    {

        return \React\Promise\resolve(
                call_user_func_array(
                [
                    TableRegistry::get($this->tableName),
                    $function
                ],
                $arguments
            )
        );
    }

    protected function callAsync($function, array $arguments = [])
    {
        $unSerialize = function ($input) {
            return unserialize($input);
        };
        return $this->pool->call($this->tableName, $function, $arguments)->then($unSerialize, $unSerialize, $unSerialize);
    }
}

Split the calling of methods up in an async and sync method


<?php

namespace Oro\Bundle\JsFormValidationBundle\Tests\Unit\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Oro\Bundle\JsFormValidationBundle\DependencyInjection\OroJsFormValidationExtension;

class OroJsFormValidationExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $container = new ContainerBuilder();
        $extension = new OroJsFormValidationExtension();

        $configs = array(array());
        $extension->load($configs, $container);

        $this->assertTrue(
            $container->hasDefinition('oro_jsfv.event_listener.load_constraints_listener'),
            'The load constraints listener is loaded'
        );
    }
}

<?php

namespace Oro\Bundle\JsFormValidationBundle\Tests\Unit\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Oro\Bundle\JsFormValidationBundle\DependencyInjection\OroJsFormValidationExtension;

class OroJsFormValidationExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $container = new ContainerBuilder();
        $extension = new OroJsFormValidationExtension();

        $configs = array(array());
        $extension->load($configs, $container);

        $this->assertTrue(
            $container->hasDefinition('jsfv.generator'),
            'The jsfv.generator is overridden'
        );
    }
}

BAP-771: Extend APYJsFormValidationBundle to make it compatible with custom errors styles
- fix test


<?php

$file_list = array();
foreach (glob('*.js') as $file) {
    $file_list[] = $file;
}
echo json_encode($file_list);

<?php

$file_list = array();
foreach (glob('*.js') as $file) {
    $file_list[] = $file;
}
sort($file_list);
echo json_encode($file_list);

?>

Sort plugins list by name

Sort plugins list by name


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Product\Repository;

use Sylius\Component\Product\Model\ProductInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
interface ProductRepositoryInterface extends RepositoryInterface
{
    /**
     * @param string $name
     * @param string $locale
     *
     * @return ProductInterface[]
     */
    public function findByName($name, $locale);

    /**
     * @param string $slug
     *
     * @return ProductInterface|null
     */
    public function findOneBySlug($slug);
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Product\Repository;

use Sylius\Component\Product\Model\ProductInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
interface ProductRepositoryInterface extends RepositoryInterface
{
    /**
     * @param string $name
     * @param string $locale
     *
     * @return ProductInterface[]
     */
    public function findByName($name, $locale);
}

Clean up the rest of repositories

[MultipleBundles] Clean up the rest of repositories


		<?php echo $view['translator']->trans('nyrodev.required') ?>

    <?php
	echo $view['form']->widget($form);
	if ($form->vars && isset($form->vars['attr']) && isset($form->vars['attr']['data-cancelurl']) && $form->vars['attr']['data-cancelurl']) {
		echo 'vars['attr']['data-cancelurl'].'" class="button cancel">'.$view['translator']->trans('admin.misc.cancel').'';
	}
	?>

		<?php echo $view['translator']->trans('nyrodev.required') ?>

    <?php
	$more = null;
	if (isset($form->vars['attr']) && isset($form->vars['attr']['more'])) {
		$more = $form->vars['attr']['more'];
		unset($form->vars['attr']['more']);
	}
	echo $view['form']->widget($form);
	if ($form->vars && isset($form->vars['attr']) && isset($form->vars['attr']['data-cancelurl']) && $form->vars['attr']['data-cancelurl']) {
		echo 'vars['attr']['data-cancelurl'].'" class="button cancel">'.$view['translator']->trans('admin.misc.cancel').'';
	}
	echo $more;
	?>

Add more attr options for button_row

Add more attr options for button_row


<?php

/**
 * Skeleton subclass for representing a row from the 'edge_server' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package Core
 * @subpackage model
 */
class EdgeServer extends BaseEdgeServer {

	const CUSTOM_DATA_DELIVERY_IDS = 'delivery_profile_ids';
	const CUSTOM_DATA_PLAYBACK_HOST_NAME = 'playback_host_name';

	/**
	 * Initializes internal state of EdgeServer object.
	 * @see        parent::__construct()
	 */
	public function __construct()
	{
		// Make sure that parent constructor is always invoked, since that
		// is where any default values for this object are set.
		parent::__construct();
	}

	/* Delivery Settings */

	public function setDeliveryProfileIds($params)
	{
		$this->putInCustomData(self::CUSTOM_DATA_DELIVERY_IDS, $params);
	}

	public function getDeliveryProfileIds()
	{
		return $this->getFromCustomData(self::CUSTOM_DATA_DELIVERY_IDS, null, array());
	}

	public function setPlaybackHostName($playbackUrl)
	{
		$this->putInCustomData(self::CUSTOM_DATA_PLAYBACK_HOST_NAME, $playbackUrl);
	}

	public function getPlaybackHostName($playbackUrl)
	{
		return $this->getFromCustomData(self::CUSTOM_DATA_PLAYBACK_HOST_NAME, null, $this->getHostName());
	}

} // EdgeServer

<?php

/**
 * Skeleton subclass for representing a row from the 'edge_server' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package Core
 * @subpackage model
 */
class EdgeServer extends BaseEdgeServer {

	const CUSTOM_DATA_DELIVERY_IDS = 'delivery_profile_ids';

	/**
	 * Initializes internal state of EdgeServer object.
	 * @see        parent::__construct()
	 */
	public function __construct()
	{
		// Make sure that parent constructor is always invoked, since that
		// is where any default values for this object are set.
		parent::__construct();
	}

	/* Delivery Settings */

	public function setDeliveryProfileIds($params)
	{
		$this->putInCustomData(self::CUSTOM_DATA_DELIVERY_IDS, $params);
	}

	public function getDeliveryProfileIds()
	{
		return $this->getFromCustomData(self::CUSTOM_DATA_DELIVERY_IDS, null, array());
	}

} // EdgeServer

Remove function that is no longer needed


<?php
    // nice and simple :)
    passthru(urldecode($_GET['commandString']) . ' 2>&1');
?>

<?php
    include '../util.php.inc';
    // nice and simple :)
    global $bespin_bases;
    $dir = $bespin_bases['Default'];

    passthru("cd $dir; " . urldecode($_GET['commandString']) . ' 2>&1');
?>

Make all exec commands work in the default directory


<?php if (get_field('hide_box_frame', $module->ID)) : ?>

<article class="no-margin <?php echo get_field('font_size', $module->ID) ? get_field('font_size', $module->ID) : ''; ?>">
    <?php if (!$module->hideTitle && !empty($module->post_title)) : ?>

<?php echo apply_filters('the_title', $module->post_title); ?>

    <?php endif; ?>

    <?php echo apply_filters('the_content', $module->post_content); ?>

<?php else : ?>

<div class="<?php echo implode(' ', apply_filters('Modularity/Module/Classes', array('box', 'box-panel'), $module->post_type, $args)); ?> <?php echo get_field('font_size', $module->ID) ? get_field('font_size', $module->ID) : ''; ?>">
    <?php if (!$module->hideTitle && !empty($module->post_title)) : ?>

<?php echo apply_filters('the_title', $module->post_title); ?>

    <?php endif; ?>

        <?php echo apply_filters('the_content', $module->post_content); ?>

<?php endif; ?>

<?php if (get_field('hide_box_frame', $module->ID)) : ?>

<article class="no-margin full <?php echo get_field('font_size', $module->ID) ? get_field('font_size', $module->ID) : ''; ?>">
    <?php if (!$module->hideTitle && !empty($module->post_title)) : ?>

<?php echo apply_filters('the_title', $module->post_title); ?>

    <?php endif; ?>

    <?php echo apply_filters('the_content', $module->post_content); ?>

<?php else : ?>

<div class="<?php echo implode(' ', apply_filters('Modularity/Module/Classes', array('box', 'box-panel'), $module->post_type, $args)); ?> <?php echo get_field('font_size', $module->ID) ? get_field('font_size', $module->ID) : ''; ?>">
    <?php if (!$module->hideTitle && !empty($module->post_title)) : ?>

<?php echo apply_filters('the_title', $module->post_title); ?>

    <?php endif; ?>

        <?php echo apply_filters('the_content', $module->post_content); ?>

<?php endif; ?>

Add .full to text module if no box

Add .full to text module if no box


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Suffix;

class SuffixController extends Controller
{
	public function __construct() {}

	public function getSuffixes() {
		try {
			$suffixes = Suffix::all();
		} catch (\Exception $e) {
			throw new \Symfony\Component\HttpKernel\Exception\HttpException('Get failed');
		}

		return response()->json([
			'data' => $suffixes,
		]);
	}

	public function create(Request $request) {
		try {
			$suffix = new Suffix();
			$suffix->name = $request->name;
			$suffix->save();
		} catch (\Exception $e) {
			throw new \Symfony\Component\HttpKernel\Exception\HttpException('Create failed');
		}

		return response()->json([
			'data' => $suffix,
		]);
	}

	public function delete($id) {
		try {
			$suffix = Suffix::find($id);
			$suffix->delete();
		} catch (\Exception $e) {
			throw new \Symfony\Component\HttpKernel\Exception\HttpException('Delete failed');
		}

		return response()->json(['meta' => ['message' => 'success', 'status_code' => 200]]);
	}
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Suffix;

class SuffixController extends Controller
{
	public function __construct() {}

	public function getSuffixes() {
		try {
			$suffixes = Suffix::orderBy('name')->get();
		} catch (\Exception $e) {
			throw new \Symfony\Component\HttpKernel\Exception\HttpException('Get failed');
		}

		return response()->json([
			'data' => $suffixes,
		]);
	}

	public function create(Request $request) {
		try {
			$suffix = new Suffix();
			$suffix->name = $request->name;
			$suffix->save();
		} catch (\Exception $e) {
			throw new \Symfony\Component\HttpKernel\Exception\HttpException('Create failed');
		}

		return response()->json([
			'data' => $suffix,
		]);
	}

	public function delete($id) {
		try {
			$suffix = Suffix::find($id);
			$suffix->delete();
		} catch (\Exception $e) {
			throw new \Symfony\Component\HttpKernel\Exception\HttpException('Delete failed');
		}

		return response()->json(['meta' => ['message' => 'success', 'status_code' => 200]]);
	}
}

Return suffix ordered by name

Return suffix ordered by name


<?php
/**
 * Definition of class PluginLoader
 *
 * @copyright  2014-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\justtexts\service
 */

namespace justso\justtexts\service;

use justso\justapi\Bootstrap;
use justso\justapi\RestService;

/**
 * Class PluginLoader
 * @package justso\justtexts\service
 */
class PluginLoader extends RestService
{
    public function getAction()
    {
        $this->environment->sendHeader('HTTP/1.0 Ok');
        $this->environment->sendHeader('Content-Type: text/javascript; charset=utf-8');
        $bootstrap = Bootstrap::getInstance();
        foreach (glob($bootstrap->getAppRoot() . '/vendor/*/*/justtexts-plugin.js') as $file) {
            $content = $this->environment->getFileSystem()->getFile($file);
            $this->environment->sendResult('200 Ok', 'text/javascript; charset=utf-8', $content);
        }
    }
}

<?php
/**
 * Definition of class PluginLoader
 *
 * @copyright  2014-today Justso GmbH
 * @author     j.schirrmacher@justso.de
 * @package    justso\justtexts\service
 */

namespace justso\justtexts\service;

use justso\justapi\Bootstrap;
use justso\justapi\RestService;

/**
 * Class PluginLoader
 * @package justso\justtexts\service
 */
class PluginLoader extends RestService
{
    public function getAction()
    {
        $this->environment->sendHeader('HTTP/1.0 200 Ok');
        $this->environment->sendHeader('Content-Type: text/javascript; charset=utf-8');
        $bootstrap = Bootstrap::getInstance();
        foreach ($this->environment->getFileSystem()->glob($bootstrap->getAppRoot() . '/vendor/*/*/justtexts-plugin.js') as $file) {
            $content = $this->environment->getFileSystem()->getFile($file);
            $this->environment->sendResult('200 Ok', 'text/javascript; charset=utf-8', $content);
        }
    }
}

Use File System class for the test to get it sandboxed. Fixed HTTP header.


    @if (Auth::user()->student->isEnrolledInCourse($course))
        <button type="button" class="btn btn-outline-secondary btn-sm disabled">Enrolled</button>

        @if ($settings->withinExchangePeriod() && Auth::student()->getEnrollmentInCourse($course)->isDeletable())
            {{-- Show dropdown to remove enrollment in course. --}}
            <button type="button" class="btn btn-outline-secondary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                Toggle Dropdown
            </button>

                <form action="{{ route('enrollments.destroy', $course->id) }}" method="post">
                    {{ csrf_field() }}
                    {{ method_field('DELETE') }}
                    <button type="submit" class="dropdown-item btn btn-sm text-danger">Delete enrollment</button>
                </form>

        @endif
    @elseif ($settings->withinEnrollmentPeriod())
        {{-- Show button to enroll in course. --}}
        <form action="{{ route('enrollments.store', $course->id) }}" method="post">
            {{ csrf_field() }}
            <button type="submit" class="btn btn-success btn-sm">Enroll in course</button>
        </form>
    @endif

    @if (Auth::user()->student->isEnrolledInCourse($course))
        <button type="button" class="btn btn-outline-secondary btn-sm disabled">Enrolled</button>

        @if ($settings->withinEnrollmentPeriod() && Auth::student()->getEnrollmentInCourse($course)->isDeletable())
            {{-- Show dropdown to remove enrollment in course. --}}
            <button type="button" class="btn btn-outline-secondary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                Toggle Dropdown
            </button>

                <form action="{{ route('enrollments.destroy', $course->id) }}" method="post">
                    {{ csrf_field() }}
                    {{ method_field('DELETE') }}
                    <button type="submit" class="dropdown-item btn btn-sm text-danger">Delete enrollment</button>
                </form>

        @endif
    @elseif ($settings->withinEnrollmentPeriod())
        {{-- Show button to enroll in course. --}}
        <form action="{{ route('enrollments.store', $course->id) }}" method="post">
            {{ csrf_field() }}
            <button type="submit" class="btn btn-success btn-sm">Enroll in course</button>
        </form>
    @endif

Fix condition to show the Delete Enrollment option


<?php

namespace LegalThings\DataEnricher\Processor;

use LegalThings\DataEnricher\Node;
use LegalThings\DataEnricher\Processor;
use JmesPath\search as jmespath_search;

/**
 * JMESPath processor
 * @see http://jmespath.org/
 */
class JmesPath implements Processor
{
    use Processor\Implementation;

    /**
     * Apply processing to a single node
     *
     * @param Node $node
     */
    public function applyToNode(Node $node)
    {
        $path = $node->getInstruction($this);
        $input = $node->getResult();

        $result = jmespath_search($path, $input);
        $node->setResult($result);
    }
}

<?php

namespace LegalThings\DataEnricher\Processor;

use LegalThings\DataEnricher\Node;
use LegalThings\DataEnricher\Processor;
use function JmesPath\search as jmespath_search;
use JmesPath\Utils;

/**
 * JMESPath processor
 * @see http://jmespath.org/
 */
class JmesPath implements Processor
{
    use Processor\Implementation;

    /**
     * Apply processing to a single node
     *
     * @param Node $node
     */
    public function applyToNode(Node $node)
    {
        $path = $node->getInstruction($this);
        $input = $node->getResult();

        $result = jmespath_search($path, $input);
        static::objectivy($result);

        $node->setResult($result);
    }

    /**
     * Cast associated arrays to objects
     *
     * @return mixed
     */
    protected static function objectivy(&$value)
    {
        if (Utils::isObject($value)) {
            $value = (object)$value;
        }

        if (is_array($value) || is_object($value)) {
            foreach ($value as &$item) {
                static::objectivy($item);
            }
        }
    }
}

Fix jmespatch 'use' statement (fatal error) Cast associated array result to object


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Shipping\Model;

use Doctrine\Common\Collections\Collection;

/**
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
interface ShippingMethodsAwareInterface
{
    /**
     * @return Collection|ShippingMethodInterface[]
     */
    public function getShippingMethods();

    /**
     * @param ShippingMethodInterface $shippingMethod
     *
     * @return bool
     */
    public function hasShippingMethod(ShippingMethodInterface $shippingMethod);

    /**
     * @param ShippingMethodInterface $shippingMethod
     */
    public function addShippingMethod(ShippingMethodInterface $shippingMethod);

    /**
     * @param ShippingMethodInterface $shippingMethod
     */
    public function removeShippingMethod(ShippingMethodInterface $shippingMethod);
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Shipping\Model;

use Doctrine\Common\Collections\Collection;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface ShippingMethodsAwareInterface
{
    /**
     * @return Collection|ShippingMethodInterface[]
     */
    public function getShippingMethods();

    /**
     * @param ShippingMethodInterface $shippingMethod
     *
     * @return bool
     */
    public function hasShippingMethod(ShippingMethodInterface $shippingMethod);

    /**
     * @param ShippingMethodInterface $shippingMethod
     */
    public function addShippingMethod(ShippingMethodInterface $shippingMethod);

    /**
     * @param ShippingMethodInterface $shippingMethod
     */
    public function removeShippingMethod(ShippingMethodInterface $shippingMethod);
}

Include correct Paweł's email :camel:

Include correct Paweł's email :camel:


<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

require_once('libs/Smarty.class.php');

if (empty($_GET['type'])) $_GET['type'] = 'problem';
if (empty($_GET['randomseed'])) $_GET['randomseed'] = '1';
if (empty($_POST['userinput'])) $_POST['userinput'] = false;

$script_path = '/srv/http/fastmath/MathServer/server.py';

// call python script
ob_start();
system(sprintf("python2 %s %d %s %s", $script_path, escapeshellarg($_GET['randomseed']), escapeshellarg($_GET['type']), escapeshellarg($_POST['userinput'])));
$out = json_decode(ob_get_clean());
print_r($out);

// print out comic
// populate template

$smarty = new Smarty;

//$smarty->force_compile = true;
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;

$smarty->assign("foo","bar");

$smarty->display('tpl/problem.tpl');

<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

define('MAX_COMIC_STEPS', 10);

session_start();

require_once('libs/Smarty.class.php');

if (empty($_SESSION['comic_seed'])) $_SESSION['comic_seed'] = rand();
if (empty($_SESSION['comic_step'])) $_SESSION['comic_step'] = 0;
if (empty($_SESSION['questions_solved'])) $_SESSION['questions_solved'] = 0;
if (empty($_GET['type'])) $_GET['type'] = 'problem';
if (empty($_GET['randomseed'])) $_GET['randomseed'] = '1';
if (empty($_POST['userinput'])) $_POST['userinput'] = false;

$script_path = '/srv/http/fastmath/MathServer/server.py';

// call python script
ob_start();
system(sprintf("python2 %s %d %s %s", $script_path, escapeshellarg($_GET['randomseed']), escapeshellarg($_GET['type']), escapeshellarg($_POST['userinput'])));
$out = json_decode(ob_get_clean());
print_r($out);

// print out comic
// i.e. pass a seed to the comic generator script
$smarty->assign('comic', array('seed' => $_SESSION['comic_seed'], 'step' => $_SESSION['comic_step']));

// populate template

$smarty = new Smarty;

//$smarty->force_compile = true;
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;

$smarty->assign("foo","bar");

$smarty->display('tpl/problem.tpl');

Add some session details for persistent state stuff


<?php

namespace Avalanche\Bundle\ImagineBundle\Imagine;

use Avalanche\Bundle\ImagineBundle\Imagine\Filter\FilterManager;

class CacheReloader
{
    private $sourceRoot;
    private $cacheManager;
    private $filterManager;

    public function __construct($sourceRoot, CacheManager $cacheManager, FilterManager $filterManager)
    {
        $this->sourceRoot    = $sourceRoot;
        $this->cacheManager  = $cacheManager;
        $this->filterManager = $filterManager;
    }

    public function reloadFor($file, $force = false)
    {
        $paths = [];

        foreach ($this->filterManager->getFilterNames() as $filter) {
            $prefix = $this->filterManager->getOption($filter, 'source_root', $this->sourceRoot);
            (false === strpos($prefix, '://')) && ($prefix = realpath($prefix));

            if (0 !== strpos($file, $prefix)) {
                continue;
            }

            $paths[$filter] = $this->cacheManager->cacheImage('', substr($file, strlen($prefix)), $filter, $force);
        }

        return $paths;
    }
}

<?php

namespace Avalanche\Bundle\ImagineBundle\Imagine;

use Avalanche\Bundle\ImagineBundle\Imagine\Filter\FilterManager;

class CacheReloader
{
    private $sourceRoot;
    private $cacheManager;
    private $filterManager;

    public function __construct($sourceRoot, CacheManager $cacheManager, FilterManager $filterManager)
    {
        $this->sourceRoot    = $sourceRoot;
        $this->cacheManager  = $cacheManager;
        $this->filterManager = $filterManager;
    }

    public function reloadFor($file, $force = false)
    {
        $paths = [];

        foreach ($this->filterManager->getFilterNames() as $filter) {
            $prefix = $this->filterManager->getOption($filter, 'source_root', $this->sourceRoot);
            stream_is_local($prefix) && ($prefix = realpath($prefix));

            if (0 !== strpos($file, $prefix)) {
                continue;
            }

            $paths[$filter] = $this->cacheManager->cacheImage('', substr($file, strlen($prefix)), $filter, $force);
        }

        return $paths;
    }
}

Use stream_is_local instead of strpos hack


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

namespace Zend\ServiceManager\Factory;

use Interop\Container\ContainerInterface;

/**
 * Interface for an abstract factory.
 *
 * An abstract factory extends the factory interface, but also has an
 * additional "has" method, which is called to check if the abstract factory
 * has the ability to create an instance for the given service. You should
 * limit the number of abstract factories to ensure good performance. Starting
 * from ServiceManager v3, remember that you can also attach multiple names to
 * the same factory, which reduces the need for abstract factories.
 */
interface AbstractFactoryInterface extends FactoryInterface
{
    /**
     * Can the factory create an instance for the service?
     *
     * @param  ContainerInterface $container
     * @param  string $requestedName
     * @return bool
     */
    public function canCreate(ContainerInterface $container, $requestedName);
}

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

namespace Zend\ServiceManager\Factory;

use Interop\Container\ContainerInterface;

/**
 * Interface for an abstract factory.
 *
 * An abstract factory extends the factory interface, but also has an
 * additional "canCreate" method, which is called to check if the abstract
 * factory has the ability to create an instance for the given service. You
 * should limit the number of abstract factories to ensure good performance.
 * Starting from ServiceManager v3, remember that you can also attach multiple
 * names to the same factory, which reduces the need for abstract factories.
 */
interface AbstractFactoryInterface extends FactoryInterface
{
    /**
     * Can the factory create an instance for the service?
     *
     * @param  ContainerInterface $container
     * @param  string $requestedName
     * @return bool
     */
    public function canCreate(ContainerInterface $container, $requestedName);
}

Update docblock to relect rename to canCreate()


<?php

class TestCase extends Illuminate\Foundation\Testing\TestCase
{
    protected $baseUrl = 'http://localhost:8000';

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

        return $app;
    }

    public function prepareForTests()
    {
        // Mail::pretend(true);
    }

    public function setupDatabase()
    {
        // Artisan::call('migrate:reset');
        // Artisan::call('db:seed', array('--class'=>'TestingDatabaseSeeder'));
    }

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

        $this->prepareForTests();
    }

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

        Mockery::close();
    }
}

<?php

abstract class TestCase extends Illuminate\Foundation\Testing\TestCase
{
    protected $baseUrl = 'http://localhost:8000';

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

        return $app;
    }

    public function prepareForTests()
    {
        // Mail::pretend(true);
    }

    public function setupDatabase()
    {
        // Artisan::call('migrate:reset');
        // Artisan::call('db:seed', array('--class'=>'TestingDatabaseSeeder'));
    }

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

        $this->prepareForTests();
    }

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

        Mockery::close();
    }
}

Fix NO TESTS FOUND IN TESTCASE error

Fix NO TESTS FOUND IN TESTCASE error

Ref:
http://nickhayden.com/blog/laravel-5-no-tests-found-in-testcase-error/


<?php

namespace App\Providers;

use Bouncer;
use App\Rental;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Role seed.
        Bouncer::seeder(function () {
            Bouncer::allow('active')
                ->to('');

            Bouncer::allow('blocked')
                ->to('');

            Bouncer::allow('admin')
                ->to('');
        });

        // Rental global variables
        view()->share('rentalCount', Rental::all()->count());
        view()->share('rentalOption', Rental::where('Status', 1)->count());
        view()->share('rentalNew', Rental::where('Status', 0)->count());
    }

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

<?php

namespace App\Providers;

use Bouncer;
use App\Rental;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Role seed.
        Bouncer::seeder(function () {
            Bouncer::allow('active')
                ->to('');

            Bouncer::allow('blocked')
                ->to('');

            Bouncer::allow('admin')
                ->to('');
        });

        // Rental global variables
        if (Schema::hasTable('rentals')) {
            view()->share('rentalCount', Rental::all()->count());
            view()->share('rentalOption', Rental::where('Status', 1)->count());
            view()->share('rentalNew', Rental::where('Status', 0)->count());
        }
    }

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

Fix global variables issue - Occurs when u try to migrate


<?php

/*
 * This file is part of the Pagerfanta package.
 *
 * (c) Pablo Díez <pablodip@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Pagerfanta\Adapter;

/**
 * PropelAdapter.
 *
 * @author William DURAND <william.durand1@gmail.com>
 */
class PropelAdapter implements AdapterInterface
{
    private $query;

    /**
     * Constructor.
     */
    public function __construct($query)
    {
        $this->query = $query;
    }

    /**
     * Returns the query.
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * {@inheritdoc}
     */
    public function getNbResults()
    {
        return $this->query->count();
    }

    /**
     * {@inheritdoc}
     */
    public function getSlice($offset, $length)
    {
        return $this->query->limit($length)->offset($offset)->find();
    }
}

<?php

/*
 * This file is part of the Pagerfanta package.
 *
 * (c) Pablo Díez <pablodip@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Pagerfanta\Adapter;

/**
 * PropelAdapter.
 *
 * @author William DURAND <william.durand1@gmail.com>
 */
class PropelAdapter implements AdapterInterface
{
    private $query;

    /**
     * Constructor.
     */
    public function __construct($query)
    {
        $this->query = $query;
    }

    /**
     * Returns the query.
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * {@inheritdoc}
     */
    public function getNbResults()
    {
        return $this->query->limit(0)->count();
    }

    /**
     * {@inheritdoc}
     */
    public function getSlice($offset, $length)
    {
        return $this->query->limit($length)->offset($offset)->find();
    }
}

Enforce the limit to be reset in get query :

```
 $query = \Admingenerator\PropelDemoBundle\Model\MovieQuery::create('q')
 $paginator = new Pagerfanta(new PagerAdapter($query));
 $paginator->setMaxPerPage(3);
 $paginator->setCurrentPage($this->getPage(), false, true);
```

```
SELECT propel_movies.ID, propel_movies.TITLE, propel_movies.IS_PUBLISHED, propel_movies.RELEASE_DATE, propel_movies.PRODUCER_ID
FROM `propel_movies` LIMIT 3
Time: 0.041 sec - Memory: 22.1 MB
SELECT COUNT(*)
FROM (SELECT propel_movies.ID, propel_movies.TITLE, propel_movies.IS_PUBLISHED, propel_movies.RELEASE_DATE, propel_movies.PRODUCER_ID
FROM `propel_movies` LIMIT 3) propelmatch4cnt
Time: 0.002 sec - Memory: 24.6 MB
```

So was always make one page !!


<?php
declare(strict_types=1);

namespace Search;

use Cake\Core\BasePlugin;

class Plugin extends BasePlugin
{
    /**
     * Plugin name
     *
     * @var string
     */
    protected $name = 'Search';

    /**
     * Do bootstrapping or not
     *
     * @var bool
     */
    protected $bootstrapEnabled = false;

    /**
     * Load routes or not
     *
     * @var bool
     */
    protected $routesEnabled = false;
}

<?php
declare(strict_types=1);

namespace Search;

use Cake\Console\CommandCollection;
use Cake\Core\BasePlugin;

class Plugin extends BasePlugin
{
    /**
     * Plugin name
     *
     * @var string
     */
    protected $name = 'Search';

    /**
     * Do bootstrapping or not
     *
     * @var bool
     */
    protected $bootstrapEnabled = false;

    /**
     * Load routes or not
     *
     * @var bool
     */
    protected $routesEnabled = false;

    /**
     * Add console commands for the plugin.
     *
     * @param \Cake\Console\CommandCollection $commands The command collection to update
     * @return \Cake\Console\CommandCollection
     */
    public function console(CommandCollection $commands): CommandCollection
    {
        // Bake plugin handles discovery of bake commands itself.
        // Since we currently only have a command class for bake command, we don't need to to anything here.
        return $commands;
    }
}

Fix error when bake plugin is not loaded.

Closes #305


<?php

/*
 * (c) Smalte - 2012 ~ Until the end of the world...
 *
 * Julien Breux <julien@smalte.org>
 * Fabien Serny <fabien@smalte.org>
 * Grégoire Poulain <gregoire@smalte.org>
 * Alain Folletete <alain@smalte.org>
 * Raphaël Malié <raphael@smalte.org>
 *
 * Thanks a lot to our community!
 *
 * Read LICENCE file for more information.
 */

namespace Controllers\FrontOffice;

use \Smalte\Controller\Controller;

class Home extends Controller
{
	public function displayAction()
	{
		$vars = array(
			'test' => 'mycontent',
			'date' => date('H:i:s'),
		);
		$content = $this->renderView('home/index', $vars);
		return $this->getResponse($content);
	}
}

<?php

/*
 * (c) Smalte - 2012 ~ Until the end of the world...
 *
 * Julien Breux <julien@smalte.org>
 * Fabien Serny <fabien@smalte.org>
 * Grégoire Poulain <gregoire@smalte.org>
 * Alain Folletete <alain@smalte.org>
 * Raphaël Malié <raphael@smalte.org>
 *
 * Thanks a lot to our community!
 *
 * Read LICENCE file for more information.
 */

namespace Controllers\FrontOffice;

use \Smalte\Controller\Controller;

class Home extends Controller
{
	public function displayAction()
	{
		// Set template vars like this
		$this->templateVars = array(
			'test' => 'mycontent',
			'date' => date('H:i:s'),
		);

		// Controller resolver will automatically render the template corresponding to this method (home/display)

		// You can change template with this method
		// $this->setTemplate('home/index');

		// In case of json answer (for example)
		// You can avoid template rendering with this method
		// $this->noRender();

		// You will be able to set the Json content with this method
		// $this->setResponseContent(json_encode(array('Smalte', 'is', 'good')));
	}
}

Add automatic template render on Controller :D


<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Homepage extends Application {

    /**
     * Index Page for the Homepage controller.
     */
    public function index()
    {
        /* Grab data from database for Stocks and Players */
        $this->data['stocks']             = $this->stocks->getAllStocks();
        $this->data['players']            = $this->players->getAllPlayers();
        $this->data['latestmovements']    = $this->movements->latest5Movements();
        $this->data['latesttransactions'] = $this->transactions->latest5transactions();

        /* Grab game status */
        $status = $this->managements->getServerStatus();

        /* Set up data to render page */
        $this->data['title'] = "Stock Ticker";
        $this->data['left-panel-content'] = 'base/players.php';
        $this->data['right-panel-content'] = 'base/stocks.php';

        $this->render();
    }
}

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Homepage extends Application {

    /**
     * Index Page for the Homepage controller.
     */
    public function index()
    {
        /* Grab data from database for Stocks and Players */
        $this->data['stocks']             = $this->stocks->getAllStocks();
        $this->data['players']            = $this->players->getAllPlayers();
        $this->data['latestmovements']    = $this->movements->latest5Movements();
        $this->data['latesttransactions'] = $this->transactions->latest5transactions();

        /* Set up data to render page */
        $this->data['title'] = "Stock Ticker";
        $this->data['left-panel-content'] = 'base/players.php';
        $this->data['right-panel-content'] = 'base/stocks.php';

        $this->render();
    }

    public function status()
    {
        /* Grab game status */
        $status = $this->managements->getServerStatus();
        $this->output->set_header('Content-Type: application/json; charset=utf-8');
        echo json_encode($status);
    }
}

Create json for bsx server status

Create json for bsx server status


<?php
/*
Template Name: Home Page - Banner
*/
?>

<?php get_header(); ?>

<  S T A G E  >

“Stage makes front-end development on WordPress faster and easier. It's made for devices of all shapes and projects of all sizes”

     Download from GitHub

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

	<?php the_content(); ?>

<?php endwhile; else: ?>

<?php _e('Sorry, no posts matched your criteria.'); ?>

<?php endif; ?>

 <?php get_footer(); ?>

Add css class for banner background

Add css class for banner background


<?php

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

namespace Symfony\Component\PropertyInfo;

/**
 * Guesses the property's human readable description.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
interface PropertyDescriptionExtractorInterface
{
    /**
     * Gets the short description of the property.
     *
     * @return string|null
     */
    public function getShortDescription(string $class, string $property, array $context = []);

    /**
     * Gets the long description of the property.
     *
     * @return string|null
     */
    public function getLongDescription(string $class, string $property, array $context = []);
}

<?php

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

namespace Symfony\Component\PropertyInfo;

/**
 * Guesses the property's human readable description.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
interface PropertyDescriptionExtractorInterface
{
    /**
     * Gets the short description of the property.
     */
    public function getShortDescription(string $class, string $property, array $context = []): ?string;

    /**
     * Gets the long description of the property.
     */
    public function getLongDescription(string $class, string $property, array $context = []): ?string;
}

Add return types - batch 5/n

Add return types - batch 5/n