<?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 spec\Sylius\Component\Cart\Resolver;

use PhpSpec\ObjectBehavior;

/**
 * @author Julien Janvier <j.janvier@gmail.com>
 */
class ItemResolvingExceptionSpec  extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Component\Cart\Resolver\ItemResolvingException');
    }

    function is_is_an_invalid_argument_exception()
    {
        $this->shouldHaveType('\InvalidArgumentException');
    }
}

<?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 spec\Sylius\Component\Cart\Resolver;

use PhpSpec\ObjectBehavior;

/**
 * @author Julien Janvier <j.janvier@gmail.com>
 */
class ItemResolvingExceptionSpec  extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Component\Cart\Resolver\ItemResolvingException');
    }

    function it_is_an_invalid_argument_exception()
    {
        $this->shouldHaveType('\InvalidArgumentException');
    }
}

Fix typo in Cart Resolver spec

Fix typo in Cart Resolver spec


<?php

namespace Adyen\Service\Resource\Recurring;

class Disable extends \Adyen\Service\Resource
{

}

<?php

namespace Adyen\Service\Resource\Recurring;

class Disable extends \Adyen\Service\Resource
{
    protected $_requiredFields = array(
        'merchantAccount',
        'shopperReference'
    );

    public function __construct($service)
    {
        $endpoint = $service->getClient()->getConfig()->get('endpoint') . '/pal/servlet/Recurring/' . $service->getClient()->getApiVersion() . '/disable';
        parent::__construct($service, $endpoint, $this->_requiredFields);
    }

}

Implement disable service with requiredFields and endpoint


<?php namespace ProcessWire; ?>
<?php $language = $content->codelanguage->title == 'riot' ? 'html' : $content->codelanguage->title; ?>
<? if($content->showcode):?>
    <div style="background-color: <?=$pages->get('/tags/'.$content->codelanguage->title)->color?>" class="code code-<?=$language?>"><?=strtoupper($content->codelanguage->title)?>

<code class="language-<?=$language?>"><?=htmlentities($content->code)?>

<? endif ?>
<? if($content->showpreview):?>
    <? if($content->codelanguage->title == 'riot'): ?>

    <? else: ?>
        <?=$content->code?>
        <application></application>

    <? endif ?>
<? endif ?>

<?php namespace ProcessWire; ?>

    <? foreach($content->codegrid as $code): ?>
        <?php
            $flex = 'flex="100"';
            if (count($content->textgrid) >= 2) {
                $flex = 'flex="100" flex-gt-md="45"';
            }
        ?>
        <div <?=$flex?>>
            <?php $language = $code->codelanguage->title == 'riot' ? 'html' : $code->codelanguage->title; ?>
            <? if($code->showcode):?>
                <div style="background-color: <?=$pages->get('/tags/'.$code->codelanguage->title)->color?>" class="code code-<?=$language?>"><?=strtoupper($code->codelanguage->title)?>

<code class="language-<?=$language?>"><?=htmlentities($code->code)?>

            <? endif ?>
            <? if($code->showpreview):?>
                <? if($code->codelanguage->title == 'riot'): ?>
                    <?= preg_replace('/\n/s', "\n\t", $code->code)?>
                <? else: ?>
                    <?=$code->code?>
                <? endif ?>
            <? endif ?>

    <? endforeach; ?>

Use codegrid and properly render riot tags on preview enabled


<?php namespace Jigsaw\Jigsaw;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;

class TemporaryFilesystem
{
    private $tempPath;
    private $filesystem;

    public function __construct($tempPath, $filesystem = null)
    {
        $this->tempPath = $tempPath;
        $this->filesystem = $filesystem ?: new Filesystem;
    }

    public function put($contents, $callback, $extension = '')
    {
        $path = $this->tempPath . '/' . Str::quickRandom(32) . $extension;
        $this->filesystem->put($path, $contents);
        $result = $callback($path);
        $this->filesystem->delete($path);
        return $result;
    }
}

<?php namespace Jigsaw\Jigsaw;

use Illuminate\Support\Str;

class TemporaryFilesystem
{
    private $tempPath;
    private $filesystem;

    public function __construct($tempPath, $filesystem = null)
    {
        $this->tempPath = $tempPath;
        $this->filesystem = $filesystem ?: new Filesystem;
    }

    public function put($contents, $callback, $extension = '')
    {
        $path = $this->tempPath . '/' . Str::quickRandom(32) . $extension;
        $this->filesystem->put($path, $contents);
        $result = $callback($path);
        $this->filesystem->delete($path);
        return $result;
    }
}

Use Jigsaw\Filesystem instead of Illuminate\Filesystem


<?php namespace Strimoid\Http\Middleware;

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as IlluminateCsrf;
use Illuminate\Session\TokenMismatchException;

class VerifyCsrfToken extends IlluminateCsrf
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @throws \Illuminate\Session\TokenMismatchException
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->isOAuth($request) || $this->isApi($request)) {
            return $next($request);
        }

        if ($this->isReading($request) || $this->tokensMatch($request)) {
            return $this->addCookieToResponse($request, $next($request));
        }

        throw new TokenMismatchException();
    }

    /**
     * Check if request is made to OAuth Authorization Server.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    protected function isOAuth($request)
    {
        return starts_with($request->getPathInfo(), '/oauth2/');
    }

    /**
     * Check if request is made to API.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    protected function isApi($request)
    {
        return starts_with($request->getPathInfo(), '/api/');
    }
}

<?php namespace Strimoid\Http\Middleware;

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as IlluminateCsrf;
use Illuminate\Session\TokenMismatchException;

class VerifyCsrfToken extends IlluminateCsrf
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @throws \Illuminate\Session\TokenMismatchException
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->canSkipVerification($request)) {
            return $next($request);
        }

        if ($this->isReading($request) || $this->tokensMatch($request)) {
            return $this->addCookieToResponse($request, $next($request));
        }

        throw new TokenMismatchException();
    }

    /**
     * Check if verification should be omitted.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    protected function canSkipVerification($request)
    {
        return starts_with($request->getPathInfo(), [
            '/oauth2/', '/api/', '/pusher/'
        ]);
    }
}

Disable CRSF token verification for /pusher/ endpoint


<?php

namespace Orm\Zed\Url\Persistence;

use Spryker\Zed\Url\Persistence\Propel\AbstractSpyRedirectQuery as BaseSpyRedirectQuery;

/**
 * Skeleton subclass for performing query and update operations on the 'spy_redirect' 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.
 */
class SpyRedirectQuery extends BaseSpyRedirectQuery
{
}

<?php

namespace Orm\Zed\Url\Persistence;

use Spryker\Zed\Url\Persistence\Propel\AbstractSpyUrlRedirectQuery as BaseSpyRedirectQuery;

/**
 * Skeleton subclass for performing query and update operations on the 'spy_redirect' 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.
 */
class SpyRedirectQuery extends BaseSpyRedirectQuery
{
}

Fix documentation for CMS and also fix URLs to not wrongly append trailing slash.


<?php

namespace Grom\Silex;

use Silex\Application;
use Silex\ExtensionInterface;
use Knplabs\Snappy\Image;
use Knplabs\Snappy\Pdf;

/**
 * Silex extension to integrate Snappy library.
 *
 * @author Jérôme Tamarelle <jerome@tamarelle.net>
 */
class SnappyExtension implements ExtensionInterface
{
    public function register(Application $app)
    {
        $app['snappy.image'] = $app->share(function () use ($app) {
            return new Image($app['snappy.image_binary']);
        });

        $app['snappy.pdf'] = $app->share(function () use ($app) {
            return new Pdf($app['snappy.pdf_binary']);
        });

        if (isset($app['snappy.class_path'])) {
            $app['autoloader']->registerNamespace('Knplabs\\Snappy', $app['snappy.class_path']);
        }
    }
}

<?php

namespace Grom\Silex;

use Silex\Application;
use Silex\ExtensionInterface;
use Knp\Snappy\Image;
use Knp\Snappy\Pdf;

/**
 * Silex extension to integrate Snappy library.
 *
 * @author Jérôme Tamarelle <jerome@tamarelle.net>
 */
class SnappyExtension implements ExtensionInterface
{
    public function register(Application $app)
    {
        $app['snappy.image'] = $app->share(function () use ($app) {
            return new Image(
                isset($app['snappy.image_binary']) ? $app['snappy.image_binary'] : '/usr/local/bin/wkhtmltoimage',
                isset($app['snappy.image_options']) ? $app['snappy.image_options'] : array()
            );
        });

        $app['snappy.pdf'] = $app->share(function () use ($app) {
            return new Pdf(
                isset($app['snappy.pdf_binary']) ? $app['snappy.pdf_binary'] : '/usr/local/bin/wkhtmltopdf',
                isset($app['snappy.pdf_options']) ? $app['snappy.pdf_options'] : array()
            );
        });

        if (isset($app['snappy.class_path'])) {
            $app['autoloader']->registerNamespace('Knp\\Snappy', $app['snappy.class_path']);
        }
    }
}

Update to upstream Snappy lib

[Snappy] Update to upstream Snappy lib


<?php

use \App\Http\Controllers\jsonApi\WorkdayController;

$app->get(
    'workdays',
    ['uses' => WorkdayController::class.'@index']
);
$app->get(
    'workdays/{id}',
    ['uses' => WorkdayController::class.'@show']
);
$app->post(
    '/workdays',
    ['uses' => WorkdayController::class.'@store']
);
$app->delete(
    '/workdays/{id}',
    ['uses' => WorkdayController::class.'@destroy']
);
$app->patch(
    '/workdays/{id}',
    ['uses' => WorkdayController::class.'@update']
);

<?php

use \App\Http\Controllers\JsonApi\WorkdayController;

$app->get(
    'workdays',
    ['uses' => WorkdayController::class.'@index']
);
$app->get(
    'workdays/{id}',
    ['uses' => WorkdayController::class.'@show']
);
$app->post(
    '/workdays',
    ['uses' => WorkdayController::class.'@store']
);
$app->delete(
    '/workdays/{id}',
    ['uses' => WorkdayController::class.'@destroy']
);
$app->patch(
    '/workdays/{id}',
    ['uses' => WorkdayController::class.'@update']
);

Fix controller's namespace on routing

Fix controller's namespace on routing


<?php
include 'db.php';
include 'lib/php/load.php';
include 'html/templates/Header.php';
include 'lib/php/html/tabs.php';

//Load the necessary tabs for the page

//Check to see which template is needed

	if (isset($_GET['i']))
		{
			$pg = load($_GET['i']);

		}

		else

		{
			$pg = load('Login.php');
		}

//Include the template

	if ($pg === false)
		{echo "Invalid File Request";}
		else
		{include($pg);}

include 'html/templates/Footer.php';

<?php
include 'db.php';
include 'lib/php/load.php';
include 'html/templates/Header.php';
include 'lib/php/html/tabs.php';

//Check to see which template is needed

	if (isset($_GET['i']))
		{
			$pg = load($_GET['i']);

		}

		else

		{
			$pg = load('Login.php');
		}

//Include the template

	if ($pg === false)
		{echo "Invalid File Request";}
		else
		{include($pg);}

//Check to see if the user has been logged out for inactivity and notify them

	if (isset($_GET['force_close']))
		{
		echo <<<FC
		<script type = 'text/javascript'>
		$('#idletimeout').css('display','block');
	</script>

FC;
		}

include 'html/templates/Footer.php';

Add notification that user has been logged off due to inactivity

git-svn-id: 245d8f85226f8eeeaacc1269b037bb4851d63c96@790 54a900ba-8191-11dd-a5c9-f1483cedc3eb


<?php

function debug_collectionInfoStart($debug) {
    if ($debug == TRUE) {
        echo "[DEBUG] Collecting data\n";
    }
}

function debug_collectionInfoEnd($debug) {
    if ($debug == TRUE) {
        echo "[DEBUG] Finished collecting data\n";
    }
}

function debug_collectionInterval($debug, $interval) {
    if ($debug == TRUE) {
        echo "[DEBUG] Collecting data every ".$interval." seconds\n\n";
    }
}

function debug($echo, $log) {

    if ($echo != "" && $echo !== NULL) {
    echo $echo;
    }

    if ($log == TRUE) {
        file_put_contents("logs/collect.log", $echo);
    }
}

?>

<?php

function debug_collectionInfoStart($debug) {
    if ($debug == TRUE) {
        echo "[DEBUG] Collecting data\n";
    }
}

function debug_collectionInfoEnd($debug) {
    if ($debug == TRUE) {
        echo "[DEBUG] Finished collecting data\n";
    }
}

function debug_collectionInterval($debug, $interval) {
    if ($debug == TRUE) {
        echo "[DEBUG] Collecting data every ".$interval." seconds\n\n";
    }
}

function debug($echo, $log) {

    if ($echo != "" && $echo !== NULL) {
    echo $echo;
    }

    if ($log == TRUE) {
        file_put_contents("logs/collect.log", $echo, FILE_APPEND);
    }
}

?>

Append to log file instead of overwrite it


<?php

namespace Tests\AppBundle\API\Listing;

use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;

class OrganismsTest extends WebserviceTestCase
{
    public function testExecute()
    {
        $organisms = $this->webservice->factory('listing', 'organisms');
        $parameterBag = new ParameterBag(array('dbversion' => $this->default_db, 'search' => 'bla', 'limit' => 5));
        $results = $organisms->execute($parameterBag, null);
        $expected = array(
            array("fennec_id" => 2243, "scientific_name" => "Anemone blanda"),
            array("fennec_id" => 3520, "scientific_name" => "Lablab purpureus"),
            array("fennec_id" => 4295, "scientific_name" => "Tmesipteris oblanceolata"),
            array("fennec_id" => 4357, "scientific_name" => "Silene oblanceolata"),
            array("fennec_id" => 5588, "scientific_name" => "Verbascum blattaria")
        );
        $this->assertEquals($expected, $results);
    }
}

<?php

namespace Tests\AppBundle\API\Listing;

use Tests\AppBundle\API\WebserviceTestCase;
use AppBundle\API\Listing;

class OrganismsTest extends WebserviceTestCase
{
    private $em;

    public function setUp()
    {
        $kernel = self::bootKernel();

        $this->em = $kernel->getContainer()
            ->get('doctrine')
            ->getManager('test');

    }

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

        $this->em->close();
        $this->em = null; // avoid memory leaks
    }

    public function testExecute()
    {
        $organisms = $this->webservice->factory('listing', 'organisms');
        $parameterBag = new ParameterBag(array('dbversion' => $this->default_db, 'search' => 'bla', 'limit' => 5));
        $results = $organisms->execute($parameterBag, null);
        $expected = array(
            array("fennec_id" => 2243, "scientific_name" => "Anemone blanda"),
            array("fennec_id" => 3520, "scientific_name" => "Lablab purpureus"),
            array("fennec_id" => 4295, "scientific_name" => "Tmesipteris oblanceolata"),
            array("fennec_id" => 4357, "scientific_name" => "Silene oblanceolata"),
            array("fennec_id" => 5588, "scientific_name" => "Verbascum blattaria")
        );
        $this->assertEquals($expected, $results);
    }
}

Add setup function to organism test for listing


<?php

use App\Bootstrap\ViewComposer;
use App\Controllers;
use DI\Container;
use DI\Bridge\Slim\Bridge;
use Dotenv\Dotenv;
use PHLAK\Config\Config;
use Slim\Views\Twig;

require __DIR__ . '/vendor/autoload.php';

/** Initialize environment variable handler */
$dotenv = Dotenv::create(__DIR__);
$dotenv->load();

/** Create the container */
$container = new Container();

/** Register dependencies */
$container->set(Config::class, new Config('app/config'));
$container->set(Twig::class, function (Config $config) {
    return new Twig("app/themes/{$config->get('theme')}", [
        'cache' => $config->get('view_cache', 'app/cache/views')
    ]);
});

/** Configure the view handler */
$container->call(ViewComposer::class);

/** Create the application */
$app = Bridge::create($container);

/** Register routes */
$app->get('/[{path:.*}]', Controllers\DirectoryController::class);

/** Enagage! */
$app->run();

<?php

use App\Bootstrap\ViewComposer;
use App\Controllers;
use DI\Container;
use DI\Bridge\Slim\Bridge;
use Dotenv\Dotenv;
use PHLAK\Config\Config;
use Slim\Views\Twig;

require __DIR__ . '/vendor/autoload.php';

/** Set some restrictions */
ini_set('open_basedir', __DIR__);

/** Initialize environment variable handler */
$dotenv = Dotenv::create(__DIR__);
$dotenv->load();

/** Create the container */
$container = new Container();

/** Register dependencies */
$container->set(Config::class, new Config('app/config'));
$container->set(Twig::class, function (Config $config) {
    return new Twig("app/themes/{$config->get('theme')}", [
        'cache' => $config->get('view_cache', 'app/cache/views')
    ]);
});

/** Configure the view handler */
$container->call(ViewComposer::class);

/** Create the application */
$app = Bridge::create($container);

/** Register routes */
$app->get('/[{path:.*}]', Controllers\DirectoryController::class);

/** Enagage! */
$app->run();

Set open_basedir to restrict file access to the current directory


<?php

class Benchmark
{
    public function run($runCount = 100000)
    {
        $functions = array("abs", "acos", "asin", "atan", "floor", "exp", "sin", "tan", "sqrt");

        for ($i = 0; $i < $runCount; $i++) {
            foreach ($functions as $function) {
				call_user_func_array($function, array($i));
            }
        }
    }
}

$benchmark = new Benchmark();

$benchmark->run();

<?php

class Benchmark
{
    public function run($runCount = 2500)
    {
        $functions = array("abs", "acos", "asin", "atan", "floor", "exp", "sin", "tan", "sqrt");

        for ($i = 0; $i < $runCount; $i++) {
            foreach ($functions as $function) {
				call_user_func_array($function, array($i));
            }
        }
    }
}

$benchmark = new Benchmark();

$benchmark->run();

Decrease load generated by the benchmark


<?php
class A01_Frontend_ProfileCest extends CestAbstract
{
    /**
     * @before setupComplete
     * @before login
     */
    public function setProfileInfo(FunctionalTester $I)
    {
        $I->wantTo('Set a user profile.');

        $I->amOnPage('/dashboard');
        $I->see('Dashboard');

        $I->amOnPage('/profile');
        $I->see('Profile');
        $I->see('Super Administrator');

        $I->click('Edit');

        $I->submitForm('.form', [
            'timezone' => 'US/Central',
            'locale' => 'fr_FR.UTF-8',
        ]);

        $I->seeCurrentUrlEquals('/profile');
        $I->see('Central Time');
        $I->see('Français');
    }
}

<?php
class A01_Frontend_ProfileCest extends CestAbstract
{
    /**
     * @before setupComplete
     * @before login
     */
    public function setProfileInfo(FunctionalTester $I)
    {
        $I->wantTo('Set a user profile.');

        $I->amOnPage('/dashboard');
        $I->see('Dashboard');

        $I->amOnPage('/profile');
        $I->see('Profile');
        $I->see('Super Administrator');

        $I->click('Edit');

        $I->submitForm('.form', [
            'timezone' => 'America/Chicago',
            'locale' => 'fr_FR.UTF-8',
        ]);

        $I->seeCurrentUrlEquals('/profile');
        $I->see('Chicago');
        $I->see('Français');
    }
}

Fix unit test that refers to a now-aliased time zone.


<?php

require_once '../lib/Postmark/Autoloader.php';
\Postmark\Autoloader::register();

// this file should be the target of the callback you set in your postmark account
//$inbound = new \Postmark\Inbound(file_get_contents('../fixtures/inbound.json'));
$inbound = new \Postmark\Inbound(file_get_contents('php://input'));

echo $inbound->Subject();

$inbound->Headers('Reivd-SPF');

<?php

require_once '../lib/Postmark/Autoloader.php';
\Postmark\Autoloader::register();

// this file should be the target of the callback you set in your postmark account
$inbound = new \Postmark\Inbound(file_get_contents('../fixtures/inbound.json'));
//$inbound = new \Postmark\Inbound(file_get_contents('php://input'));

//echo $inbound->Subject();

var_dump($inbound->Headers('Reivd-SPF'));

Revert "revert changes in example"

Revert "revert changes in example"

This reverts commit fd2ba5245c6c8c388a0c693b736d9b2f5b720794.


<?php

namespace Neblion\AppBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/hello/Fabien');

        $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
    }
}

<?php

namespace Neblion\AppBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {

    }
}

Test: Remove default assertion for Default controller


<?php
require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();

$app->get('/hello/{name}', function ($name) use ($app) {
  return 'Hello '.$app->escape($name);
});

return $app;

<?php
require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();
$app['debug'] = true;

$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
    'db.options' => array(
        'driver'   => 'pdo_sqlite',
        'path'     => __DIR__.'/../db/worldcup.db',
    ),
));

$app->get('/hello/{name}', function ($name) use ($app) {
    return 'Hello '.$app->escape($name);
});

return $app;

Add service provider for sqlite database


<?php
namespace Concrete\Package\KintDebug;

use Concrete\Core\Package\Package;
use View;

defined('C5_EXECUTE') or die(t("Access Denied."));

require_once __DIR__ . '/vendor/autoload.php';

class Controller extends Package {
    protected $pkgHandle = 'kint_debug';
    protected $appVersionRequired = '5.7.0.4';
    protected $pkgVersion = '0.9.1';

    public function getPackageDescription() {
        return t('Add Kint debugging tools');
    }

    public function getPackageName() {
        return t('Kint Debug');
    }

    public function on_start() {
        $al = \Concrete\Core\Asset\AssetList::getInstance();
        $al->register('css', $this->pkgHandle . '/css', 'css/debug.css', array(), $this->pkgHandle);
        View::getInstance()->requireAsset('css', $this->pkgHandle . '/css');
    }
}

<?php
namespace Concrete\Package\KintDebug;

use Concrete\Core\Package\Package;
use View;

defined('C5_EXECUTE') or die(_("Access Denied."));

require_once __DIR__ . '/vendor/autoload.php';

class Controller extends Package {
    protected $pkgHandle = 'kint_debug';
    protected $appVersionRequired = '5.7.0.4';
    protected $pkgVersion = '0.9.1';

    public function getPackageDescription() {
        return t('Add Kint debugging tools');
    }

    public function getPackageName() {
        return t('Kint Debug');
    }

    public function on_start() {
        $al = \Concrete\Core\Asset\AssetList::getInstance();
        $al->register('css', 'kint_debug/css', 'css/debug.css', array(), $this->pkgHandle);

        // Never include the css in ajax responses
        if(!$this->isAjaxRequest()) {
            View::getInstance()->requireAsset('css', 'kint_debug/css');
        }
    }

    /**
     * Check, if possible, that this execution was triggered by an AJAX request.
     * @return bool
     */
    protected function isAjaxRequest()
    {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
            strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    }
}

Fix CSS getting required in AJAX request


<?php

namespace LAG\AdminBundle\Event;

class AdminEvents
{
    const HANDLE_REQUEST = 'lag.admin.handleRequest';

    const HANDLE_FORM = 'lag.admin.handleForm';

    const ADMIN_CONFIGURATION = 'lag.admin.admin_configuration';

    const ACTION_CONFIGURATION = 'lag.admin.action_configuration';

    const FILTER = 'lag.admin.filter';

    const VIEW = 'lag.admin.view';

    const MENU = 'lag.admin.menu';

    const ENTITY_LOAD = 'lag.admin.entity_load';

    const ENTITY_SAVE = 'lag.admin.entity_save';

    const DOCTRINE_ORM_FILTER = 'lag.admin.doctrine_orm_filter';
}

<?php

namespace LAG\AdminBundle\Event;

class AdminEvents
{
    const HANDLE_REQUEST = 'lag.admin.handleRequest';

    const HANDLE_FORM = 'lag.admin.handleForm';

    const ADMIN_CONFIGURATION = 'lag.admin.admin_configuration';

    const ACTION_CONFIGURATION = 'lag.admin.action_configuration';

    const MENU_CONFIGURATION = 'lag.admin.menu_configuration';

    const FILTER = 'lag.admin.filter';

    const VIEW = 'lag.admin.view';

    const MENU = 'lag.admin.menu';

    const ENTITY_LOAD = 'lag.admin.entity_load';

    const ENTITY_SAVE = 'lag.admin.entity_save';

    const DOCTRINE_ORM_FILTER = 'lag.admin.doctrine_orm_filter';
}

Add an event to change the menu configuration before resolving


<?php

require __DIR__ . '/src/Vlc.php';
require file_exists(__DIR__ . '/conf.php') ? __DIR__ . '/conf.php' : __DIR__ . '/default.conf.php';

$vlc = new \jcisio\Karaoke\Vlc('127.0.0.1', 8080, '1234', array('/media/hd2/Karaoke'));
$items = $vlc->getFileList();
$action = isset($_GET['action']) ? $_GET['action'] : 'list';

switch ($action) {
  case 'list':
    $data = array();
    foreach ($items as $uri) {
      $data[] = array(pathinfo(urldecode($uri), PATHINFO_FILENAME));
    }
    die(json_encode(array('data' => $data)));
    break;

  case 'fullscreen':
    $vlc->send('status', array('command' => 'fullscreen'));
    return;

  case 'audio':
    $status = $vlc->send('status');
    foreach ($status->Streams as $s){};return;

  case 'play':
  case 'queue':
    $id = (int) $_GET['id'];
    $command = $action == 'play' ? 'in_play' : 'in_enqueue';
    $vlc->send('status', array(
      'command' => $command,
      'input' => $items[$id],
    ));
    break;
}

<?php

require __DIR__ . '/src/Vlc.php';
require file_exists(__DIR__ . '/conf.php') ? __DIR__ . '/conf.php' : __DIR__ . '/default.conf.php';

$vlc = new \jcisio\Karaoke\Vlc($host, $port, $password, $paths);
$items = $vlc->getFileList();
$action = isset($_GET['action']) ? $_GET['action'] : 'list';

switch ($action) {
  case 'list':
    $data = array();
    foreach ($items as $uri) {
      $data[] = array(pathinfo(urldecode($uri), PATHINFO_FILENAME));
    }
    die(json_encode(array('data' => $data)));
    break;

  case 'fullscreen':
    $vlc->send('status', array('command' => 'fullscreen'));
    return;

  case 'audio':
    $status = $vlc->send('status');
    foreach ($status->Streams as $s){};return;

  case 'play':
  case 'queue':
    $id = (int) $_GET['id'];
    $command = $action == 'play' ? 'in_play' : 'in_enqueue';
    $vlc->send('status', array(
      'command' => $command,
      'input' => $items[$id],
    ));
    break;
}

Use settings from conf file

Use settings from conf file


<?php

require_once("config.php");

if(!@mysql_connect("$DBIP","$DBUSER","$DBPASS"))
{
	echo "Result:4";
	die();
}

mysql_select_db("$DBNAME");

if ($_REQUEST["myl"] != "")
{
  $temp = split(":", $_REQUEST["myl"]);
  $mcc = $temp[0];
  $mnc = $temp[1];
  $lac = $temp[2];
  $cid = $temp[3];
} else
{
  $mcc = $_REQUEST["mcc"];
  $mnc = $_REQUEST["mnc"];
  $lac = $_REQUEST["lac"];
  $cid = $_REQUEST["cid"];
}

if ( $mcc == "" || $mnc == "" || $lac == "" || $cid == "" )
{
		echo "Result:7"; // CellID not specified
	 	die();
}

$result=mysql_query("Select latitude,longitude FROM cellids WHERE cellid='$mcc-$mnc-$lac-$cid' order by dateadded desc limit 0,1");

if ( $row=mysql_fetch_array($result) )
	echo "Result:0|".$row['latitude']."|".$row['longitude'];
else
	echo "Result:6"; // No lat/long for specified CellID

die();

?>

<?php

require_once("database.php");

$db = connect_save();

if ($db === null)
{
	echo "Result:4";
	die();
}

if ($_REQUEST["myl"] != "")
{
  $temp = split(":", $_REQUEST["myl"]);
  $mcc = $temp[0];
  $mnc = $temp[1];
  $lac = $temp[2];
  $cid = $temp[3];
} else
{
  $mcc = $_REQUEST["mcc"];
  $mnc = $_REQUEST["mnc"];
  $lac = $_REQUEST["lac"];
  $cid = $_REQUEST["cid"];
}

if ( $mcc == "" || $mnc == "" || $lac == "" || $cid == "" )
{
		echo "Result:7"; // CellID not specified
	 	die();
}

$result = $db->exec_sql("SELECT Latitude, Longitude FROM cellids WHERE CellID=? ORDER BY DateAdded DESC LIMIT 0,1", "$mcc-$mnc-$lac-$cid");

if ( $row=$result->fetch() )
        echo "Result:0|$row[Latitude]|$row[Longitude]";
else
	echo "Result:6"; // No lat/long for specified CellID

die();

?>

Use PDO in the local cellid script

Use PDO in the local cellid script

With 13ae949 the `mysql` calls have been changed to calls using the `PDO`
classes. This updates `cellid_local.php` to use `PDO` as well. It also uses
the proper capitalisation of the columns because at least the SQLite driver
is case sensitive.


@extends('layouts.app')

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

@extends('layouts.app')

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

Change syntax of template call to match other files in views/


<?php
require_once dirname(__FILE__).'/../phpunit.php';

if(!defined('PHPUnit_MAIN_METHOD')) {
  define('PHPUnit_MAIN_METHOD', 'Web_AllTests::main');
}

require_once 'TAssetManagerTest.php';
require_once 'THttpCookieCollectionTest.php';
require_once 'THttpCookieTest.php';
require_once 'THttpRequestTest.php';
require_once 'THttpResponseTest.php';
require_once 'THttpSessionTest.php';
require_once 'THttpUtilityTest.php';
require_once 'TUriTest.php';

require_once 'UI/AllTests.php';

class Web_AllTests {
  public static function main() {
    PHPUnit_TextUI_TestRunner::run(self::suite());
  }

  public static function suite() {
    $suite = new PHPUnit_Framework_TestSuite('System.Web');

	$suite->addTestSuite('TAssetManagerTest');
	$suite->addTestSuite('THttpCookieCollectionTest');
	$suite->addTestSuite('THttpCookieTest');
    $suite->addTestSuite('THttpRequestTest');
	$suite->addTestSuite('THttpResponseTest');
	$suite->addTestSuite('THttpSessionTest');
	$suite->addTestSuite('THttpUtilityTest');
	$suite->addTestSuite('TUriTest');

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

    return $suite;
  }
}

if(PHPUnit_MAIN_METHOD == 'Web_AllTests::main') {
  Web_AllTests::main();
}
?>

<?php
require_once dirname(__FILE__).'/../phpunit.php';

if(!defined('PHPUnit_MAIN_METHOD')) {
  define('PHPUnit_MAIN_METHOD', 'Web_AllTests::main');
}

require_once 'TAssetManagerTest.php';
require_once 'THttpCookieCollectionTest.php';
require_once 'THttpCookieTest.php';
require_once 'THttpRequestTest.php';
require_once 'THttpResponseTest.php';
require_once 'THttpSessionTest.php';
require_once 'THttpUtilityTest.php';
require_once 'TUriTest.php';

require_once 'UI/AllTests.php';

class Web_AllTests {
  public static function main() {
    PHPUnit_TextUI_TestRunner::run(self::suite());
  }

  public static function suite() {
    $suite = new PHPUnit_Framework_TestSuite('System.Web');

    $suite->addTestSuite('THttpRequestTest');
	$suite->addTestSuite('TAssetManagerTest');
	$suite->addTestSuite('THttpCookieCollectionTest');
	$suite->addTestSuite('THttpCookieTest');
	$suite->addTestSuite('THttpResponseTest');
	$suite->addTestSuite('THttpSessionTest');
	$suite->addTestSuite('THttpUtilityTest');
	$suite->addTestSuite('TUriTest');

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

    return $suite;
  }
}

if(PHPUnit_MAIN_METHOD == 'Web_AllTests::main') {
  Web_AllTests::main();
}
?>

Change the order of the Web_Alltests suite


<?php
class Kwc_Mail_Placeholder_Content_Component extends Kwc_Abstract
{
    public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
    {
        $ret = parent::getTemplateVars();
        if ($renderer && $renderer instanceof Kwf_Component_Renderer_Mail) {
            $user = $renderer->getRecipient();
            $ret['username'] = $user ? $user->getMailLastname() : 'noname';
        }
        return $ret;
    }
}

<?php
class Kwc_Mail_Placeholder_Content_Component extends Kwc_Abstract
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['viewCache'] = false;
        return $ret;
    }

    public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
    {
        $ret = parent::getTemplateVars();
        if ($renderer && $renderer instanceof Kwf_Component_Renderer_Mail) {
            $user = $renderer->getRecipient();
            $ret['username'] = $user ? $user->getMailLastname() : 'noname';
        }
        return $ret;
    }
}

Fix test, disable view cache as getTemplateVars is dynamic

before view cache was disabled for the whole test


<?php
$u = new User();
$ui = UserInfo::getByID($u->getUserID());

if ($u) {
    $userInfo = [
      'name' => $u->getUserName(),
      'firstName' => $ui->getAttribute('first_name')
  ];
}

// Capture renderable areas
ob_start();
(new GlobalArea('Left Header'))->display($c);
$LeftHeader = ['Left Header' => ob_get_clean()];

ob_start();
(new GlobalArea('Dropdown'))->display($c);
$Dropdown = ['Dropdown' => ob_get_clean()];

?>

<?php
$u = new User();

if ($u->getUserID()) {
    $ui = UserInfo::getByID($u->getUserID());
    $userInfo = [
      'name' => $u->getUserName(),
      'firstName' => $ui->getAttribute('first_name')
  ];
}

// Capture renderable areas
ob_start();
(new GlobalArea('Left Header'))->display($c);
$LeftHeader = ['Left Header' => ob_get_clean()];

ob_start();
(new GlobalArea('Dropdown'))->display($c);
$Dropdown = ['Dropdown' => ob_get_clean()];

?>

Validate user exists before sending its info out


<?php
class Kwc_Favourites_Box_Component extends Kwc_Abstract
{
    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $ret['favourite'] = Kwf_Component_Data_Root::getInstance()
            ->getComponentByClass('Kwc_Favourites_Page_Component');
        if (!$ret['favourite']) {
            throw new Kwf_Exception('Could not find "Kwc_Favourites_Page_Component"');
        }
        return $ret;
    }
}

<?php
class Kwc_Favourites_Box_Component extends Kwc_Abstract
{
    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $ret['favourite'] = Kwf_Component_Data_Root::getInstance()
            ->getComponentByClass('Kwc_Favourites_Page_Component', array('subroot' => $this->getData()));
        if (!$ret['favourite']) {
            throw new Kwf_Exception('Could not find "Kwc_Favourites_Page_Component"');
        }
        return $ret;
    }
}

Enable multi-domain support for favourite-component


<?php

namespace App\Console\Commands;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Console\Command;

class UpdateCloudfrontIps extends Command
{

    protected $signature = 'update:cloudfront-ips';

    protected $description = 'Update file cache of CloudFront IPs for TrustProxies';

    public function handle()
    {
        // This throws an exception if the URL is unreachable
        $contents = file_get_contents('http://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips');

        if ($contents === false) {
            return;
        }

        // API-189: Remember for two hours, and keep the file as fallback
        // This command should be run on both app and utility after deploy
        Cache::remember('list-cloudfront-ips', 60 * 60 * 2, function () use ($contents) {
            return $contents;
        });

        Storage::put('list-cloudfront-ips.json', $contents);

        $this->info('Cloudfront IPs updated!');
    }
}

<?php

namespace App\Console\Commands;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Console\Command;

class UpdateCloudfrontIps extends Command
{

    protected $signature = 'update:cloudfront-ips';

    protected $description = 'Update file cache of CloudFront IPs for TrustProxies';

    public function handle()
    {
        // This throws an exception if the URL is unreachable
        $contents = file_get_contents('http://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips');

        if ($contents === false) {
            return;
        }

        // API-189: Remember for two hours, and keep the file as fallback
        // This command should be run on both app and utility after deploy
        Cache::set('list-cloudfront-ips', $contents, 60 * 60 * 2);

        Storage::put('list-cloudfront-ips.json', $contents);

        $this->info('Cloudfront IPs updated!');
    }
}

Use `set` instead of `remember` for CloudFront IPs [API-189]


<?php

namespace DZunke\FeatureFlagsBundle\Twig;

use DZunke\FeatureFlagsBundle\Toggle;

class FeatureExtension extends \Twig_Extension
{

    /**
     * @var Toggle
     */
    protected $toggle;

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

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('has_feature', [$this, 'checkFeature'], ['is_safe' => ['html']]),
        ];
    }

    /**
     * @param string $name
     * @param array  $arguments
     * @return bool
     */
    public function checkFeature($name, $arguments = null)
    {
        return $this->toggle->isActive($name, $arguments);
    }

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

<?php

namespace DZunke\FeatureFlagsBundle\Twig;

use DZunke\FeatureFlagsBundle\Toggle;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class FeatureExtension extends AbstractExtension
{

    /**
     * @var Toggle
     */
    protected $toggle;

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

    public function getFunctions()
    {
        return [
            new TwigFunction('has_feature', [$this, 'checkFeature'], ['is_safe' => ['html']]),
        ];
    }

    /**
     * @param string $name
     * @param array  $arguments
     * @return bool
     */
    public function checkFeature($name, $arguments = null)
    {
        return $this->toggle->isActive($name, $arguments);
    }

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

Replace Twig global namespaces to support Twig 3

Use of the globally namespaced Twig functions was deprecated in Twig 2.x and removed in Twig 3.x.

This commit simply replaces the globally namespaced functions with their namespaced equivalents.


<?php

if($loguser['powerlevel'] > 3)
{
	Write("

						" . __("Badge Manager Panel") . "

									" . __("Add a new badge for this user") . "
									 —
									" . __("Delete all badges of this user") . "

");
}
?>

Add background for user profile hints in user badge manager


<?php
	namespace Bolt\Api\Request;

	class Headers extends \Bolt\Base
	{
		private $headers;

		public function __construct($auto = false)
		{
			if ($auto === true)
			{
				$this->parse();
			}
		}

		public function __get($name)
		{
			return $this->$name;
		}

		public function __isset($name)
		{
			return isset($this->headers[$name]) ? true : false;
		}

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

			$this->headers[$name] = $arguments[0];
			return true;
		}

		private function fetchHeaders()
		{
			$headers = array();

			foreach ($_SERVER as $key => $value)
			{
				if (strpos($key, "HTTP_") === 0)
				{
					$bits = explode("_", $key);
					array_shift($bits);

					foreach ($bits as &$bit)
					{
						$bit = ucwords(strtolower($bit));
					}

					$headers[implode("-", $bits)] = $value;
				}
			}

			return $headers;
		}

		public function parse()
		{
            $this->headers = array_change_key_case(apache_request_headers(), CASE_LOWER);
		}
	}
?>

<?php
	namespace Bolt\Api\Request;

	class Headers extends \Bolt\Base
	{
		private $headers;

		public function __construct($auto = false)
		{
			if ($auto === true)
			{
				$this->parse();
			}
		}

		public function __get($name)
		{
			return $this->$name;
		}

		public function __isset($name)
		{
			return isset($this->headers[$name]) ? true : false;
		}

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

			$this->headers[$name] = $arguments[0];
			return true;
		}

		private function fetchHeaders()
		{
			$headers = array();

			foreach ($_SERVER as $key => $value)
			{
				if (strpos($key, "HTTP_") === 0)
				{
					$bits = explode("_", $key);
					array_shift($bits);

					foreach ($bits as &$bit)
					{
						$bit = ucwords(strtolower($bit));
					}

					$headers[implode("-", $bits)] = $value;
				}
			}

			return $headers;
		}

		public function parse()
		{
            $this->headers = array_change_key_case($this->fetchHeaders(), CASE_LOWER);
		}
	}
?>

Use new headers method to avoid apache specific functions


<?php

namespace Scheb\TwoFactorBundle\Model\Google;

interface TwoFactorInterface
{
    /**
     * Return true if the user should do two-factor authentication.
     *
     * @return bool
     */
    public function isGoogleAuthenticatorEnabled(): bool;

    /**
     * Return the user name.
     *
     * @return string
     */
    public function getGoogleAuthenticatorUsername(): string;

    /**
     * Return the Google Authenticator secret
     * When an empty string or null is returned, the Google authentication is disabled.
     *
     * @return string
     */
    public function getGoogleAuthenticatorSecret(): string;

    /**
     * Set the Google Authenticator secret.
     *
     * @param string|null $googleAuthenticatorSecret
     */
    public function setGoogleAuthenticatorSecret(?string $googleAuthenticatorSecret): void;
}

<?php

namespace Scheb\TwoFactorBundle\Model\Google;

interface TwoFactorInterface
{
    /**
     * Return true if the user should do two-factor authentication.
     *
     * @return bool
     */
    public function isGoogleAuthenticatorEnabled(): bool;

    /**
     * Return the user name.
     *
     * @return string
     */
    public function getGoogleAuthenticatorUsername(): string;

    /**
     * Return the Google Authenticator secret
     * When an empty string or null is returned, the Google authentication is disabled.
     *
     * @return string
     */
    public function getGoogleAuthenticatorSecret(): string;
}

Remove unused method from interface

Remove unused method from interface


<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\CoreBundle\Tests\Form\Type;

use Sonata\CoreBundle\Form\Type\CollectionType;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CollectionTypeTest extends TypeTestCase
{
    public function testGetDefaultOptions()
    {
        $type = new CollectionType();

        $optionResolver = new OptionsResolver();

        $type->setDefaultOptions($optionResolver);

        $options = $optionResolver->resolve();

        $this->assertFalse($options['modifiable']);
        $this->assertEquals('text', $options['type']);
        $this->assertEquals(0, count($options['type_options']));
        $this->assertEquals('link_add', $options['btn_add']);
        $this->assertEquals('SonataCoreBundle', $options['btn_catalogue']);
    }
}

<?php

/*
 * This file is part of the Sonata package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\CoreBundle\Tests\Form\Type;

use Sonata\CoreBundle\Form\Type\CollectionType;
use Symfony\Component\Form\Tests\Extension\Core\Type\TypeTestCase;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CollectionTypeTest extends TypeTestCase
{
    public function testGetDefaultOptions()
    {
        $type = new CollectionType();

        $optionResolver = new OptionsResolver();

        $type->setDefaultOptions($optionResolver);

        $options = $optionResolver->resolve();

        $this->assertFalse($options['modifiable']);
        $this->assertEquals('text', $options['type']);
        $this->assertEquals(0, count($options['type_options']));
        $this->assertEquals('link_add', $options['btn_add']);
        $this->assertEquals('SonataCoreBundle', $options['btn_catalogue']);
    }
}

Fix namespace to work with sf2.2

Fix namespace to work with sf2.2


<?php

namespace Tco\Checkout\Helper;

use Magento\Framework\App\Helper\Context;
use Magento\Sales\Model\Order;
use Magento\Framework\App\Helper\AbstractHelper;

class Checkout extends AbstractHelper
{
    protected $session;
    protected $quote;
    protected $quoteManagement;
    protected $orderSender;

    public function __construct(
        Context $context,
        \Magento\Checkout\Model\Session $session,
        \Magento\Quote\Model\Quote $quote,
        \Magento\Quote\Model\QuoteManagement $quoteManagement,
        \Magento\Framework\Event\ManagerInterface $eventManager
    ) {
        $this->session = $session;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->_eventManager = $eventManager;
        parent::__construct($context);
    }

    public function cancelCurrentOrder($comment)
    {
        $order = $this->session->getLastRealOrder();
        if ($order->getId() && $order->getState() != Order::STATE_CANCELED) {
            $order->registerCancellation($comment)->save();
            return true;
        }
        return false;
    }

    public function restoreQuote()
    {
        return $this->session->restoreQuote();
    }

    public function getUrl($route, $params = [])
    {
        return $this->_getUrl($route, $params);
    }

}

<?php

namespace Tco\Checkout\Helper;

use Magento\Framework\App\Helper\Context;
use Magento\Sales\Model\Order;
use Magento\Framework\App\Helper\AbstractHelper;

class Checkout extends AbstractHelper
{
    protected $session;
    protected $quote;
    protected $quoteManagement;
    protected $orderSender;

    public function __construct(
        Context $context,
        \Magento\Checkout\Model\Session $session,
        \Magento\Quote\Model\Quote $quote,
        \Magento\Quote\Model\QuoteManagement $quoteManagement
    ) {
        $this->session = $session;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        parent::__construct($context);
    }

    public function cancelCurrentOrder($comment)
    {
        $order = $this->session->getLastRealOrder();
        if ($order->getId() && $order->getState() != Order::STATE_CANCELED) {
            $order->registerCancellation($comment)->save();
            return true;
        }
        return false;
    }

    public function restoreQuote()
    {
        return $this->session->restoreQuote();
    }

    public function getUrl($route, $params = [])
    {
        return $this->_getUrl($route, $params);
    }

}

Remove unnecessary eventManager from Helper


<?php namespace yfwz100\wechat\router;

class TextHandler {

  private $handlers;

  function __construct() {
    $this->handlers = array();
  }

  function match($regexp, $callback=NULL) {
    if (!$callback) {
      $this->handlers['/.*/'] = $regexp;
    } else {
      if ($regexp[0] != '/') {
        $regexp = "/$regexp/";
      }
      $this->handlers[$regexp] = $callback;
    }
  }

  function __invoke($postObj) {
    $content = $postObj->Content;
    foreach ($this->handlers as $regexp => $callback) {
      if (preg_match($regexp, $content, $matches)) {
        if (!$callback($matches)) {
          break;
        }
      }
    }
  }

}

class EventHandler extends \yfwz100\wechat\Router {

  function __construct() {
    $this->handlers = array(
      click=> new TextHandler()
    );
  }

  function __invoke($postObj) {
    $eventType = strtolower($postObj->Event);
    $this->{$msgType}($postObj);
  }

}

<?php namespace yfwz100\wechat\router;

class TextHandler {

  private $handlers;

  function __construct() {
    $this->handlers = array();
  }

  function match($regexp, $callback=NULL) {
    if (!$callback) {
      $this->handlers['/.*/'] = $regexp;
    } else {
      if ($regexp[0] != '/') {
        $regexp = "/$regexp/";
      }
      $this->handlers[$regexp] = $callback;
    }
  }

  protected function textToProcess($postObj) {
    return $postObj->Content;
  }

  function __invoke($postObj) {
    $content = $postObj->Content;
    foreach ($this->handlers as $regexp => $callback) {
      if (preg_match($regexp, $content, $matches)) {
        if (!$callback($matches)) {
          break;
        }
      }
    }
  }

}

class ClickHandler extends TextHandler {

  protected function textToProcess($postObj) {
    return $postObj->EventKey;
  }

}

class EventHandler extends \yfwz100\wechat\Router {

  function __construct() {
    $this->handlers = array(
      click=> new ClickHandler()
    );
  }

  function __invoke($postObj) {
    $eventType = strtolower($postObj->Event);
    $this->{$eventType}($postObj);
  }

}

Fix event key in click handler.

Fix event key in click handler.


<?php

namespace Behat\JournalExtension\Formatter;

use Behat\Behat\Definition\DefinitionInterface;
use Behat\Behat\Formatter\HtmlFormatter;
use Behat\Gherkin\Node\StepNode;
use Behat\Mink\Mink;
use Behat\Mink\Driver\DriverInterface;

use Behat\Mink\Driver\SeleniumDriver;

class JournalFormatter extends HtmlFormatter
{
    protected $mink;

    public function __construct(Mink $mink)
    {
        $this->mink = $mink;

        parent::__construct();
    }

    protected function printStepBlock(StepNode $step, DefinitionInterface $definition = null, $color)
    {
        parent::printStepBlock($step, $definition, $color);

        $driver = $this->mink->getSession()->getDriver();
        if ($screenshot = $this->getScreenshot($driver)) {
            $this->writeln(sprintf('<img src="data:image/png;base64,%s" />', $screenshot));
        }
    }

    protected function getScreenshot(DriverInterface $driver)
    {
        if ($driver instanceof SeleniumDriver) {
            $driver->getBrowser()->captureEntirePageScreenshot("/tmp/toto", '');

            return base64_encode(file_get_contents('/tmp/toto'));
        }
    }
}

<?php

namespace Behat\JournalExtension\Formatter;

use Behat\Behat\Definition\DefinitionInterface;
use Behat\Behat\Formatter\HtmlFormatter;
use Behat\Gherkin\Node\StepNode;
use Behat\Mink\Mink;
use Behat\Mink\Driver\DriverInterface;

use Behat\Mink\Driver\SeleniumDriver;

class JournalFormatter extends HtmlFormatter
{
    protected $mink;

    public function __construct(Mink $mink)
    {
        $this->mink = $mink;

        parent::__construct();
    }

    protected function printStepBlock(StepNode $step, DefinitionInterface $definition = null, $color)
    {
        parent::printStepBlock($step, $definition, $color);

        $driver = $this->mink->getSession()->getDriver();
        if ($screenshot = $this->getScreenshot($driver)) {
            $this->wrteln('
');
            $this->writeln(sprintf('Toggle screenshot'));
            $this->writeln(sprintf('', $screenshot));
            $this->writeln('
');
        }
    }

    protected function getHtmlTemplateScript()
    {
        $result = parent::getHtmlTemplateScript();

        $result .= <<<JS
        $(document).ready(function(){
            $('#behat .screenshot a').click(function(){
                $(this).parent().toggleClass('jq-toggle-opened');
            }).parent().addClass('jq-toggle');
        });
JS;

        return $result;
    }

    protected function getScreenshot(DriverInterface $driver)
    {
        if ($driver instanceof SeleniumDriver) {
            $driver->getBrowser()->captureEntirePageScreenshot("/tmp/toto", '');

            return base64_encode(file_get_contents('/tmp/toto'));
        }
    }
}

Add a toggler for screenshots

Add a toggler for screenshots


<?php namespace Orchestra\Extension\Console;

class RefreshCommand extends ExtensionCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'extension:refresh';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Refresh an extension.';

    /**
     * {@inheritdoc}
     */
    public function fire()
    {
        $name = $this->argument('name');

        $activated = $this->laravel['orchestra.extension']->refresh($name);

        if (!! $activated) {
            $this->info("Extension [{$name}] refreshed.");
        } else {
            $this->error("Unable to refresh extension [{$name}].");
        }
    }
}

<?php namespace Orchestra\Extension\Console;

use Illuminate\Console\ConfirmableTrait;

class RefreshCommand extends ExtensionCommand
{
    use ConfirmableTrait;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Refresh an extension.';

    /**
     * {@inheritdoc}
     */
    public function fire()
    {
        if (! $this->confirmToProceed()) {
            return null;
        }

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

        $activated = $this->laravel['orchestra.extension']->refresh($name);

        if (!! $activated) {
            $this->info("Extension [{$name}] refreshed.");
        } else {
            $this->error("Unable to refresh extension [{$name}].");
        }
    }
}

Add confirmation to `php artisan extension:refresh` command.

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


<?php

class CodesController extends \BaseController {

	public function process($code)
	{
        $code = Code::where('code', '=', $code)->first();

        if(is_null($code) || $code->used == 1){
            return Redirect::to('/');
        } else {

            //Snapchatty functions
            //Refresh(disappear) after 6 seconds
            header("Refresh: " . 6);

            $code->used = 1;
            $code->used_time = Carbon::now();
            $code->used_ip = Request::getClientIp();
            $mobileDetect = new Mobile_Detect();
            //Check for facebook bots (done in robots.txt)
            $code->used_useragent = $mobileDetect->getUserAgent();
            $code->save();

            $path = storage_path().'/memes/'.Meme::find($code->meme_id)->filename;
            // Get the image
            $image = Image::make($path)->widen(600, function ($constraint) {
                $constraint->upsize();
            })->encode('data-url');

            return View::make('meme')->withMeme($code->meme)->withImage($image);
        }

    }

}

<?php

class CodesController extends \BaseController {

	public function process($code)
	{
        $code = Code::where('code', '=', $code)->first();

        if(is_null($code) || $code->used == 1){
            return Redirect::to('/');
        } else {

            //Snapchatty functions
            //Refresh(disappear) after 4 seconds
            header("Refresh: " . 4);

            $code->used = 1;
            $code->used_time = Carbon::now();
            $code->used_ip = Request::getClientIp();
            $mobileDetect = new Mobile_Detect();
            //Check for facebook bots (done in robots.txt)
            $code->used_useragent = $mobileDetect->getUserAgent();
            $code->save();

            $path = storage_path().'/memes/'.Meme::find($code->meme_id)->filename;
            // Get the image
            $image = Image::make($path)->widen(600, function ($constraint) {
                $constraint->upsize();
            })->encode('data-url');

            return View::make('meme')->withMeme($code->meme)->withImage($image);
        }

    }

}

Change refresh time to 4 seconds

Change refresh time to 4 seconds


<?php

namespace Petty\Http\Controllers;

use Petty\Http\Requests;
use Petty\Http\Controllers\Controller;
use Petty\Http\Requests\UrlRequest;
use Petty\Models\Url;

class UrlController extends Controller
{
    protected $url;

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

    public function index()
    {
        $urls = $this->url->orderBy('created_at', 'desc')->paginate(10);

        return view('url.index', compact('urls'));
    }

    public function create()
    {
        return view('url.create');
    }

    public function store(UrlRequest $request)
    {
        $data = $request->only(['original_url']);
        $url = $this->url->create($data);
        $shortUrl = $url->short();

        return view('url.store', compact('shortUrl'));
    }

    public function show($hash)
    {
        $url = $this->url->where('hash', $hash)->first();

        return redirect()->to($url->destination_url);
    }
}

<?php

namespace Petty\Http\Controllers;

use Petty\Http\Requests;
use Petty\Http\Controllers\Controller;
use Petty\Http\Requests\UrlRequest;
use Petty\Models\Url;

class UrlController extends Controller
{
    protected $url;

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

    public function index()
    {
        $urls = $this->url->orderBy('created_at', 'desc')->paginate(10);

        return view('url.index', compact('urls'));
    }

    public function create()
    {
        return view('url.create');
    }

    public function store(UrlRequest $request)
    {
        $data = $request->only(['original_url']);
        $url = $this->url->create($data);
        $shortUrl = $url->short();

        return view('url.store', compact('shortUrl'));
    }

    public function show($hash)
    {
        $url = $this->url->where('hash', $hash)->first();
        $url->clicks += 1;
        $url->save();

        return redirect()->to($url->destination_url);
    }
}

Increment clicks in url show method

Increment clicks in url show method


<?php

use Proud\Core;

class AgencyMenu extends Core\ProudWidget {

  function __construct() {
    parent::__construct(
      'agency_menu', // Base ID
      __( 'Agency menu', 'wp-agency' ), // Name
      array( 'description' => __( "Display an agency menu", 'wp-agency' ), ) // Args
    );
  }

  function initialize() {
  }

  /**
   * Outputs the content of the widget
   *
   * @param array $args
   * @param array $instance
   */
  public function printWidget( $args, $instance ) {
      $args = array(
        'menu_class' => 'nav nav-pills nav-stacked',
      );
      if ('agency' === get_post_type()) {
          if ( $menu = get_post_meta( get_the_ID(), 'post_menu', true ) ) {
              $args['menu'] = $menu;
              wp_nav_menu( $args );
          }
      }
      else {
        global $pageInfo;
        $args = array(
          'menu' => $pageInfo['menu'],
          'menu_class' => 'nav nav-pills nav-stacked',
        );
        wp_nav_menu( $args );
      }
  }
}

// register Foo_Widget widget
function register_agency_menu_widget() {
    register_widget( 'AgencyMenu' );
}
add_action( 'widgets_init', 'register_agency_menu_widget' );

<?php

use Proud\Core;

class AgencyMenu extends Core\ProudWidget {

  function __construct() {
    parent::__construct(
      'agency_menu', // Base ID
      __( 'Agency menu', 'wp-agency' ), // Name
      array( 'description' => __( "Display an agency menu", 'wp-agency' ), ) // Args
    );
  }

  function initialize() {
  }

  /**
   * Outputs the content of the widget
   *
   * @param array $args
   * @param array $instance
   */
  public function printWidget( $args, $instance ) {
      $args = array(
        'menu_class' => 'nav nav-pills nav-stacked submenu',
        'fallback_cb' => false,
      );
      if ('agency' === get_post_type()) {
          if ( $menu = get_post_meta( get_the_ID(), 'post_menu', true ) ) {
              $args['menu'] = $menu;
              wp_nav_menu( $args );
          }
      }
      else {
        global $pageInfo;
        print_r($pageInfo);die();
        $args = array(
          'menu' => $pageInfo['menu'],
          'menu_class' => 'nav nav-pills nav-stacked',
        );
        wp_nav_menu( $args );
      }
  }
}

// register Foo_Widget widget
function register_agency_menu_widget() {
    register_widget( 'AgencyMenu' );
}
add_action( 'widgets_init', 'register_agency_menu_widget' );

Set callback param to false

Set callback param to false


<?php

/**
 * Created by PhpStorm.
 * User: Conrad
 * Date: 24/06/2016
 * Time: 9:06 AM
 */
class ModuleController extends Controller
{
    /**
     * @var ContentModule
     */
    protected $dataRecord;

    protected $currentController;

    public function __construct(ContentModule $dataRecord, ContentController $curr = null)
    {
        $this->dataRecord = $dataRecord;
        $this->currentController = $curr;

        $this->setFailover($this->dataRecord);

        parent::__construct();
    }

    public function init()
    {
        parent::init();
    }

    public function handleRequest(SS_HTTPRequest $request, DataModel $model)
    {
        return parent::handleRequest($request, $model);
    }

    public function data()
    {
        return $this->dataRecord;
    }

    public function currController()
    {
        return $this->currentController;
    }
}

<?php

/**
 * Created by PhpStorm.
 * User: Conrad
 * Date: 24/06/2016
 * Time: 9:06 AM
 */
class ModuleController extends Controller
{
    /**
     * @var ContentModule
     */
    protected $dataRecord;

    protected $currentController;

    public function __construct(ContentModule $dataRecord, ContentController $curr = null)
    {
        $this->dataRecord = $dataRecord;
        $this->currentController = $curr;

        $this->setFailover($this->dataRecord);

        parent::__construct();
    }

    public function init()
    {
        parent::init();
    }

    public function handleRequest(SS_HTTPRequest $request, DataModel $model)
    {
        return parent::handleRequest($request, $model);
    }

    public function data()
    {
        return $this->dataRecord;
    }

    public function currController()
    {
        return $this->currentController;
    }

    /**
     * Overwrite the link function from the Controller
     *
     * @param null $action
     * @return mixed
     */
    public function Link($action = null)
    {
        return $this->data()->Link($action);
    }
}

Fix Link function coming from controller, not module


<?php
/*
 * Copyright 2010 by DracoBlue.net, licensed under the terms of MIT
 */

/**
 * PhpDebugToolbarLoggerAppender logs all log messages to the PhpDebugToolbar.
 */
class PhpDebugToolbarLoggerAppender extends AgaviLoggerAppender
{
	public function write($message)
	{
		if(($layout = $this->getLayout()) === null) {
			throw new AgaviLoggingException('No Layout set');
		}

		$str = $this->getLayout()->format($message);
        $bt = debug_backtrace();
        if (AgaviLogger::ERROR >= $message->getLevel()) {
            PhpDebugToolbar::log('error', $str, $bt[2]);
        } else if (AgaviLogger::WARN >= $message->getLevel()) {
            PhpDebugToolbar::log('warning', $str, $bt[2]);
        } else {
            PhpDebugToolbar::log('debug', $str, $bt[2]);
        }
	}

	public function shutdown()
    {
    }
}

<?php
/*
 * Copyright 2010 by DracoBlue.net, licensed under the terms of MIT
 */

/**
 * PhpDebugToolbarLoggerAppender logs all log messages to the PhpDebugToolbar.
 */
class PhpDebugToolbarLoggerAppender extends AgaviLoggerAppender
{
    public function write(AgaviLoggerMessage $message)
    {
        if(($layout = $this->getLayout()) === null) {
            throw new AgaviLoggingException('No Layout set');
        }

        $str = $this->getLayout()->format($message);
        $bt = debug_backtrace();
        if (AgaviLogger::ERROR >= $message->getLevel()) {
            PhpDebugToolbar::log('error', $str, $bt[2]);
        } else if (AgaviLogger::WARN >= $message->getLevel()) {
            PhpDebugToolbar::log('warning', $str, $bt[2]);
        } else {
            PhpDebugToolbar::log('debug', $str, $bt[2]);
        }
    }

    public function shutdown()
    {
    }
}

Add type hint for $message & fix mixed indenting.


<?php

namespace InfyOm\RoutesExplorer;

use Illuminate\Support\ServiceProvider;

class RoutesExplorerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $configPath = __DIR__ . './../config/routes_explorer.php';

        $this->publishes([
            $configPath => config_path('infyom/routes_explorer.php'),
        ]);

        $migrationPath = __DIR__ . './../stubs/migration.stub';
        $fileName = date('Y_m_d_His') . '_' . 'create_api_calls_count_table.php';

        $this->publishes([
            $migrationPath => database_path('migrations/' . $fileName),
        ], 'migrations');

        $viewPath = __DIR__ . './../views/routes.blade.php';

        $this->publishes([
            $viewPath => resource_path('views/routes/routes.blade.php'),
        ], 'views');

        $this->loadViewsFrom(__DIR__ . './../views', 'infyomlabs');

        if (config('infyom.routes_explorer.enable_explorer')) {
            $this->app['router']->get(
                config('infyom.routes_explorer.route'),
                "\\InfyOm\\RoutesExplorer\\RoutesExplorer@showRoutes"
            );
        }
    }

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

<?php

namespace InfyOm\RoutesExplorer;

use Illuminate\Support\ServiceProvider;

class RoutesExplorerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $configPath = __DIR__ . '/../config/routes_explorer.php';

        $this->publishes([
            $configPath => config_path('infyom/routes_explorer.php'),
        ]);

        $migrationPath = __DIR__ . '/../stubs/migration.stub';
        $fileName = date('Y_m_d_His') . '_' . 'create_api_calls_count_table.php';

        $this->publishes([
            $migrationPath => database_path('migrations/' . $fileName),
        ], 'migrations');

        $viewPath = __DIR__ . '/../views/routes.blade.php';

        $this->publishes([
            $viewPath => resource_path('views/routes/routes.blade.php'),
        ], 'views');

        $this->loadViewsFrom(__DIR__ . '/../views', 'infyomlabs');

        if (config('infyom.routes_explorer.enable_explorer')) {
            $this->app['router']->get(
                config('infyom.routes_explorer.route'),
                "\\InfyOm\\RoutesExplorer\\RoutesExplorer@showRoutes"
            );
        }
    }

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

Fix the relative path to vendor resources


<?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\Bridge\Monolog\Formatter;

use Monolog\Formatter\FormatterInterface;
use Symfony\Component\VarDumper\Cloner\VarCloner;

/**
 * @author Grégoire Pineau <lyrixx@lyrixx.info>
 */
class VarDumperFormatter implements FormatterInterface
{
    private $cloner;

    public function __construct(VarCloner $cloner = null)
    {
        $this->cloner = $cloner ?: new VarCloner();
    }

    /**
     * {@inheritdoc}
     *
     * @return mixed
     */
    public function format(array $record)
    {
        $record['context'] = $this->cloner->cloneVar($record['context']);
        $record['extra'] = $this->cloner->cloneVar($record['extra']);

        return $record;
    }

    /**
     * {@inheritdoc}
     *
     * @return mixed
     */
    public function formatBatch(array $records)
    {
        foreach ($records as $k => $record) {
            $record[$k] = $this->format($record);
        }

        return $records;
    }
}

<?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\Bridge\Monolog\Formatter;

use Monolog\Formatter\FormatterInterface;
use Symfony\Component\VarDumper\Cloner\VarCloner;

/**
 * @author Grégoire Pineau <lyrixx@lyrixx.info>
 */
class VarDumperFormatter implements FormatterInterface
{
    private $cloner;

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

    /**
     * {@inheritdoc}
     *
     * @return mixed
     */
    public function format(array $record)
    {
        $record['context'] = $this->cloner->cloneVar($record['context']);
        $record['extra'] = $this->cloner->cloneVar($record['extra']);

        return $record;
    }

    /**
     * {@inheritdoc}
     *
     * @return mixed
     */
    public function formatBatch(array $records)
    {
        foreach ($records as $k => $record) {
            $record[$k] = $this->format($record);
        }

        return $records;
    }
}

Replace easy occurences of ?: with ??

[CS] Replace easy occurences of ?: with ??


<?php
/**
 * @author Jean Silva <me@jeancsil.com>
 * @license MIT
 */
namespace Jeancsil\FlightSpy\Service\ElasticSearch;

use Elasticsearch\ClientBuilder;

final class Client
{
    /**
     * @var \Elasticsearch\Client
     */
    private static $instance;

    /**
     * To avoid the direct construction
     */
    private function __construct()
    {
    }

    /**
     * Returns ElasticSearch client object
     * @return \Elasticsearch\Client
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            $logger = ClientBuilder::defaultLogger('flightspy_elasticsearch.log');

            static::$instance = ClientBuilder::create()
                ->setRetries(2)
                ->setLogger($logger)
                ->build();
        }

        return static::$instance;
    }
}

<?php
/**
 * @author Jean Silva <me@jeancsil.com>
 * @license MIT
 */
namespace Jeancsil\FlightSpy\Service\ElasticSearch;

use Elasticsearch\ClientBuilder;

final class Client
{
    private static $ELASTICSEARCH_DEFAULT_HOST = 'elasticsearch:9200';

    /**
     * @var \Elasticsearch\Client
     */
    private static $instance;

    /**
     * To avoid the direct construction
     */
    private function __construct()
    {
    }

    /**
     * Returns ElasticSearch client object
     * @return \Elasticsearch\Client
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            $logger = ClientBuilder::defaultLogger('flightspy_elasticsearch.log');

            static::$instance = ClientBuilder::create()
                ->setHosts([static::$ELASTICSEARCH_DEFAULT_HOST])
                ->setRetries(2)
                ->setLogger($logger)
                ->build();
        }

        return static::$instance;
    }
}

Add the default ElasticSearch host for Docker container.


<?php

/**
 * Field which implements Select2 tag functionality (http://http://ivaynberg.github.io/select2/)
 *
 * By default expects select2 to be installed via composer to component/select2/
 */
class Select2TagField extends TextField {
    // this is default library install path with composer
    private static $library_path = 'components/select2/';

    private static $tag_seperator = ',';

    public function Field($properties = array()) {
        $this->addExtraClass('select2field');
        $this->setAttribute('tagseperator', static::tag_seperator());
        return parent::Field($properties);
    }

    /**
     * implode value if it is an array.
     *
     * @param mixed $value
     * @return $this|FormField
     */
    public function setValue($value) {
        parent::setValue(is_array($value) ? implode(self::tag_seperator(), $value) : $value);
        return $this;
    }

    /**
     * Set the available options.
     *
     * @param array $options
     * @return $this
     */
    public function setOptions(array $options) {
        $this->setAttribute('tags', implode(static::tag_seperator(), $options));
        return $this;
    }

    public static function tag_seperator() {
        return static::config()->tag_seperator;
    }

}

<?php

/**
 * Field which implements Select2 tag functionality (http://http://ivaynberg.github.io/select2/)
 *
 * By default expects select2 to be installed via composer to component/select2/
 */
class Select2TagField extends TextField {
    // this is default library install path with composer
    private static $library_path = 'components/select2/';

    private static $tag_seperator = ',';

    public function Field($properties = array()) {
        $this->addExtraClass('select2field');
        $this->setAttribute('tagseperator', static::tag_seperator());
        return parent::Field($properties);
    }

    /**
     * implode value if it is an array.
     *
     * @param mixed $value
     * @return $this|FormField
     */
    public function setValue($value) {
        parent::setValue(is_array($value) ? implode(self::tag_seperator(), $value) : $value);
        return $this;
    }

    /**
     * Set the available options.
     *
     * @param array|SS_Map $options
     * @return $this
     */
    public function setOptions($options) {
        if ($options instanceof SS_Map) {
            $options = $options->toArray();
        }
        $this->setAttribute('tags', implode(static::tag_seperator(), $options));
        return $this;
    }

    public static function tag_seperator() {
        return static::config()->tag_seperator;
    }

}

Allow an SS_Map to be passed to setOptions as well as an array


<?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 OAuth2ServerExamples\Entities;

use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Entities\Traits\EntityTrait;

class ScopeEntity implements ScopeEntityInterface
{
    use EntityTrait;

    public function jsonSerialize()
    {
        return $this->getIdentifier();
    }
}

<?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 OAuth2ServerExamples\Entities;

use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Entities\Traits\EntityTrait;
use League\OAuth2\Server\Entities\Traits\ScopeTrait;

class ScopeEntity implements ScopeEntityInterface
{
    use EntityTrait, ScopeTrait;
}

Change example to use scope trait

Change example to use scope trait


<?php

namespace UWDOEM\Framework\Filter;

class FilterControls {

    static public function getControl($handle, $key, $default = null) {
        return array_key_exists("$handle-$key", $_GET) ? $_GET["$handle-$key"] : $default;
    }
}

<?php

namespace UWDOEM\Framework\Filter;

class FilterControls {

    static public function controlIsSet($handle, $key) {
        return array_key_exists("$handle-$key", $_GET);
    }

    static public function getControl($handle, $key, $default = null) {
        return static::controlIsSet($handle, $key) ? $_GET["$handle-$key"] : $default;
    }
}

Add check for whether filter control is set.


<?php

namespace app\controllers;

use app\models\FlightFilterForm;
use app\models\OutdoorLogs;
use app\models\forge\Brand;
use yii\helpers\VarDumper;

class FlightController extends \yii\web\Controller
{
    public function actionIndex()
    {
        $model = new FlightFilterForm();

        // profile
        $profile = \Yii::$app->user->identity->profile;

        // get brands for respective company
        $brands = Brand::find()->where(['company_id'=>$profile->type_id])->all();

        if ($model->load(\Yii::$app->request->post())) {
            if ($model->validate()) {

                $logs = OutdoorLogs::find()
                    ->where(['brand_id'=>$model->brand])
                    ->andWhere(['between','date_time',$model->start_date,$model->end_date]);

                return $this->render('result',[
                    'logs'=>$logs
                ]);
            }
        }

        return $this->render('index', [
            'model' => $model,
            'brands'=>$brands
        ]);
    }
}

<?php

namespace app\controllers;

use app\models\FlightFilterForm;
use app\models\OutdoorLogs;
use app\models\forge\Brand;
use yii\helpers\VarDumper;

class FlightController extends \yii\web\Controller
{
    public function actionIndex()
    {
        $model = new FlightFilterForm();

        // profile
        $profile = \Yii::$app->user->identity->profile;

        // get brands for respective company
        $brands = Brand::find()->where(['company_id'=>$profile->type_id])->all();

        if ($model->load(\Yii::$app->request->post())) {
            if ($model->validate()) {

                $logs = OutdoorLogs::find()
                    ->where(['in','brand_id',$model->brand])
                    ->andWhere(['between','date_time',$model->start_date,$model->end_date]);

                return $this->render('result',[
                    'logs'=>$logs
                ]);
            }
        }

        return $this->render('index', [
            'model' => $model,
            'brands'=>$brands
        ]);
    }
}

Fix query to WHERE In from WHERE

Fix query to WHERE In from WHERE


<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Libraries\Markdown\StyleBlock;

use InvalidArgumentException;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Block\Renderer\BlockRendererInterface;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\HtmlElement;
use League\CommonMark\Util\ConfigurationAwareInterface;
use League\CommonMark\Util\ConfigurationInterface;

class Renderer implements BlockRendererInterface, ConfigurationAwareInterface
{
    /**
     * @var string[]
     */
    private $allowedClasses;

    public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, bool $inTightList = false)
    {
        if (!$block instanceof Element) {
            throw new InvalidArgumentException('Incompatible block type: '.get_class($block));
        }

        $renderedChildren = $htmlRenderer->renderBlocks($block->children());

        if (!in_array($block->getClass(), $this->allowedClasses, true)) {
            return $renderedChildren;
        }

        $separator = $htmlRenderer->getOption('inner_separator', "\n");

        return new HtmlElement(
            'div',
            $block->getData('attributes', []),
            $separator.$renderedChildren.$separator,
        );
    }

    public function setConfiguration(ConfigurationInterface $configuration): void
    {
        $this->allowedClasses = $configuration->get('style_block_allowed_classes', []);
    }
}

<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Libraries\Markdown\StyleBlock;

use Ds\Set;
use InvalidArgumentException;
use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Block\Renderer\BlockRendererInterface;
use League\CommonMark\ElementRendererInterface;
use League\CommonMark\HtmlElement;
use League\CommonMark\Util\ConfigurationAwareInterface;
use League\CommonMark\Util\ConfigurationInterface;

class Renderer implements BlockRendererInterface, ConfigurationAwareInterface
{
    /**
     * @var Set
     */
    private $allowedClasses;

    public function render(AbstractBlock $block, ElementRendererInterface $htmlRenderer, bool $inTightList = false)
    {
        if (!$block instanceof Element) {
            throw new InvalidArgumentException('Incompatible block type: '.get_class($block));
        }

        $renderedChildren = $htmlRenderer->renderBlocks($block->children());

        if (!$this->allowedClasses->contains($block->getClass())) {
            return $renderedChildren;
        }

        $separator = $htmlRenderer->getOption('inner_separator', "\n");

        return new HtmlElement(
            'div',
            $block->getData('attributes', []),
            $separator.$renderedChildren.$separator,
        );
    }

    public function setConfiguration(ConfigurationInterface $configuration): void
    {
        $this->allowedClasses = new Set($configuration->get('style_block_allowed_classes'));
    }
}

Use Ds\Set instead of array for allowed StyleBlock classes


<?php
chdir(dirname(__DIR__));

if (php_sapi_name() === 'cli-server' && is_file( dirname(__FILE__) . $_SERVER['REQUEST_URI'])) {
    return false;
}

# setup autoloading
require 'vendor/autoload.php';

# starts the session, required for flash messages
session_start();

# load configs
$config = array_replace_recursive(require 'config-defaults.php', file_exists('config.php') ? require 'config.php' : array());

# wireup dependencies
$injector = new Auryn\Provider();
$injector->define('Ed\Model', array(':config' => $config));
$injector->define('PDO', array(':dsn' => $config['db']['dsn'], ':username' => $config['db']['username'], ':password' => $config['db']['password']));

# initialize locale
# note: will not work on builtin server
putenv('LC_ALL=' . $config['ui']['locale']);
setlocale(LC_ALL, $config['ui']['locale']);
bindtextdomain('messages', 'locales');
textdomain('messages');

# handle request
\Http\Resource::handle($config['resources'], array($injector, 'make'));

<?php
chdir(dirname(__DIR__));

if (php_sapi_name() === 'cli-server' && is_file( dirname(__FILE__) . $_SERVER['REQUEST_URI'])) {
    return false;
}

# setup autoloading
require 'vendor/autoload.php';

# starts the session, required for flash messages
session_start();

# load configs
$config = array_replace_recursive(require 'config-defaults.php', file_exists('config.php') ? require 'config.php' : array());

# wireup dependencies
$injector = new Auryn\Provider();
$injector->define('Ed\Model', array(':config' => $config));
$injector->define('PDO', array(':dsn' => $config['db']['dsn'], ':username' => $config['db']['username'], ':passwd' => $config['db']['password']));

# initialize locale
# note: will not work on builtin server
putenv('LC_ALL=' . $config['ui']['locale']);
setlocale(LC_ALL, $config['ui']['locale']);
bindtextdomain('messages', 'locales');
textdomain('messages');

# handle request
\Http\Resource::handle($config['resources'], array($injector, 'make'));

Fix PDO password param definition

Fix PDO password param definition


<?php

namespace Risan\OAuth1\Request;

interface RequestBuilderInterface
{
    /**
     * Get the ConfigInterface instance.
     *
     * @return \Risan\OAuth1\ConfigInterface
     */
    public function getConfig();

    /**
     * Get the SignerInterface instance.
     *
     * @return \Risan\OAuth1\Signature\SignerInterface
     */
    public function getSigner();

    /**
     * Get the NonceGeneratorInterface instance.
     *
     * @return \Risan\OAuth1\Request\NonceGeneratorInterface
     */
    public function getNonceGenerator();

    /**
     * Get current timestamp in seconds since Unix Epoch.
     *
     * @return int
     */
    public function getCurrentTimestamp();

    /**
     * Get url for obtaining temporary credentials.
     *
     * @return string
     */
    public function getTemporaryCredentialsUrl();

    /**
     * Get authorization header for obtaining temporary credentials.
     *
     * @return string
     */
    public function getTemporaryCredentialsAuthorizationHeader();
}

<?php

namespace Risan\OAuth1\Request;

interface RequestBuilderInterface
{
    /**
     * Get the ConfigInterface instance.
     *
     * @return \Risan\OAuth1\ConfigInterface
     */
    public function getConfig();

    /**
     * Get the SignerInterface instance.
     *
     * @return \Risan\OAuth1\Signature\SignerInterface
     */
    public function getSigner();

    /**
     * Get the NonceGeneratorInterface instance.
     *
     * @return \Risan\OAuth1\Request\NonceGeneratorInterface
     */
    public function getNonceGenerator();

    /**
     * Get current timestamp in seconds since Unix Epoch.
     *
     * @return int
     */
    public function getCurrentTimestamp();

    /**
     * Get base protocol parameters for the authorization header.
     *
     * @return array
     */
    public function getBaseProtocolParameters();

    /**
     * Add signature parameter to the given protocol parameters.
     *
     * @param array  &$parameters
     * @param string $uri
     * @param string $httpMethod
     */
    public function addSignatureParameter(array &$parameters, $uri, $httpMethod = 'POST');

    /**
     * Normalize protocol parameters to be used as authorization header.
     *
     * @param  array  $parameters
     * @return string
     */
    public function normalizeProtocolParameters(array $parameters);
}

Update the request builder interface.

:hammer: Update the request builder interface.


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\TaxBundle\Tests\Manager;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;

/**
 * Class TaxManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class TaxManagerTest extends AbstractManagerTestCase
{
    protected function get()
    {
        return $this->container->get('tax.manager');
    }
}

<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\TaxBundle\Tests\Manager;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;
use WellCommerce\Bundle\DoctrineBundle\Manager\ManagerInterface;

/**
 * Class TaxManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class TaxManagerTest extends AbstractManagerTestCase
{
    protected function get() : ManagerInterface
    {
        return $this->container->get('tax.manager');
    }
}

Return types in manager tests

Return types in manager tests


<?php

//
// Вспомогательные функции
//

/**
 * Функция для получения конфигурационных параметров из файла
 * @param  string $param Параметр в виде раздел.параметр
 * @return mixed
 */
function config($param) {
  assert('is_string($param)');
  static $config = [];

  // Создаем специальный массив для доступа к элементам через namespace.param
  if (!$config) {
    foreach (parse_ini_file(getenv('CONFIG_DIR') . '/config.ini', true) as $key => $item) {
      $config[$key] = $item;
      foreach ($item as $key2 => $item2) {
        $config[$key . '.' . $key2] = $item2;
      }
    }
  }
  return $config[$param];
}

<?php

//
// Вспомогательные функции
//

/**
 * Функция для получения конфигурационных параметров из файла
 * @param  string $param Параметр в виде раздел.параметр
 * @return mixed
 */
function config($param) {
  assert('is_string($param)');
  static $config = [];

  // Создаем специальный массив для доступа к элементам через namespace.param
  if (!$config) {
    foreach (parse_ini_file(getenv('CONFIG_DIR') . '/config.ini', true) as $key => $item) {
      if (false !== strpos($key, ':') && split(':', $key)[1] === getenv('PROJECT_ENV')) {
        $origin = strtok($key, ':');
        $config[$origin] = array_merge($config[$origin], $item);
        $key = $origin;
      } else {
        $config[$key] = $item;
      }
      foreach ($config[$key] as $key2 => $item2) {
        $config[$key . '.' . $key2] = $item2;
      }
    }
  }
  return $config[$param];
}

Fix config function for multi environment support


<?php

	Class DateTimeObj{

		public static function setDefaultTimezone($timezone){
			if(!@date_default_timezone_set($timezone)) trigger_error(E_USER_WARNING, "Invalid timezone '{$timezone}'");
		}

		public static function getGMT($format, $timestamp=NULL){
			return self::get($format, $timestamp, 'GMT');
		}

		public static function getTimeAgo($format){
			return '<abbr class="timeago" title="'.self::get('r').'">'.self::get($format).'</abbr>';
		}

		public static function get($format, $timestamp=NULL, $timezone=NULL){
			if(!$timestamp || $timestamp == 'now') $timestamp = time();
			if(!$timezone) $timezone = date_default_timezone_get();

			$current_timezone = date_default_timezone_get();
			if($current_timezone != $timezone) self::setDefaultTimezone($timezone);

			$ret = date($format, $timestamp);

			if($current_timezone != $timezone) self::setDefaultTimezone($current_timezone);

			return $ret;

		}

	}

<?php

	Class DateTimeObj{

		public static function setDefaultTimezone($timezone){
			if(!@date_default_timezone_set($timezone)) trigger_error("Invalid timezone '{$timezone}'", E_USER_WARNING);
		}

		public static function getGMT($format, $timestamp=NULL){
			return self::get($format, $timestamp, 'GMT');
		}

		public static function getTimeAgo($format){
			return '<abbr class="timeago" title="'.self::get('r').'">'.self::get($format).'</abbr>';
		}

		public static function get($format, $timestamp=NULL, $timezone=NULL){
			if(!$timestamp || $timestamp == 'now') $timestamp = time();
			if(!$timezone) $timezone = date_default_timezone_get();

			$current_timezone = date_default_timezone_get();
			if($current_timezone != $timezone) self::setDefaultTimezone($timezone);

			$ret = date($format, $timestamp);

			if($current_timezone != $timezone) self::setDefaultTimezone($current_timezone);

			return $ret;

		}

	}

Swap the arguments being passed to trigger_error().

Fixes issue #247
http://symphony-cms.com/discuss/issues/view/247/


<?php

namespace Bundle\TimeBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;

class TimeBundle extends BaseBundle
{
}

<?php

namespace Bundle\TimeBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;

class TimeBundle extends BaseBundle
{
    public function getNamespace()
    {
        return __NAMESPACE__;
    }

    public function getPath()
    {
        return __DIR__;
    }
}

Implement two new bundle interface methods


<?php

namespace Oro\Bundle\DistributionBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $treeBuilder->root('oro_distribution')
            ->children()
                ->scalarNode('entry_point')
                    ->beforeNormalization()
                        ->ifNull()
                        ->then(
                            function () {
                                return '/install.php';
                            }
                        )
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

<?php

namespace Oro\Bundle\DistributionBundle\DependencyInjection;

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

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $treeBuilder->root('oro_distribution')
            ->children()
                ->scalarNode('entry_point')
                    ->beforeNormalization()
                        ->ifNull()
                        ->then(
                            function () {
                                return 'install.php';
                            }
                        )
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

BAP-3835: Package Manager does not take in account root folder


<?php

final class PhutilRemarkupDefaultBlockRule extends PhutilRemarkupBlockRule {

  public function getPriority() {
    return 750;
  }

  public function getMatchingLineCount(array $lines, $cursor) {
    return 1;
  }

  public function markupText($text, $children) {
    $text = trim($text);
    $text = $this->applyRules($text);

    if ($this->getEngine()->isTextMode()) {
      if (!$this->getEngine()->getConfig('preserve-linebreaks')) {
        $text = preg_replace('/ *\n */', ' ', $text);
      }
      return $text;
    }

    if ($this->getEngine()->getConfig('preserve-linebreaks')) {
      $text = phutil_escape_html_newlines($text);
    }

    if (!strlen($text)) {
      return null;
    }

    return phutil_tag('p', array(), $text);
  }

}

<?php

final class PhutilRemarkupDefaultBlockRule extends PhutilRemarkupBlockRule {

  public function getPriority() {
    return 750;
  }

  public function getMatchingLineCount(array $lines, $cursor) {
    return 1;
  }

  public function markupText($text, $children) {
    $engine = $this->getEngine();

    $text = trim($text);
    $text = $this->applyRules($text);

    if ($engine->isTextMode()) {
      if (!$this->getEngine()->getConfig('preserve-linebreaks')) {
        $text = preg_replace('/ *\n */', ' ', $text);
      }
      return $text;
    }

    if ($engine->getConfig('preserve-linebreaks')) {
      $text = phutil_escape_html_newlines($text);
    }

    if (!strlen($text)) {
      return null;
    }

    $default_attributes = $engine->getConfig('default.p.attributes');
    if ($default_attributes) {
      $attributes = $default_attributes;
    } else {
      $attributes = array();
    }

    return phutil_tag('p', $attributes, $text);
  }

}

Allow the default Remarkup <p> tag to be inline-styled for mail

Summary: Ref T10694. Browsers / mail clients have default `<p>` rules, particularly margin/padding. This allows the inline stuff to turn them off with explicit `"padding: 0; margin: 0;"` so it can control spacing more precisely.

Test Plan: See D15857.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T10694

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


<?php

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

class CreateUserDataTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        Schema::create('user_data', function (Blueprint $table)
        {
            $table->increments('id');
            $table->string('burner_name')->nullable();
            $table->string('real_name')->nullable();
            $table->string('address')->unique();
            $table->string('phone')->unique();
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

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

<?php

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

class CreateUserDataTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        Schema::create('user_data', function (Blueprint $table)
        {
            $table->increments('id');
            $table->string('burner_name')->nullable();
            $table->string('real_name')->nullable();
            $table->string('address');
            $table->string('phone');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

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

Update the userdata migration for address and phone

The user address and phone number do not need to be unique. This fixes
an issue where the data is null. It is also possible for applicants
to be at the same address and phone.

Signed-off-by: Marc Jones <bb1304e98184a66f7e15848bfbd0ff1c09583089@gmail.com>