<?php

namespace Illuminate\Foundation\Providers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\AggregateServiceProvider;

class FoundationServiceProvider extends AggregateServiceProvider
{
    /**
     * The provider class names.
     *
     * @var array
     */
    protected $providers = [
        FormRequestServiceProvider::class,
    ];

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        parent::register();

        $this->registerRequestValidation();
        $this->registerRequestSignatureValidation();
    }

    /**
     * Register the "validate" macro on the request.
     *
     * @return void
     */
    public function registerRequestValidation()
    {
        Request::macro('validate', function (array $rules, ...$params) {
            return validator()->validate($this->all(), $rules, ...$params);
        });
    }

    /**
     * Register the "hasValidSignature" macro on the request.
     *
     * @return void
     */
    public function registerRequestSignatureValidation()
    {
        Request::macro('hasValidSignature', function ($absolute = true) {
            return URL::hasValidSignature($this, $absolute);
        });
    }
}

<?php

namespace Illuminate\Foundation\Providers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\AggregateServiceProvider;

class FoundationServiceProvider extends AggregateServiceProvider
{
    /**
     * The provider class names.
     *
     * @var array
     */
    protected $providers = [
        FormRequestServiceProvider::class,
    ];

    /**
     * Boot the service provider.
     */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__.'/../Exceptions/views' => $this->app->resourcePath('views/errors/'),
            ], 'laravel-errors');
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        parent::register();

        $this->registerRequestValidation();
        $this->registerRequestSignatureValidation();
    }

    /**
     * Register the "validate" macro on the request.
     *
     * @return void
     */
    public function registerRequestValidation()
    {
        Request::macro('validate', function (array $rules, ...$params) {
            return validator()->validate($this->all(), $rules, ...$params);
        });
    }

    /**
     * Register the "hasValidSignature" macro on the request.
     *
     * @return void
     */
    public function registerRequestSignatureValidation()
    {
        Request::macro('hasValidSignature', function ($absolute = true) {
            return URL::hasValidSignature($this, $absolute);
        });
    }
}

Add ability to publish error views

Add ability to publish error views


<?php

namespace wcatron\CommonDBFramework;

abstract class DB {
    /**
     * @var array Contains configuration data dependant on parent database type.
     */
    private $config;
    /**
     * @return string
     */
    private static $instance;
    /**
     * Gets the singleton instance of the DB. Used throughout the framework.
     * @return static Returns the singlton DB object.
     */
    public static function getInstance($connect = true) {
        if (null === static::$instance) {
            static::$instance = new static();
        }
        if ($connect) {
            static::$instance->connect();
        }
        return static::$instance;
    }

    public static function configure($config) {
        static::getInstance(false)->config = $config;
    }

    function connect() {
    }

}

?>

<?php

namespace wcatron\CommonDBFramework;

abstract class DB {
    /**
     * @var array Contains configuration data dependant on parent database type.
     */
    protected $config;
    /**
     * @return string
     */
    private static $instance;
    /**
     * Gets the singleton instance of the DB. Used throughout the framework.
     * @return static Returns the singlton DB object.
     */
    public static function getInstance($connect = true) {
        if (null === static::$instance) {
            static::$instance = new static();
        }
        if ($connect) {
            static::$instance->connect();
        }
        return static::$instance;
    }

    public static function configure($config) {
        static::getInstance(false)->config = $config;
    }

    function connect() {
    }

}

?>

Make config protected so it's accessable.


<?php
require_once 'Lisphp/Runtime/Function.php';

final class Lisphp_Runtime_PHPFunction extends Lisphp_Runtime_Function {
    public $callback;

    function __construct($callback) {
        if (is_array($callback) ? !method_exists($callback[0], $callback[1])
                                : !function_exists($callback)) {
            throw new UnexpectedValueException('undefined function or method');
        }
        $this->callback = $callback;
    }

    function execute(array $arguments) {
        return call_user_func_array($this->callback, $arguments);
    }
}

<?php
require_once 'Lisphp/Runtime/Function.php';

final class Lisphp_Runtime_PHPFunction extends Lisphp_Runtime_Function {
    public $callback;

    function __construct($callback) {
        if (!is_callable($callback)) {
            throw new UnexpectedValueException('undefined function or method');
        }
        $this->callback = $callback;
    }

    function execute(array $arguments) {
        return call_user_func_array($this->callback, $arguments);
    }
}

Allow using lambdas with runtime functions

Example:

    $scope[require] = new Lisphp_Runtime_PHPFunction(function ($file) {
        require $file;
    });


<?php

/**
 * Consumes RabbitMQ messages and dumps them.
 */

namespace Graviton\MessageBundle\Service;

use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
use PhpAmqpLib\Message\AMQPMessage;

/**
 * Consumes RabbitMQ messages and dumps them.
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://swisscom.ch
 */
class DumpConsumer implements ConsumerInterface
{

    /**
     * Callback executed when a message is received. Dumps the message body, delivery_info and properties.
     *
     * @param AMQPMessage $msg The received message.
     *
     * @return void
     */
    public function execute(AMQPMessage $msg)
    {
        echo 'Message received at ' . date('c') . ': ' . $msg->body . "\n";
        echo "\t" . 'Delivery Info: ' . "\n";
        foreach ($msg->delivery_info as $key => $value) {
            if (is_scalar($value)) {
                echo "\t\t" . $key . ': ' . $value . "\n";
            }
        }
        echo "\t" . 'Properties: ' . "\n";
        foreach ($msg->get_properties() as $property => $value) {
            if (is_scalar($value)) {
                echo "\t\t" . $property . ': ' . $value . "\n";
            }
        }
    }
}

<?php

/**
 * Consumes RabbitMQ messages and dumps them.
 */

namespace Graviton\MessageBundle\Service;

use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
use PhpAmqpLib\Message\AMQPMessage;

/**
 * Consumes RabbitMQ messages and dumps them.
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://swisscom.ch
 */
class DumpConsumer implements ConsumerInterface
{

    /**
     * Callback executed when a message is received. Dumps the message body, delivery_info and properties.
     *
     * @param AMQPMessage $msg The received message.
     *
     * @return void
     */
    public function execute(AMQPMessage $msg)
    {
        echo 'Message received at ' . date('c') . ': ' . $msg->body . "\n";
        echo "\t" . 'Delivery Info: ' . "\n";
        foreach ($msg->{'delivery_info'} as $key => $value) {
            if (is_scalar($value)) {
                echo "\t\t" . $key . ': ' . $value . "\n";
            }
        }
        echo "\t" . 'Properties: ' . "\n";
        foreach ($msg->get_properties() as $property => $value) {
            if (is_scalar($value)) {
                echo "\t\t" . $property . ': ' . $value . "\n";
            }
        }
    }
}

Work around phpcs fail while unpacking $msg for debug purposes


<?php

namespace MonsieurBiz\CoffeeShop\Router;

use Thruway\Peer\Router as BaseRouter;
use Thruway\Transport\RatchetTransportProvider;

class Router extends BaseRouter
{
    public function __construct(LoopInterface $loop = null)
    {
        parent::__construct($loop);
        $this->addTransportProvider(new RatchetTransportProvider("127.0.0.1", 9090));
    }
}

<?php

namespace MonsieurBiz\CoffeeShop\Router;

use Thruway\Peer\Router as BaseRouter;
use Thruway\Transport\RatchetTransportProvider;

class Router extends BaseRouter
{
    public function __construct(LoopInterface $loop = null)
    {
        parent::__construct($loop);
        $this->addTransportProvider(new RatchetTransportProvider("0.0.0.0", 9090));
    }
}

Change IP address to listen on

[router] Change IP address to listen on


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use function count;
use PHPUnit\TestFixture\DoubleTestCase;
use PHPUnit\TestFixture\Success;

/**
 * @small
 */
final class TestImplementorTest extends TestCase
{
    public function testSuccessfulRun(): void
    {
        $result = new TestResult;

        $test = new DoubleTestCase(new Success('testOne'));
        $test->run($result);

        $this->assertCount(count($test), $result);
        $this->assertEquals(0, $result->errorCount());
        $this->assertEquals(0, $result->failureCount());
    }
}

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Framework;

use function count;
use PHPUnit\Event\Facade;
use PHPUnit\TestFixture\DoubleTestCase;
use PHPUnit\TestFixture\Success;

/**
 * @small
 */
final class TestImplementorTest extends TestCase
{
    public function testSuccessfulRun(): void
    {
        $result = new TestResult;

        $test = new DoubleTestCase(new Success('testOne'));

        Facade::suspend();
        $test->run($result);
        Facade::resume();

        $this->assertCount(count($test), $result);
        $this->assertEquals(0, $result->errorCount());
        $this->assertEquals(0, $result->failureCount());
    }
}

Disable event dispatching for this test

Disable event dispatching for this test


<?php
namespace wcf\system\form\builder\field;

/**
 * Provides default implementations of `IImmutableFormField` methods.
 *
 * @author	Matthias Schmidt
 * @copyright	2001-2018 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Form\Builder\Field
 * @since	5.2
 */
trait TImmutableFormField {
	/**
	 * `true` if the value of this field is immutable and `false` otherwise
	 * @var	bool
	 */
	protected $__immutable = false;

	/**
	 * Sets whether the value of this field is immutable and returns this field.
	 *
	 * @param	bool		$immutable	determines if field value is immutable
	 * @return	static				this field
	 */
	public function immutable($immutable = true) {
		$this->__immutable = $immutable;

		return $this;
	}

	/**
	 * Returns `true` if the value of this field is immutable and returns `false`
	 * otherwise. By default, fields are mutable.
	 *
	 * @return	bool
	 */
	public function isImmutable() {
		return $this->__immutable;
	}
}

Add missing newline at end of file

Add missing newline at end of file

See #2509
See aa6f853584182980c1c7d12891b689317e458b8b


<?php

namespace React\Filesystem\Node;

interface NodeInterface
{
    /**
     * @return string
     */
    public function __toString();
}

<?php

namespace React\Filesystem\Node;

interface NodeInterface
{
    /**
     * @return string
     */
    public function __toString();

    /**
     * @return string
     */
    public function getPath();
}

Make sure getPath is part of the interface


<?php

namespace Nimbusoft\Parrot\Plugin;

use Nimbusoft\Parrot\Parrot;
use League\Event\EventInterface;
use Nimbusoft\Parrot\Extension\AbstractPlugin;

class FilesPlugin extends AbstractPlugin
{
    public function register()
    {
        $this->parrot->listen('run', [$this, 'run'], Parrot::P_NORMAL);
    }

    public function run(EventInterface $event)
    {
        if ( ! isset($config['files'])) return;
    }
}

<?php

namespace Nimbusoft\Parrot\Plugin;

use Nimbusoft\Parrot\Parrot;
use League\Event\EventInterface;
use Nimbusoft\Parrot\Extension\AbstractPlugin;

class FilesPlugin extends AbstractPlugin
{
    public function register()
    {
        $this->parrot->listen('run', [$this, 'run'], Parrot::P_NORMAL);
    }

    public function run(EventInterface $event)
    {
        $config = $event->getConfig();

        if ( ! isset($config['files'])) return;
        if (isset($config['files']['adapter'])) $config['files'] = [$config['files']];
    }
}

Make sure files config is an array

Make sure files config is an array


<?php

namespace Butterfly\Plugin\TemplateRouter;

use Butterfly\Adapter\Twig\IRenderer;
use Butterfly\Component\DI\Container;
use Symfony\Component\HttpFoundation\Request;

/**
 * @author Marat Fakhertdinov <marat.fakhertdinov@gmail.com>
 */
class TemplateController
{
    /**
     * @var IRenderer
     */
    protected $render;

    /**
     * @var Container
     */
    protected $container;

    /**
     * @param IRenderer $render
     * @param Container $container
     */
    public function __construct(IRenderer $render, Container $container)
    {
        $this->container = $container;
        $this->render    = $render;
    }

    /**
     * @param Request $request
     * @return string
     */
    public function indexAction(Request $request)
    {
        $template = $request->attributes->get('template');

        $parameters = array(
            'container' => $this->container,
            'data'      => $this->container->getParameter('bfy_plugin.template_router.data_source'),
            'request'   => $request,
        );

        return $this->render->render($template, $parameters);
    }
}

<?php

namespace Butterfly\Plugin\TemplateRouter;

use Butterfly\Adapter\Twig\IRenderer;
use Butterfly\Component\DI\Container;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * @author Marat Fakhertdinov <marat.fakhertdinov@gmail.com>
 */
class TemplateController
{
    /**
     * @var IRenderer
     */
    protected $render;

    /**
     * @var Container
     */
    protected $container;

    /**
     * @param IRenderer $render
     * @param Container $container
     */
    public function __construct(IRenderer $render, Container $container)
    {
        $this->container = $container;
        $this->render    = $render;
    }

    /**
     * @param Request $request
     * @return string
     */
    public function indexAction(Request $request)
    {
        $template = $request->attributes->get('template');

        $parameters = array(
            'container' => $this->container,
            'data'      => $this->container->getParameter('bfy_plugin.template_router.data_source'),
            'request'   => $request,
        );

        $content = $this->render->render($template, $parameters);

        return new Response($content);
    }
}

Fix bug for template controller

Fix bug for template controller


<?php

declare(strict_types=1);

use Isolated\Symfony\Component\Finder\Finder;

// Symfony polyfills must live in global namespace.
$symfonyPolyfill = (static function (): array {
    $files = [];
    foreach (
        Finder::create()
            ->files()
            ->in(__DIR__ . '/../../vendor/symfony/polyfill-*')
            ->name('bootstrap.php') as $bootstrap
    ) {
        $files[] = $bootstrap->getPathName();
    }
    foreach (
        Finder::create()
            ->files()
            ->in(__DIR__ . '/../../vendor/symfony/polyfill-*/Resources/stubs')
            ->name('*.php') as $bootstrap
    ) {
        $files[] = $bootstrap->getPathName();
    }

    return $files;
})();

return [
    'whitelist' => [
        '\Phpcq\PluginApi\*',
        '\Symfony\Polyfill\*',
    ],
    'files-whitelist' => $symfonyPolyfill,
];

<?php

declare(strict_types=1);

use Isolated\Symfony\Component\Finder\Finder;

// Symfony polyfills must live in global namespace.
$symfonyPolyfill = (static function (): array {
    $files = [];
    foreach (
        Finder::create()
            ->files()
            ->in(__DIR__ . '/../../vendor/symfony/polyfill-*')
            ->name('bootstrap.php') as $bootstrap
    ) {
        $files[] = $bootstrap->getPathName();
    }
    foreach (
        Finder::create()
            ->files()
            ->in(__DIR__ . '/../../vendor/symfony/polyfill-*/Resources/stubs')
            ->name('*.php') as $bootstrap
    ) {
        $files[] = $bootstrap->getPathName();
    }

    return $files;
})();

return [
    'whitelist' => [
        '\Phpcq\PluginApi\*',
        '\Symfony\Polyfill\*',
    ],
    'files-whitelist' => $symfonyPolyfill,
    'patchers' => [
        static function (string $filePath, string $prefix, string $content): string {
            if ($filePath === 'vendor/phpcq/gnupg/src/GnuPGFactory.php') {
                return str_replace('use ' . $prefix . '\Gnupg;', 'use Gnupg;', $content);
            }

            return $content;
        }
    ]
];

Fix namespace of Gnupg class in generated phar


<?php
/**
 * Sandbox
 *
 * @package App.Sandbox
 */

use Helloworld\Module\AppModule;
use Ray\Di\Injector;

require_once __DIR__ . '/load.php';

$hasApc = function_exists('apc_fetch');
$app = $hasApc && apc_fetch('app-helloworld');
if ($app) {
    return $app;
}

$injector = Injector::create([new AppModule]);
$app = $injector->getInstance('BEAR\Sunday\Extension\Application\AppInterface');

$hasApc ? apc_store('app-helloworld', $app) : null;
return $app;

<?php
/**
 * Sandbox
 *
 * @package App.Sandbox
 */

use Helloworld\Module\AppModule;
use Ray\Di\Injector;

require_once __DIR__ . '/load.php';

$hasApc = function_exists('apc_fetch');
if ($hasApc) {
    $app = apc_fetch('app-helloworld');
    if ($app) {
        return $app;
    }
}

$injector = Injector::create([new AppModule]);
$app = $injector->getInstance('BEAR\Sunday\Extension\Application\AppInterface');

$hasApc ? apc_store('app-helloworld', $app) : null;
return $app;

Fix APC handling of Helloworld app.

Fix APC handling of Helloworld app.


{{--
    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.
--}}
@extends('master', ['titlePrepend' => trans('layout.header.admin.beatmapset')])

@section('content')
    @include('admin/_header')

{{ $beatmapset->title }} - {{ $beatmapset->artist }}

{{ trans('admin.beatmapsets.show.discussion._') }}:
                @if ($beatmapset->discussion_enabled)
                    {{ trans('admin.beatmapsets.show.discussion.active') }}
                @else
                    {{ trans('admin.beatmapsets.show.discussion.inactive') }}
                    /
                     $beatmapset->getKey(),
                            'beatmapset[discussion_enabled]=1'
                        ]) }}"
                        data-method="PUT"
                        data-confirm="{{ trans('admin.beatmapsets.show.discussion.activate_confirm') }}"
                    >{{ trans('admin.beatmapsets.show.discussion.activate') }}
                @endif

beatmapset_id) }}">{{ trans('admin.beatmapsets.show.covers') }}

@endsection

{{--
    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.
--}}
@extends('master', ['titlePrepend' => trans('layout.header.admin.beatmapset')])

@section('content')
    @include('admin/_header')

{{ $beatmapset->title }} - {{ $beatmapset->artist }}

{{ trans('admin.beatmapsets.show.discussion._') }}:
                @if ($beatmapset->discussion_enabled)
                    {{ trans('admin.beatmapsets.show.discussion.active') }}
                @else
                    {{ trans('admin.beatmapsets.show.discussion.inactive') }}
                    /
                    getKey(),
                            'beatmapset[discussion_enabled]' => true,
                        ]) }}"
                        data-method="PUT"
                        data-confirm="{{ trans('admin.beatmapsets.show.discussion.activate_confirm') }}"
                    >{{ trans('admin.beatmapsets.show.discussion.activate') }}
                @endif

beatmapset_id) }}">{{ trans('admin.beatmapsets.show.covers') }}

@endsection

Fix modding v2 activation link in admin view


<?php
	$id=0;
	eval ('$id='.$data['id'].';');
?>
<?php if (array_key_exists('edit', $_GET) && Session::isLoggedIn()) { ?>
<span id="Label<?= $id ?>" edit_id="<?= $id ?>" style="display:inherit;"><?=Label::ROW($id)->getText() ?>
<?php } else { ?>
<?=Label::ROW($id)->getText() ?>
<?php } ?>

<?php
	$id=0;
	eval ('$id='.$data['id'].';');

	$edit = !in_array('noedit', $flags);
?>
<?php if (array_key_exists('edit', $_GET) && Session::isLoggedIn() && $edit) { ?>
<span id="Label<?= $id ?>" edit_id="<?= $id ?>" style="display:inherit;"><?=Label::ROW($id)->getText() ?>
<?php } else { ?>
<?=Label::ROW($id)->getText() ?>
<?php } ?>

Improve component Label (add flag 'noedit')


<?php

if ( ! function_exists('basset_stylesheet'))
{
    /**
     * Ouput the stylesheets for a given collection.
     *
     * @param  string  $collection
     * @return string
     */
    function basset_stylesheet($name)
    {
        return app('basset.output')->stylesheets($name);
    }
}

if ( ! function_exists('basset_javascript'))
{
    /**
     * Ouput the javascripts for a given collection.
     *
     * @param  string  $collection
     * @return string
     */
    function basset_javascript($collection)
    {
        return app('basset.output')->javascripts($collection);
    }
}

if ( ! function_exists('array_to_newlines'))
{
    /**
     * Convert an array to a newline separated string.
     *
     * @param  array  $array
     * @return string
     */
    function array_to_newlines(array $array)
    {
        return implode(PHP_EOL, $array);
    }
}

<?php

if ( ! function_exists('basset_stylesheet'))
{
    /**
     * Ouput the stylesheets for several collections.
     *
     * @return string
     */
    function basset_stylesheet()
    {
        return basset_collections(func_get_args(), 'stylesheets');
    }
}

if ( ! function_exists('basset_javascript'))
{
    /**
     * Ouput the javascripts for several collections.
     *
     * @return string
     */
    function basset_javascript()
    {
        return basset_collections(func_get_args(), 'javascripts');
    }
}

if ( ! function_exists('basset_collections'))
{
    /**
     * Output a given group for an array of collections.
     *
     * @param  array  $collections
     * @param  string  $group
     * @return string
     */
    function basset_collections(array $collections, $group)
    {
        $responses = array();

        foreach ($collections as $collection)
        {
            $responses[] = app('basset.output')->$group($name);
        }

        return array_to_newlines($responses);
    }
}

if ( ! function_exists('array_to_newlines'))
{
    /**
     * Convert an array to a newline separated string.
     *
     * @param  array  $array
     * @return string
     */
    function array_to_newlines(array $array)
    {
        return implode(PHP_EOL, $array);
    }
}

Allow multiple collections to be outputted in views.

Signed-off-by: Jason Lewis <b136be6b8ecc2c62ceb9857ec62bf85489a45e0c@gmail.com>


<?php
class Synology_DSM_Api extends Synology_Api_Authenticate{
	const API_SERVICE_NAME = 'DSM';
	const API_NAMESPACE = 'SYNO';

	/**
	 * Info API setup
	 *
	 * @param string $address
	 * @param int $port
	 * @param string $protocol
	 * @param int $version
	 */
	public function __construct($address, $port = null, $protocol = null, $version = 1){
		parent::__construct(self::API_SERVICE_NAME, self::API_NAMESPACE, $address, $port, $protocol, $version);
	}

	/**
	 * Return Information about DSM
	 * - is_manager
	 * - version
	 * - version_string
	 */
	public function getInfo(){
		return $this->_request('Info', 'DSM/info.cgi', 'getinfo');
	}
}

<?php
class Synology_DSM_Api extends Synology_Api_Authenticate{
	const API_SERVICE_NAME = 'API';
	const API_NAMESPACE = 'SYNO';

	/**
	 * Info API setup
	 *
	 * @param string $address
	 * @param int $port
	 * @param string $protocol
	 * @param int $version
	 */
	public function __construct($address, $port = null, $protocol = null, $version = 1){
		parent::__construct(self::API_SERVICE_NAME, self::API_NAMESPACE, $address, $port, $protocol, $version);
	}

	/**
	 * Return Information about DSM
	 * - is_manager
	 * - version
	 * - version_string
	 */
	public function getInfo(){
		return $this->_request('Info', 'query.cgi', 'query');
	}
}

Update API path for Syno.API.Info

Update API path for Syno.API.Info


<?php

namespace {
    require __DIR__.'/../vendor/autoload.php';
}

namespace PHPUnit\Framework
{
    // compatibility for when these tests are run with PHPUnit<6.0 (which we
    // still do because PHPUnit=6.0 stopped supporting a lot of PHP versions)
    if (!class_exists('PHPUnit\Framework\TestCase')) {
        abstract class TestCase extends \PHPUnit_Framework_TestCase
        {
        }
    }
}

<?php

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

Remove no longer useful test compat help


<?php namespace Flarum\Events;

use Flarum\Support\ClientAction;
use Flarum\Support\ClientView;
use Flarum\Forum\Actions\ClientAction as ForumClientAction;

class BuildClientView
{
    /**
     * @var ClientAction
     */
    public $action;

    /**
     * @var ClientView
     */
    public $view;

    /**
     * @var array
     */
    public $keys;

    /**
     * @param ClientAction $action
     * @param ClientView $view
     * @param array $keys
     */
    public function __construct($action, $view, &$keys)
    {
        $this->action = $action;
        $this->view = $view;
        $this->keys = &$keys;
    }

    public function forumAssets($files)
    {
        if ($this->action instanceof ForumClientAction) {
            $this->view->getAssets()->addFiles((array) $files);
        }
    }

    public function forumBootstrapper($bootstrapper)
    {
        if ($this->action instanceof ForumClientAction) {
            $this->view->addBootstrapper($bootstrapper);
        }
    }

    public function forumTranslations(array $keys)
    {
        if ($this->action instanceof ForumClientAction) {
            foreach ($keys as $key) {
                $this->keys[] = $key;
            }
        }
    }}

<?php namespace Flarum\Events;

use Flarum\Support\ClientAction;
use Flarum\Support\ClientView;
use Flarum\Forum\Actions\ClientAction as ForumClientAction;
use Flarum\Admin\Actions\ClientAction as AdminClientAction;

class BuildClientView
{
    /**
     * @var ClientAction
     */
    public $action;

    /**
     * @var ClientView
     */
    public $view;

    /**
     * @var array
     */
    public $keys;

    /**
     * @param ClientAction $action
     * @param ClientView $view
     * @param array $keys
     */
    public function __construct($action, $view, &$keys)
    {
        $this->action = $action;
        $this->view = $view;
        $this->keys = &$keys;
    }

    public function forumAssets($files)
    {
        if ($this->action instanceof ForumClientAction) {
            $this->view->getAssets()->addFiles((array) $files);
        }
    }

    public function forumBootstrapper($bootstrapper)
    {
        if ($this->action instanceof ForumClientAction) {
            $this->view->addBootstrapper($bootstrapper);
        }
    }

    public function forumTranslations(array $keys)
    {
        if ($this->action instanceof ForumClientAction) {
            foreach ($keys as $key) {
                $this->keys[] = $key;
            }
        }
    }

    public function adminAssets($files)
    {
        if ($this->action instanceof AdminClientAction) {
            $this->view->getAssets()->addFiles((array) $files);
        }
    }

    public function adminBootstrapper($bootstrapper)
    {
        if ($this->action instanceof AdminClientAction) {
            $this->view->addBootstrapper($bootstrapper);
        }
    }
}

Allow for the addition of admin assets

Allow for the addition of admin assets

I think the `BuildClientView` event should ultimately be split into two
separate events for the forum/admin clients, but this is fine for now.


<?php

namespace Cascade\Tests\Exceptions;

use Cascade\Exceptions\ExceptionWithContext;

class ExceptionWithContextTest extends \PHPUnit_Framework_TestCase
{
    public function testItShouldPassThroughStandardDataToTheBaseExceptionClass()
    {
        $previousException = new \Exception('previousMessage');

        $exception = new ExceptionWithContext('message', [], 42, $previousException);

        $this->assertEquals('message', $exception->getMessage());
        $this->assertEquals(42, $exception->getCode());
        $this->assertSame($previousException, $exception->getPrevious());
    }

    public function testItShouldAllowTheContextToBeRetrieved()
    {
        $context = new \stdClass();

        $exception = new ExceptionWithContext('message', $context);

        $this->assertSame($context, $exception->getContext());
    }
}

Clean up some extra spacing

Clean up some extra spacing


<?php
namespace CodeDay\Clear\Services;

use CodeDay\Clear\Models\Batch\Event;
use CodeDay\Clear\Models\Batch\Event\Registration;

class Notifications {
  public static function SendNotificationsForAnnouncement($announcement) {
    \Queue::push(function($job) use ($announcement) {
      $event = $announcement->event;
      $registrations = $event->registrations;

      foreach($registrations as $registration) {
        $devices = $registration->devices;

        foreach($devices as $device) {
          switch($device->service) {
            case "messenger":
              FacebookMessenger::SendMessage("An announcement from the CodeDay organizers:\n\n" . $announcement->body, $device->token);
              break;
            case "sms":
              Telephony\Sms::send($device->token, "CodeDay Announcement: " . $announcement->body);
              break;
            case "app":
              // TODO companion implementation
              break;
          }
        }
      }

      $job->delete();
    });
  }
}

<?php
namespace CodeDay\Clear\Services;

use CodeDay\Clear\Models\Batch\Event;
use CodeDay\Clear\Models\Batch\Event\Registration;

class Notifications {
  public static function SendNotificationsForAnnouncement($announcement) {
    $event = $announcement->event;
    $registrations = $event->registrations;

    foreach($registrations as $registration) {
      $devices = $registration->devices;

      foreach($devices as $device) {
        switch($device->service) {
          case "messenger":
            FacebookMessenger::SendMessage("An announcement from the CodeDay organizers:\n\n" . $announcement->body, $device->token);
            break;
          case "sms":
            Telephony\Sms::send($device->token, "CodeDay Announcement: " . $announcement->body);
            break;
          case "app":
            // TODO companion implementation
            break;
        }
      }
    }

    $job->delete();
  }
}

Revert to queueing things one-by-one

Revert to queueing things one-by-one


<?php namespace Prologue\Support\Collection;

use Illuminate\Support\Collection as BaseCollection;

class Collection extends BaseCollection {

	/**
	 * Take the first {$limit} items.
	 *
	 * @param  int  $limit
	 * @return \Prologue\Support\Collection
	 */
	public function take($limit)
	{
		return $this->slice(0, $limit);
	}

	/**
	 * Take the last {$limit} items.
	 *
	 * @param  int  $limit
	 * @return \Prologue\Support\Collection
	 */
	public function takeLast($limit)
	{
		return $this->slice(-$limit, $limit);
	}

	/**
	 * Tries to filter items by a key/value pair.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return \Prologue\Support\Collection
	 */
	public function filterBy($key, $value)
	{
		return $this->filter(function($item) use ($key, $value)
		{
			$itemValue = is_object($item) ? $item->{$key} : $item[$key];

			return $itemValue == $value;
		});
	}

	/**
	 * Orders items by a key.
	 *
	 * @param  string  $key
	 * @return \Prologue\Support\Collection
	 */
	public function orderBy($key)
	{
		return $this->sort(function($a, $b) use ($key)
		{
			$valueA = is_object($a) ? $a->{$key} : $a[$key];
			$valueB = is_object($b) ? $b->{$key} : $b[$key];

			if ($valueA == $valueB) return 0;

			return ($valueA < $valueB) ? 1 : -1;
		});
	}

}

<?php namespace Prologue\Support\Collection;

use Illuminate\Support\Collection as BaseCollection;

class Collection extends BaseCollection {

	/**
	 * Tries to filter items by a key/value pair.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return \Prologue\Support\Collection
	 */
	public function filterBy($key, $value)
	{
		return $this->filter(function($item) use ($key, $value)
		{
			$itemValue = is_object($item) ? $item->{$key} : $item[$key];

			return $itemValue == $value;
		});
	}

	/**
	 * Orders items by a key.
	 *
	 * @param  string  $key
	 * @return \Prologue\Support\Collection
	 */
	public function orderBy($key)
	{
		return $this->sort(function($a, $b) use ($key)
		{
			$valueA = is_object($a) ? $a->{$key} : $a[$key];
			$valueB = is_object($b) ? $b->{$key} : $b[$key];

			if ($valueA == $valueB) return 0;

			return ($valueA < $valueB) ? 1 : -1;
		});
	}

}

Remove take method. Merged to Illuminate\Support

Signed-off-by: Dries Vints <9818b0f8e34f57ac0059d0bc440479771e319166@gmail.com>


<?php

/**
 * This file is part of the Hayttp package.
 *
 * @package Hayttp
 * @author Kim Ravn Hansen <moccalotto@gmail.com>
 * @copyright 2016
 * @license MIT
 */

namespace Moccalotto\Hayttp\Contracts;

interface Payload
{
    /**
     * Render the body of the payload.
     *
     * @return string
     */
    public function __toString() : string;

    /**
     * The Content-Type header to use when sending this payload.
     *
     * @return string
     */
    public function contentType() : string;

    /**
     * Array of headers to add to the request upon sending.
     *
     * @return string[]
     */
    public function addedHeaders() : array;

    /**
     * Add these strings to the path.
     *
     * @return string[]
     */
    public function addedPath() : array;

    /**
     * Add these args to the query string.
     *
     * @return array Associative array of args to add.
     */
    public function addedQueryArgs() : array;
}

<?php

/**
 * This file is part of the Hayttp package.
 *
 * @package Hayttp
 * @author Kim Ravn Hansen <moccalotto@gmail.com>
 * @copyright 2016
 * @license MIT
 */

namespace Moccalotto\Hayttp\Contracts;

interface Payload
{
    /**
     * Render the body of the payload.
     *
     * @return string
     */
    public function __toString() : string;

    /**
     * The Content-Type header to use when sending this payload.
     *
     * @return string
     */
    public function contentType() : string;
}

Remove requirements for unused code.

Remove requirements for unused code.


<?php namespace GameScan\Core\Exceptions;

class Base extends \Exception
{
    protected $logException = true;

    public function __construct($message = "", $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
        if($this->logException){
            \GameScan\Core\Tools\LoggerFactory::getLogger()->error("Exception thrown : " . $this);
        }
    }
}

<?php namespace GameScan\Core\Exceptions;

class Base extends \Exception
{
    protected $logException = true;

    public function __construct($message = "", $code = 0, \Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
        if($this->logException){
            \GameScan\Core\Tools\LoggerFactory::getLogger()->error("Exception thrown : " . $this);
        }
    }
}

Use namespace so we avoid ambiguous class name


<?php

/*
 +--------------------------------------------------------------------------+
 | Zephir                                                                   |
 | Copyright (c) 2013-present Zephir Team (https://zephir-lang.com/)        |
 |                                                                          |
 | This source file is subject the MIT license, that is bundled with this   |
 | package in the file LICENSE, and is available through the world-wide-web |
 | at the following url: http://zephir-lang.com/license.html                |
 +--------------------------------------------------------------------------+
*/

namespace Extension\Oo\Scope;

use PHPUnit\Framework\TestCase;
use Test\Oo\Scopes\PrivateScopeTester;

class PrivateScopeTest extends TestCase
{
    /** @test */
    public function shouldCallPrivateMethod()
    {
        $this->assertSame('isPrivate', (new PrivateScopeTester())->run());
    }
}

<?php

/*
 +--------------------------------------------------------------------------+
 | Zephir                                                                   |
 | Copyright (c) 2013-present Zephir Team (https://zephir-lang.com/)        |
 |                                                                          |
 | This source file is subject the MIT license, that is bundled with this   |
 | package in the file LICENSE, and is available through the world-wide-web |
 | at the following url: http://zephir-lang.com/license.html                |
 +--------------------------------------------------------------------------+
*/

namespace Extension\Oo\Scope;

use PHPUnit\Framework\TestCase;
use Test\Oo\Scopes\PrivateScopeTester;

class PrivateScopeTest extends TestCase
{
    /** @test */
    public function shouldCallPrivateMethod()
    {
        if (PHP_VERSION_ID < 50600) {
            $this->markTestSkipped(
                "Calling parent's private methods from the child's public ones doesn't provided for PHP < 5.6"
            );
        }

        $this->assertSame('isPrivate', (new PrivateScopeTester())->run());
    }
}

Correct tests for PHP < 5.6

Correct tests for PHP < 5.6


<?php

namespace Northstar\Http\Transformers;

use Northstar\Models\User;
use League\Fractal\TransformerAbstract;

class UserInfoTransformer extends TransformerAbstract
{
    /**
     * @param User $user
     * @return array
     */
    public function transform(User $user)
    {
        // User data, formatted according to OpenID Connect spec, section 5.3.
        // @see http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
        $response = [
            'id' => $user->_id,
            'given_name' => $user->first_name,
            'family_name' => $user->last_name,
            'email' => $user->email,
            'phone_number' => $user->mobile,
            'birthdate' => format_date($user->birthdate, 'Y-m-d'),

            'address' => [
                'street_address' => implode(PHP_EOL, [$user->addr_street1, $user->addr_street2]),
                'locality' => $user->addr_city,
                'region' => $user->addr_state,
                'postal_code' => $user->addr_zip,
                'country' => $user->country,
            ],

            'updated_at' => $user->updated_at->timestamp,
            'created_at' => $user->created_at->timestamp,
        ];

        return $response;
    }
}

<?php

namespace Northstar\Http\Transformers;

use Northstar\Models\User;
use League\Fractal\TransformerAbstract;

class UserInfoTransformer extends TransformerAbstract
{
    /**
     * @param User $user
     * @return array
     */
    public function transform(User $user)
    {
        // User data, formatted according to OpenID Connect spec, section 5.3.
        // @see http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
        $response = [
            'id' => $user->_id,
            'given_name' => $user->first_name,
            'family_name' => $user->last_name,
            'email' => $user->email,
            'phone_number' => $user->mobile,
            'birthdate' => format_date($user->birthdate, 'Y-m-d'),

            'address' => [
                'street_address' => implode(PHP_EOL, [$user->addr_street1, $user->addr_street2]),
                'locality' => $user->addr_city,
                'region' => $user->addr_state,
                'postal_code' => $user->addr_zip,
                'country' => strlen($user->country) === 2 ? $user->country : null,
            ],

            'updated_at' => $user->updated_at->timestamp,
            'created_at' => $user->created_at->timestamp,
        ];

        return $response;
    }
}

Make sure country userinfo response is valid.


<?php

namespace Octo\System\Admin\Controller;

use b8\Config;
use Octo\Admin\Controller;
use Octo\Event;
use Octo\Store;
use Octo\System\Model\Setting;

class DashboardController extends Controller
{
    public function index()
    {
        $this->setTitle(Config::getInstance()->get('site.name') . ': Dashboard');
        $this->addBreadcrumb('Dashboard', '/');

        $moduleManager = Config::getInstance()->get('ModuleManager');

        $pageStore = Store::get('Page');

        if ($pageStore && $moduleManager->isEnabled('Pages')) {
            $this->view->pages = $pageStore->getTotal();
            $this->view->latestPages = $pageStore->getLatest(5);
        }

        if ($moduleManager->isEnabled('Forms')) {
            $contactStore = Store::get('Contact');

            if ($contactStore) {
                $this->view->contacts = $contactStore->getTotal();
            }

            $submissionStore = Store::get('Submission');

            if ($submissionStore) {
                $this->view->submissions = $submissionStore->getTotal();
                $this->view->latestSubmissions = $submissionStore->getAll(0, 5);
            }
        }

        $this->view->showAnalytics = false;
        if (Setting::get('analytics', 'ga_email') != '') {
            $this->view->showAnalytics = true;
        }

        Event::trigger('dashboardLoad', $this);
    }
}

<?php

namespace Octo\System\Admin\Controller;

use b8\Config;
use Octo\Admin\Controller;
use Octo\Event;
use Octo\Store;
use Octo\System\Model\Setting;

class DashboardController extends Controller
{
    public function index()
    {
        $this->setTitle(Config::getInstance()->get('site.name') . ': Dashboard');
        $this->addBreadcrumb('Dashboard', '/');

        $moduleManager = Config::getInstance()->get('ModuleManager');

        $pageStore = Store::get('Page');

        if ($pageStore && $moduleManager->isEnabled('Pages')) {
            $this->view->pages = $pageStore->getTotal();
            $this->view->latestPages = $pageStore->getLatest(5);
        }

        if ($moduleManager->isEnabled('Forms')) {
            $contactStore = Store::get('Contact');

            if ($contactStore) {
                $this->view->contacts = $contactStore->getTotal();
            }

            $submissionStore = Store::get('Submission');

            if ($submissionStore) {
                $this->view->submissions = $submissionStore->getTotal();
                $this->view->latestSubmissions = $submissionStore->getAll(0, 5);
            }
        }

        $this->view->showAnalytics = false;
        if (Setting::get('analytics', 'ga_email') != '') {
            $this->view->showAnalytics = true;
        }

        $instance = clone($this); // Can't pass and return $this to a listener, sadface.
        Event::trigger('dashboardLoad', $instance);
        $this->view = $instance->view;
    }
}

Add override listener to Dashboard.

Add override listener to Dashboard.


<?php

namespace Plummer\Calendarful;

interface RegistryInterface
{
	public function get();
}

<?php

namespace Plummer\Calendarful;

interface RegistryInterface
{
	public function get(Array $filters = array());
}

Add optional filters array to method signature.


<?php
include_once( "header.php" );
include_once( "methods.php" );
include_once( 'tohtml.php' );
include_once( "check_access_permissions.php" );
mustHaveAnyOfTheseRoles( Array( 'USER' ) );

echo userHTML( );

$user = $_SESSION[ 'user' ];

if( $_POST )
{
    $data = array( 'speaker' => $user );
    $data = array_merge( $_POST, $data );
    echo( "Sending your acknowledgment to database " );
    $res = updateTable( 'upcoming_aws', 'id,speaker', 'acknowledged', $data );
    if( $res )
    {
        echo printInfo(
            "You have successfully acknowledged your AWS schedule.
            Please mark your calendar as well."
        );

        $email = "<p>User " . loginToText( $user ) . " has just acknowledged his/her AWS date. </p>";
        $subject = "$user has acknowledged his/her AWS date";
        $to = 'hippo@lists.ncbs.res.in';
        sendPlainTextEmail( $email, $subject, $to );

        goToPage( "user_aws.php", 1 );
        exit;
    }
    else
    {
        echo printWarning( "Failed to update database ..." );
    }
}

echo goBackToPageLink( "user_aws.php", "Go back" );

?>

<?php
include_once( "header.php" );
include_once( "methods.php" );
include_once( 'tohtml.php' );
include_once( "check_access_permissions.php" );
mustHaveAnyOfTheseRoles( Array( 'USER' ) );

echo userHTML( );

$user = $_SESSION[ 'user' ];

if( $_POST )
{
    $data = array( 'speaker' => $user );
    $data = array_merge( $_POST, $data );
    echo( "Sending your acknowledgment to database " );
    $res = updateTable( 'upcoming_aws', 'id,speaker', 'acknowledged', $data );
    if( $res )
    {
        echo printInfo(
            "You have successfully acknowledged your AWS schedule.
            Please mark your calendar as well."
        );

        $email = "<p>" . loginToHTML( $user ) . " has just acknowledged his/her AWS date. </p>";
        $emial .= "<p>" . humanReadableDate( 'now' ) . "</p>";
        $subject = "$user has acknowledged his/her AWS date";

        $to = 'hippo@lists.ncbs.res.in';
        sendPlainTextEmail( $email, $subject, $to );

        goToPage( "user_aws.php", 1 );
        exit;
    }
    else
    {
        echo printWarning( "Failed to update database ..." );
    }
}

echo goBackToPageLink( "user_aws.php", "Go back" );

?>

Send email to hippo when user acknowledge his/her AWS.


<?php
	header("Refresh: 300");

	$now = date("Y-m-d H:i:s");
	$local_ip = getHostByName(getHostName());
	$ping_result = exec("ping -n 1 googlaasdasdase.com | FIND \"TTL=\"");
	$time = 0;
	$host_ip = "";

	preg_match('/Reply from (.*?):/', $ping_result, $ip_match);
	preg_match('/time=(.*?)ms/', $ping_result, $time_match);

	if (array_key_exists(1, $time_match))
		$time = $time_match[1];

	if (array_key_exists(1, $ip_match))
		$host_ip = $ip_match[1];

	$mysql_connection = new mysqli("localhost", "root", "", "pinger");

	if($mysql_connection->connect_error){
	    die("ERROR: Could not connect. " . mysqli_connect_error());
	}

	$stmt = $mysql_connection->prepare("INSERT INTO data (local_ip, host_ip, ping_time, ping_data) VALUES (?, ?, ?, ?)");
	$stmt->bind_param("ssss", $local_ip, $host_ip, $time, $ping_result);
	$stmt->execute();

	echo "Records inserted successfully.";

	mysqli_close($mysql_connection);

<?php
	header("Refresh: 300");

	$now = date("Y-m-d H:i:s");
	$local_ip = getHostByName(getHostName());
	$ping_result = exec("ping -n 1 google.com | FIND \"TTL=\"");
	$time = 0;
	$host_ip = "";

	preg_match('/Reply from (.*?):/', $ping_result, $ip_match);
	preg_match('/time=(.*?)ms/', $ping_result, $time_match);

	if (array_key_exists(1, $time_match))
		$time = $time_match[1];

	if (array_key_exists(1, $ip_match))
		$host_ip = $ip_match[1];

	$mysql_connection = new mysqli("localhost", "root", "", "pinger");

	if($mysql_connection->connect_error){
	    die("ERROR: Could not connect. " . mysqli_connect_error());
	}

	$stmt = $mysql_connection->prepare("INSERT INTO data (local_ip, host_ip, ping_time, ping_data) VALUES (?, ?, ?, ?)");
	$stmt->bind_param("ssss", $local_ip, $host_ip, $time, $ping_result);
	$stmt->execute();

	echo "Records inserted successfully.";

	mysqli_close($mysql_connection);

Fix URL and changed to google.com

Fix URL and changed to google.com


<?php

namespace AppBundle\Repository;

use AppBundle\Entity\Cycle;
use AppBundle\Entity\Pack;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\ResultSetMappingBuilder;

class PackRepository extends EntityRepository
{
    public function __construct(EntityManager $entityManager)
    {
        parent::__construct($entityManager, $entityManager->getClassMetadata('AppBundle\Entity\Pack'));
    }

    /**
     * @param Cycle $cycle
     * @return Pack[]
     */
    public function findByCycleWithCardCount(Cycle $cycle): array
    {
        $rsm = new ResultSetMappingBuilder($this->getEntityManager());
        $rsm->addRootEntityFromClassMetadata(Pack::class, 'p');
        $rsm->addScalarResult('cards', 'count', 'integer');

        $selectClause = $rsm->generateSelectClause([
            'p' => 'p',
        ]);

        $sql = 'SELECT ' . $selectClause . ', count(c.id) as cards from pack p
                    left join card c on c.pack_id=p.id
                    where p.cycle_id = ?
                    group by p.id
                    order by p.position';

        $query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
        $query->setParameter(1, $cycle->getId());

        return array_map(function ($item) {
            /** @var Pack $pack */
            $pack = $item[0];
            $pack->setCardCount($item['count']);

            return $pack;
        }, $query->getResult());
    }
}

<?php

namespace AppBundle\Repository;

use AppBundle\Entity\Cycle;
use AppBundle\Entity\Pack;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\ResultSetMappingBuilder;

class PackRepository extends EntityRepository
{
    public function __construct(EntityManager $entityManager)
    {
        parent::__construct($entityManager, $entityManager->getClassMetadata('AppBundle\Entity\Pack'));
    }

    /**
     * @param Cycle $cycle
     * @return Pack[]
     */
    public function findByCycleWithCardCount(Cycle $cycle): array
    {
        $rsm = new ResultSetMappingBuilder($this->getEntityManager());
        $rsm->addRootEntityFromClassMetadata(Pack::class, 'p');
        $rsm->addScalarResult('cards', 'count', 'integer');

        $selectClause = $rsm->generateSelectClause([
            'p' => 'p',
        ]);

        $sql = 'SELECT ' . $selectClause . ', count(c.id) as cards from pack p
                    left join card c on c.pack_id=p.id
                    where p.cycle_id = ?
                    group by p.id
                    order by p.position DESC';

        $query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
        $query->setParameter(1, $cycle->getId());

        return array_map(function ($item) {
            /** @var Pack $pack */
            $pack = $item[0];
            $pack->setCardCount($item['count']);

            return $pack;
        }, $query->getResult());
    }
}

Sort packs newest to oldest.

Sort packs newest to oldest.


<?php

namespace SilverLeague\Console\Framework\Loader;

use SilverLeague\Console\Command\Factory;
use SilverLeague\Console\Framework\ConsoleBase;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\BuildTask;

/**
 * The class responsible for loading/instantiating SilverStripe and accessing its class hierarchy, etc
 *
 * @package silverstripe-console
 * @author  Robbie Averill <robbie@averill.co.nz>
 */
class SilverStripeLoader extends ConsoleBase
{
    /**
     * Return a set of Tasks from SilverStripe
     *
     * @return array
     */
    public function getTasks()
    {
        $commands = [];
        $tasks = ClassInfo::subclassesFor(BuildTask::class);

        // Remove the BuildTask itself
        array_shift($tasks);

        foreach ($tasks as $taskClass) {
            $task = Injector::inst()->get($taskClass);
            if ($command = $this->getCommandFactory()->getCommandFromTask($task)) {
                $commands[] = $command;
            }
        }

        return $commands;
    }

    /**
     * Get a new command factory instance to generate the console Command
     *
     * @return Factory
     */
    public function getCommandFactory()
    {
        return new Factory($this->getApplication());
    }
}

<?php

namespace SilverLeague\Console\Framework\Loader;

use ReflectionClass;
use SilverLeague\Console\Command\Factory;
use SilverLeague\Console\Framework\ConsoleBase;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\BuildTask;

/**
 * The class responsible for loading/instantiating SilverStripe and accessing its class hierarchy, etc
 *
 * @package silverstripe-console
 * @author  Robbie Averill <robbie@averill.co.nz>
 */
class SilverStripeLoader extends ConsoleBase
{
    /**
     * Return a set of Tasks from SilverStripe
     *
     * @return array
     */
    public function getTasks()
    {
        $commands = [];
        $tasks = ClassInfo::subclassesFor(BuildTask::class);

        // Remove the BuildTask itself
        array_shift($tasks);

        foreach ($tasks as $taskClass) {
            if ($this->taskIsAbstract($taskClass)) {
                continue;
            }

            $task = Injector::inst()->get($taskClass);
            if ($command = $this->getCommandFactory()->getCommandFromTask($task)) {
                $commands[] = $command;
            }
        }

        return $commands;
    }

    /**
     * Get a new command factory instance to generate the console Command
     *
     * @return Factory
     */
    public function getCommandFactory()
    {
        return new Factory($this->getApplication());
    }

    /**
     * Check whether the given task class is abstract
     *
     * @param string $className
     * @return bool
     */
    protected function taskIsAbstract($className)
    {
        $reflection = new ReflectionClass($className);
        return $reflection->isAbstract();
    }
}

FIX Ignore abstract BuildTasks when loading commands


<?php

namespace Jwpage\Clickatell\Response;

class QueryMsg extends AbstractResponse
{
    public function getStatus()
    {
        preg_match('/Status: (.*?)$/', $this->parsedResponse[0][2], $matches);
        return $matches[1];
    }
}

<?php

namespace Jwpage\Clickatell\Response;

class QueryMsg extends AbstractResponse
{
    public function getStatus()
    {
        if (!$this->isSuccessful()) {
            return false;
        }

        preg_match('/Status: (.*?)$/', $this->parsedResponse[0][2], $matches);
        return $matches[1];
    }
}

Return false if not successful

Return false if not successful


<?php
  $dir = "sqlite:../db/home.db";
  $pdo = new PDO($dir);
  $stmt = $pdo->query("SELECT * FROM heater WHERE heater_id = 1");
  $row = $stmt->fetchObject();

  function GetCurrentPower() {
    global $row;
    return ($row->current_power == 1);
  }

  function SetCurrentPower($power) {
    global $pdo;
    $stmt = $pdo->prepare(GetUpdateSql("current_power", $power));
    $stmt->execute();
  }

  function GetUpdateSql($field, $val) {
    return sprintf("UPDATE heater set %s = %d WHERE heater_id = 1", $field, $val);
  }
?>

<?php
  $pdo = new PDO("sqlite:../db/home.db");
  $stmt = $pdo->query("SELECT * FROM heater WHERE heater_id = 1");
  $row = $stmt->fetchObject();

  function GetUpdateSql($field, $val) {
    return sprintf("UPDATE heater SET %s = %d WHERE heater_id = 1", $field, $val);
  }

  function GetCurrentPower() {
    global $row;
    return ($row->current_power == 1);
  }

  function SetCurrentPower($power) {
    if ($power != GetCurrentPower()) {
      global $pdo;
      $stmt = $pdo->prepare(GetUpdateSql("current_power", $power));
      $stmt->execute();
    }
  }

  function GetSelectedPower() {
    global $row;
    return ($row->selected_power == 1);
  }

  function SetSelectedPower($power) {
    if ($power != GetSelectedPower()) {
      global $pdo;
      $stmt = $pdo->prepare(GetUpdateSql("selected_power", $power));
      $stmt->execute();
    }
  }

  function BoundTemperature($temperature) {
    $max = 20.0;
    $min = 10.0;
    return min($max, max($min, $temperature));
  }

  function GetCurrentTemperature() {
    global $row;
    return $row->current_temperature;
  }

  function SetCurrentTemperature($temperature) {
    if ($temperature != GetCurrentTemperature()) {
      global $pdo;
      $stmt = $pdo->prepare(GetUpdateSql("current_temperature", BoundTemperature($temperature)));
      $stmt->execute();
    }
  }

  function GetSelectedTemperature() {
    global $row;
    return $row->selected_temperature;
  }

  function SetSelectedTemperature($temperature) {
    if ($temperature != GetSelectedTemperature()) {
      global $pdo;
      $stmt = $pdo->prepare(GetUpdateSql("selected_temperature", BoundTemperature($temperature)));
      $stmt->execute();
    }
  }
?>

Add wrapper functions for table fields

Add wrapper functions for table fields


<?php namespace Orchestra\Support;

use Illuminate\Support\ServiceProvider;

class MessagesServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['orchestra.messages'] = $this->app->share(function () {
            return new Messages;
        });

        $this->app->booting(function () {
            $loader = AliasLoader::getInstance();
            $loader->alias('Orchestra\Messages', 'Orchestra\Support\Facades\Messages');
        });
    }

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

        $app->after(function () use ($app) {
            $app['orchestra.messages']->save();
        });
    }
}

<?php namespace Orchestra\Support;

use Illuminate\Support\ServiceProvider;

class MessagesServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['orchestra.messages'] = $this->app->share(function () {
            return new Messages;
        });
    }

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

        $app->after(function () use ($app) {
            $app['orchestra.messages']->save();
        });
    }
}

Remove alias from service provider.

Remove alias from service provider.

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php
/**
 * This class formats log entries for thanks
 */
class ThanksLogFormatter extends LogFormatter {
	/**
	 * @inheritDoc
	 * @suppress SecurityCheck-DoubleEscaped Problem with makeUserLink, see T201565
	 */
	protected function getMessageParameters() {
		$params = parent::getMessageParameters();
		// Convert target from a pageLink to a userLink since the target is
		// actually a user, not a page.
		$recipient = User::newFromName( $this->entry->getTarget()->getText(), false );
		$params[2] = Message::rawParam( $this->makeUserLink( $recipient ) );
		$params[3] = $recipient->getName();
		return $params;
	}

	public function getPreloadTitles() {
		// Add the recipient's user talk page to LinkBatch
		return [ Title::makeTitle( NS_USER_TALK, $this->entry->getTarget()->getText() ) ];
	}
}

<?php
/**
 * This class formats log entries for thanks
 */
class ThanksLogFormatter extends LogFormatter {
	/**
	 * @inheritDoc
	 */
	protected function getMessageParameters() {
		$params = parent::getMessageParameters();
		// Convert target from a pageLink to a userLink since the target is
		// actually a user, not a page.
		$recipient = User::newFromName( $this->entry->getTarget()->getText(), false );
		$params[2] = Message::rawParam( $this->makeUserLink( $recipient ) );
		$params[3] = $recipient->getName();
		return $params;
	}

	public function getPreloadTitles() {
		// Add the recipient's user talk page to LinkBatch
		return [ Title::makeTitle( NS_USER_TALK, $this->entry->getTarget()->getText() ) ];
	}
}

Remove unneccessary @suppress after phan-taint-check-plugin upgrade

Bug: T201565
Change-Id: Ib35e55e5bebbb7dc6ca8ef4f08b519ec2065037b


<?php

namespace Retrinko\CottonTail\Message\Messages;

use Retrinko\CottonTail\Exceptions\MessageException;
use Retrinko\CottonTail\Message\MessageInterface;
use Retrinko\CottonTail\Message\Payloads\RpcResponsePayload;

class RpcResponseMessage extends BasicMessage
{
    /**
     * @var array
     */
    protected $requiredProperties = [MessageInterface::PROPERTY_TYPE,
                                     MessageInterface::PROPERTY_CORRELATION_ID,
                                     MessageInterface::PROPERTY_CONTENT_TYPE];

    /**
     * @param string $body
     * @param array $properties
     */
    public function __construct($body = '', array $properties = [])
    {
        // Override MessageInterface::PROPERTY_TYPE
        $properties[MessageInterface::PROPERTY_TYPE] = MessageInterface::TYPE_RPC_RESPONSE;
        parent::__construct($body, $properties);
    }

    /**
     * @return RpcResponsePayload
     */
    public function getPayload()
    {
        $data = parent::getPayload();

        return new RpcResponsePayload($data);
    }

    /**
     * @param array $properties
     *
     * @throws MessageException
     */
    protected function checkRequiredPropertiesPresence(array $properties)
    {
        parent::checkRequiredPropertiesPresence($properties);
        if (MessageInterface::TYPE_RPC_RESPONSE != $properties[MessageInterface::PROPERTY_TYPE])
        {
            throw MessageException::wrongMessageType($this->getType(),
                                                     MessageInterface::TYPE_RPC_REQUEST);
        }
    }

}

<?php

namespace Retrinko\CottonTail\Message\Messages;

use Retrinko\CottonTail\Exceptions\MessageException;
use Retrinko\CottonTail\Message\MessageInterface;
use Retrinko\CottonTail\Message\Payloads\RpcResponsePayload;

class RpcResponseMessage extends BasicMessage
{
    /**
     * @var array
     */
    protected $requiredProperties = [MessageInterface::PROPERTY_TYPE,
                                     MessageInterface::PROPERTY_CORRELATION_ID,
                                     MessageInterface::PROPERTY_CONTENT_TYPE];

    /**
     * @param string $body
     * @param array $properties
     */
    public function __construct($body = '', array $properties)
    {
        // Override MessageInterface::PROPERTY_TYPE
        $properties[MessageInterface::PROPERTY_TYPE] = MessageInterface::TYPE_RPC_RESPONSE;
        parent::__construct($body, $properties);
    }

    /**
     * @return RpcResponsePayload
     */
    public function getPayload()
    {
        $data = parent::getPayload();

        return new RpcResponsePayload($data);
    }

    /**
     * @param array $properties
     *
     * @throws MessageException
     */
    protected function checkRequiredPropertiesPresence(array $properties)
    {
        parent::checkRequiredPropertiesPresence($properties);
        if (MessageInterface::TYPE_RPC_RESPONSE != $properties[MessageInterface::PROPERTY_TYPE])
        {
            throw MessageException::wrongMessageType($this->getType(),
                                                     MessageInterface::TYPE_RPC_REQUEST);
        }
    }

}

Remove default value for properties.

Remove default value for properties.


<?php namespace Sprockets\Filter;

use Sprockets\Asset;
use Sprockets\TmpFile;

class CoffeeScriptFilter extends BaseProcessFilter {

	protected $bare = false;

	public function __construct($config = array())
	{
		if (array_key_exists('bare', $config))
		{
			$this->bare = $config['bare'];
		}
	}

	protected function command(Asset $asset, TmpFile $tmpFile)
	{
		$options = array('c', 'p', 'l');

		if ($this->bare)
		{
			$options[] = 'b';
		}

		return array('coffee', '-'.implode($options), $tmpFile->getRealPath());
	}

}

<?php namespace Sprockets\Filter;

use Sprockets\Asset;
use Sprockets\TmpFile;

class CoffeeScriptFilter extends BaseProcessFilter {

	protected $bare = false;

	public function __construct($config = array())
	{
		if (array_key_exists('bare', $config))
		{
			$this->bare = $config['bare'];
		}
	}

	protected function command(Asset $asset, TmpFile $tmpFile)
	{
		$options = array('c', 'p');

		if ($this->bare)
		{
			$options[] = 'b';
		}

		return array('coffee', '-'.implode($options), $tmpFile->getRealPath());
	}

}

Remove the -l option from the CoffeeScript filter because it breaks


<?php
require_once __DIR__ . '/../../abstract.php';

class Meanbee_Configpoweredcss_Regenerate extends Mage_Shell_Abstract
{

    /**
     * Run script
     *
     */
    public function run()
    {

        /**
         * Shell script regenerate the configpowered css for all stores
         */

        try {

            /** @var Meanbee_ConfigPoweredCss_Model_Css $css */
            $css = Mage::getModel('meanbee_configpoweredcss/css');

            $stores = Mage::app()->getStores();
            foreach ($stores as $storeId => $store) {
                try {
                    Mage::app()->setCurrentStore($storeId);
                    $css->publish($storeId);
                } catch (Exception $e) {
                    Mage::logException($e);
                    return;
                }
            }

            fwrite(STDERR,
                "Config powered css has been regenerated successfully.\n");
            exit(0);
        } catch (Exception $e) {
            Mage::logException($e);

            fwrite(STDERR,
                "There was an error when regenerating the config powered css, it has been logged.\n");
            exit(1);
        }
    }
}

$shell = new Meanbee_Configpoweredcss_Regenerate();
$shell->run();

<?php
require_once __DIR__ . '/../../abstract.php';

class Meanbee_Configpoweredcss_Regenerate extends Mage_Shell_Abstract
{

    /**
     * Run script
     *
     */
    public function run()
    {

        /**
         * Shell script regenerate the configpowered css for all stores
         */

        try {

            /** @var Meanbee_ConfigPoweredCss_Model_Css $css */
            $css = Mage::getModel('meanbee_configpoweredcss/css');

            $stores = Mage::app()->getStores();
            foreach ($stores as $storeId => $store) {
                try {
                    Mage::app()->setCurrentStore($storeId);
                    $css->publish($storeId);
                } catch (Exception $e) {
                    fwrite(STDERR, sprintf('There was an error when regenerating the config powered css: %s',
                        $e->getTraceAsString()));
                    exit(1);
                }
            }

            fwrite(STDOUT,
                "Config powered css has been regenerated successfully.\n");
            exit(0);
        } catch (Exception $e) {
            fwrite(STDERR,
                sprintf('There was an error when regenerating the config powered css: %s', $e->getTraceAsString()));
            exit(1);
        }
    }
}

$shell = new Meanbee_Configpoweredcss_Regenerate();
$shell->run();

Update the error messaging to be more useful and use the correct exit codes


<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'normington@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: robot@normo.uk\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

Add email to contact form

Add email to contact form


<?php

namespace Eluceo\iCal\Property\Event;

use Eluceo\iCal\Property\ValueInterface;
use Eluceo\iCal\Util\PropertyValueUtil;

/**
 * Class Description
 * Alows new line charectars to be in the description
 *
 * @package Eluceo\iCal\Property
 */
class Description implements ValueInterface
{
    /**
     * The value.
     *
     * @var string
     */
    protected $value;

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

    /**
     * Return the value of the Property as an escaped string.
     *
     * Escape values as per RFC 2445. See http://www.kanzaki.com/docs/ical/text.html
     *
     * @return string
     */
    public function getEscapedValue()
    {
        return PropertyValueUtil::escapeValueAllowNewLine((string) $this->value);
    }

    /**
     * @param string $value
     *
     * @return $this
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }
}

<?php

namespace Eluceo\iCal\Property\Event;

use Eluceo\iCal\Property\ValueInterface;
use Eluceo\iCal\Util\PropertyValueUtil;

/**
 * Class Description
 * Alows new line charectars to be in the description
 *
 * @package Eluceo\iCal\Property
 */
class Description implements ValueInterface
{
    /**
     * The value.
     *
     * @var string
     */
    protected $value;

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

    /**
     * Return the value of the Property as an escaped string.
     *
     * Escape values as per RFC 2445. See http://www.kanzaki.com/docs/ical/text.html
     *
     * @return string
     */
    public function getEscapedValue()
    {
        return PropertyValueUtil::escapeValue((string) $this->value);
    }

    /**
     * @param string $value
     *
     * @return $this
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }
}

Use 'escapeValue' to escape the new line character

We need to escape the new line character as well as per RFC : http://tools.ietf.org/html/rfc5545#section-3.3.11


<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Field\Configurator;

use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldConfiguratorInterface;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;

/**
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
final class BooleanConfigurator implements FieldConfiguratorInterface
{
    public function supports(FieldDto $field, EntityDto $entityDto): bool
    {
        return BooleanField::class === $field->getFieldFqcn();
    }

    public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $context): void
    {
        // TODO: ask someone who knows Symfony forms well how to make this work
        if ($field->getCustomOption(BooleanField::OPTION_RENDER_AS_SWITCH)) {
            // see https://symfony.com/blog/new-in-symfony-4-4-bootstrap-custom-switches
            // $field->setFormTypeOptionIfNotSet('label_attr.class', 'switch-custom');
        }
    }
}

<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Field\Configurator;

use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldConfiguratorInterface;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;

/**
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
final class BooleanConfigurator implements FieldConfiguratorInterface
{
    public function supports(FieldDto $field, EntityDto $entityDto): bool
    {
        return BooleanField::class === $field->getFieldFqcn();
    }

    public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $context): void
    {
        $isRenderedAsSwitch = true === $field->getCustomOption(BooleanField::OPTION_RENDER_AS_SWITCH);
        if ($isRenderedAsSwitch && false !== strpos($field->getProperty(), '.')) {
            throw new \InvalidArgumentException('The "%s" property cannot be rendered as a switch because it belongs to an associated entity instead of to the entity itself. Render the property as a normal boolean field.', $field->getProperty());
        }

        // TODO: ask someone who knows Symfony forms well how to make this work
        if ($isRenderedAsSwitch) {
            // see https://symfony.com/blog/new-in-symfony-4-4-bootstrap-custom-switches
            // $field->setFormTypeOptionIfNotSet('label_attr.class', 'switch-custom');
        }
    }
}

Throw an error for boolean properties of associated entities


<?php
declare(strict_types=1);

namespace WoohooLabs\Yin\Tests\JsonApi\Serializer;

use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use WoohooLabs\Yin\JsonApi\Serializer\JsonDeserializer;
use Zend\Diactoros\ServerRequest;

class JsonDeserializerTest extends TestCase
{
    /**
     * @test
     */
    public function deserializeEmptyBody()
    {
        $request = $this->createRequestWithJsonBody("");

        $deserializer = new JsonDeserializer();

        $this->expectException(InvalidArgumentException::class);
        $deserializer->deserialize($request);
    }

    /**
     * @test
     */
    public function deserialize()
    {
        $parsedBody = [
            "data" => [
                "type" => "cat",
                "id" => "tom",
            ],
        ];

        $request = $this->createRequestWithJsonBody($parsedBody);

        $this->assertEquals($parsedBody, $request->getParsedBody());
    }

    private function createRequestWithJsonBody($body): ServerRequest
    {
        $request = new ServerRequest();

        return $request->withParsedBody($body);
    }
}

<?php
declare(strict_types=1);

namespace WoohooLabs\Yin\Tests\JsonApi\Serializer;

use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use WoohooLabs\Yin\JsonApi\Serializer\JsonDeserializer;
use Zend\Diactoros\ServerRequest;

class JsonDeserializerTest extends TestCase
{
    /**
     * @test
     */
    public function deserializeNullBody()
    {
        $request = $this->createRequestWithJsonBody(null);

        $deserializer = new JsonDeserializer();

        $this->assertNull($deserializer->deserialize($request));
    }

    /**
     * @test
     */
    public function deserializeEmptyBody()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->createRequestWithJsonBody("");
    }

    /**
     * @test
     */
    public function deserialize()
    {
        $parsedBody = [
            "data" => [
                "type" => "cat",
                "id" => "tom",
            ],
        ];

        $request = $this->createRequestWithJsonBody($parsedBody);

        $this->assertEquals($parsedBody, $request->getParsedBody());
    }

    private function createRequestWithJsonBody($body): ServerRequest
    {
        $request = new ServerRequest();

        return $request->withParsedBody($body);
    }
}

Add test for deserializing null body

Add test for deserializing null body


<?php

class CarouselSlide extends DataObject {
	private static $db = array(
		'Title' => 'Varchar(100)',
		'External' => 'Boolean',
		'ExternalLink' => 'Varchar(200)',
		'SlideSort' => 'Int'
	);

	private static $has_one = array(
		'SlideImage' => 'Image',
		'HolderPage' => 'Page',
		'IntenalLink' => 'SiteTree'
	);

	private static $default_sort = 'SlideSort';

	public function getCMSFields() {
		$fields = new FieldList();
		$fields->push(new TextField('Title', 'Title'));
		$fields->push($image = new UploadField('SlideImage', 'SlideImage'));
		$image->setAllowedFileCategories('image');
		$image->setAllowedMaxFileNumber(1);
		$image->setCanAttachExisting(true);
		$image->setFolderName('Carousel');

		$fields->push(new TreeDropdownField("IntenalLinkID", "Choose a page to link to", "SiteTree"));
		$fields->push(new CheckboxField('External', 'Using external link'));
		$fields->push(new TextField('ExternalLink', 'External Link URL'));

		return $fields;
	}
}

<?php

class CarouselSlide extends DataObject {
	private static $db = array(
		'Title' => 'Varchar(100)',
		'UseLink' => 'Boolean',
		'ExternalLink' => 'Varchar(200)',
		'SlideSort' => 'Int'
	);

	private static $has_one = array(
		'SlideImage' => 'Image',
		'HolderPage' => 'Page',
		'IntenalLink' => 'SiteTree'
	);

	private static $default_sort = 'SlideSort';

	public function getCMSFields() {
		$fields = new FieldList();
		$fields->push(new TextField('Title', 'Title'));
		$fields->push($image = new UploadField('SlideImage', 'SlideImage'));
		$image->setAllowedFileCategories('image');
		$image->setAllowedMaxFileNumber(1);
		$image->setCanAttachExisting(true);
		$image->setFolderName('Carousel');
		$fields->push(new CheckboxField('UseLink', 'Slide links to page'));
		$fields->push($tree = new TreeDropdownField("IntenalLinkID", "Choose a page to link to", "SiteTree"));
		$fields->push(new TextField('ExternalLink', 'Or use this URL'));
		$tree->setChildrenMethod('Children');

		return $fields;
	}

	public function onBeforeWrite() {
		parent::onBeforeWrite();
		$this->ExternalLink = trim($this->ExternalLink);
		if($this->ExternalLink != '' && !preg_match('!://!', $this->ExternalLink)) $this->ExternalLink = 'http://' . $this->ExternalLink;
		if($this->SlideImage()) {
			$this->SlideImage()->Title = $this->Title;
			$this->SlideImage()->write();
		}
	}
}

Change to handling of links to allow for no link


<?php

namespace PhpAbac\Test;

use PhpAbac\Abac;

class AbacTest extends \PHPUnit_Framework_TestCase {
    public function setUp() {
        new Abac(new \PDO(
            'mysql:host=' . $GLOBALS['MYSQL_DB_HOST'] . ';' .
            'dbname=' . $GLOBALS['MYSQL_DB_DBNAME'],
            $GLOBALS['MYSQL_DB_USER'],
            $GLOBALS['MYSQL_DB_PASSWD'],
            [
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
            ]
        ));
    }

    public function tearDown() {
        Abac::clearContainer();
    }

    public function testContainer() {
        $item = new \stdClass();
        $item->property = 'test';
        // Test Set method
        Abac::set('test-item', $item);
        // Test Has method
        $this->assertTrue(Abac::has('test-item'));
        // Test Get method
        $containedItem = Abac::get('test-item');

        $this->assertInstanceof('StdClass', $containedItem);
        $this->assertEquals('test', $containedItem->property);
        // Test clearContainer
        Abac::clearContainer();
        $this->assertFalse(Abac::has('test-item'));
    }
}

<?php

namespace PhpAbac\Test;

use PhpAbac\Abac;

class AbacTest extends AbacTestCase {
    /** @var Abac **/
    protected $abac;

    public function setUp() {
        $this->abac = new Abac(new \PDO(
            'mysql:host=' . $GLOBALS['MYSQL_DB_HOST'] . ';' .
            'dbname=' . $GLOBALS['MYSQL_DB_DBNAME'],
            $GLOBALS['MYSQL_DB_USER'],
            $GLOBALS['MYSQL_DB_PASSWD'],
            [
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
            ]
        ));
        $this->abac->resetSchema();
        $this->loadFixture('rules');
    }

    public function tearDown() {
        Abac::clearContainer();
    }

    public function testEnforce() {
        $this->abac->enforce('nationality-access', 1);
    }

    public function testContainer() {
        $item = new \stdClass();
        $item->property = 'test';
        // Test Set method
        Abac::set('test-item', $item);
        // Test Has method
        $this->assertTrue(Abac::has('test-item'));
        // Test Get method
        $containedItem = Abac::get('test-item');

        $this->assertInstanceof('StdClass', $containedItem);
        $this->assertEquals('test', $containedItem->property);
        // Test clearContainer
        Abac::clearContainer();
        $this->assertFalse(Abac::has('test-item'));
    }
}

Load fixtures for the Abac tests

Load fixtures for the Abac tests


<?php

require_once 'Swat/SwatPage.php';
require_once 'XML/RPC2/Server.php';

/**
 * Base class for an XML-RPC Server
 *
 * The XML-RPC server acts as a regular page in an application. This means
 * all the regular page security features work for XML-RPC servers.
 *
 * Swat XML-RPC server pages use the PEAR::XML_RPC2 package to service
 * requests.
 *
 * @package   Swat
 * @copyright 2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
abstract class SwatXMLRPCServer extends SwatPage
{
	/**
	 * Process the request
	 *
	 * This method is called by site code to process the page request. It creates
	 * an XML-RPC server and handles a request. The XML-RPC response from the
	 * server is output here as well.
	 *
	 * @xmlrpc.hidden
	 */
	public function process()
	{
		$server = XML_RPC2_Server::create($this);

		ob_start();
		$server->handleCall();
		// TODO: remove workaround when php-5.0.5 is commonplace
		$x = ob_get_clean();
		$this->layout->response = $x;
	}

	/**
	 * @xmlrpc.hidden
	 */
	public function build()
	{
	}

	protected function createLayout()
	{
		return new SwatLayout('Swat/layouts/xmlrpcserver.php');
	}
}

?>

<?php

require_once 'Swat/SwatPage.php';
require_once 'XML/RPC2/Server.php';

/**
 * Base class for an XML-RPC Server
 *
 * The XML-RPC server acts as a regular page in an application. This means
 * all the regular page security features work for XML-RPC servers.
 *
 * Swat XML-RPC server pages use the PEAR::XML_RPC2 package to service
 * requests.
 *
 * @package   Swat
 * @copyright 2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
abstract class SwatXMLRPCServer extends SwatPage
{
	/**
	 * Process the request
	 *
	 * This method is called by site code to process the page request. It creates
	 * an XML-RPC server and handles a request. The XML-RPC response from the
	 * server is output here as well.
	 *
	 * @xmlrpc.hidden
	 */
	public function process()
	{
		$server = XML_RPC2_Server::create($this);

		ob_start();
		$server->handleCall();
		$this->layout->response = ob_get_clean();
	}

	/**
	 * @xmlrpc.hidden
	 */
	public function build()
	{
	}

	protected function createLayout()
	{
		return new SwatLayout('Swat/layouts/xmlrpcserver.php');
	}
}

?>

Remove workaround now that we are using PHP 5.0.5

svn commit r1967


<?php
namespace Youkok\Processors\Admin;

use Youkok\Models\Element;

class PendingProcessor
{
    public static function run()
    {
        return Element::where('pending', 1)->count();
    }
}

<?php
namespace Youkok\Processors\Admin;

use Youkok\Models\Element;

class PendingProcessor
{
    public static function run()
    {
        return Element
            ::where('pending', 1)
            ->where('deleted', 0)
            ->count();
    }
}

Make sure indicator for number of pending elements reflects the actual query


<?php

namespace BruceCms\Pages;

use Illuminate\Database\Eloquent\Model;
use Knp\Menu\MenuFactory;
use Knp\Menu\Matcher\Matcher;
use Knp\Menu\Renderer\ListRenderer;

class Page extends Model
{

    /**
     * Columns which are allowed to be mass-assigned.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'link',
        'body',
        'sort',
        'hidden'
    ];

    /**
     * Limit a query to the pages that are not hidden from navigation.
     *
     * @param $query
     * @return mixed
     */
    public function scopeUnhidden($query)
    {
        return $query->where('hidden', '0');
    }

    /**
     * Build the navigation for pages.
     */
    public function printMenu()
    {
        $factory = new MenuFactory();
        $menu = $factory->createItem('navigation');

        foreach ($this->unhidden()->orderBy('sort')->get() as $page) {
            $menu->addChild($page->title, [ 'uri' => url($page->link) ]);
        }

        $renderer = new ListRenderer(new Matcher());
        echo $renderer->render($menu);
    }
}

<?php

namespace BruceCms\Pages;

use Illuminate\Database\Eloquent\Model;
use Knp\Menu\MenuFactory;
use Knp\Menu\Matcher\Matcher;
use Knp\Menu\Renderer\ListRenderer;

class Page extends Model
{

    /**
     * Columns which are allowed to be mass-assigned.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'link',
        'body',
        'sort',
        'hidden'
    ];

    /**
     * Limit a query to the pages that are not hidden from navigation.
     *
     * @param $query
     * @return mixed
     */
    public function scopeUnhidden($query)
    {
        return $query->where('hidden', '0');
    }

    /**
     * Build the navigation for pages.
     */
    public function printMenu()
    {
        $factory = new MenuFactory();
        $menu = $factory->createItem('navigation');

        $pages = $this->unhidden()->orderBy('sort')->get();

        // Create the top level of navigation.
        foreach ($pages as $page) {
            if ($page->parent_id == 0) {
                $menu->addChild($page->title, [ 'uri' => url($page->link) ]);
                $menu[$page->title]->setAttribute('id', $page->id);
            }
        }

        // Create the child nodes.
        foreach ($menu as $menuItem) {
            foreach ($pages as $page) {
                if ($page->parent_id == $menuItem->getAttribute('id')) {
                    $menu[$menuItem->getName()]->addChild($page->title, ['uri' => url($page->link) ]);
                }
            }
        }

        $renderer = new ListRenderer(new Matcher());
        echo $renderer->render($menu);
    }
}

Add parenting logic for pages.

Add parenting logic for pages.


<?php
/**
 * Part of the CSCMS package by Coder Studios.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the terms of the MIT license https://opensource.org/licenses/MIT
 *
 * @package    CSCMS
 * @version    1.0.0
 * @author     Coder Studios Ltd
 * @license    MIT https://opensource.org/licenses/MIT
 * @copyright  (c) 2017, Coder Studios Ltd
 * @link       https://www.coderstudios.com
 */

namespace CoderStudios\CSCMS\Middleware;

use Closure;
use Illuminate\Contracts\Cache\Repository as Cache;

class ClearCache
{
    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Cache\Repository  $cache
     * @return void
     */
    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     *
     */
    public function handle($request, Closure $next)
    {
        if (!config('app.coderstudios.cache_enabled')) {
            $this->cache->flush();
        }

        if ($request->session()->get('clear_cache')) {
            $this->cache->flush();
            $request->session()->remove('clear_cache');
        }

        return $next($request);
    }
}

<?php
/**
 * Part of the CSCMS package by Coder Studios.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the terms of the MIT license https://opensource.org/licenses/MIT
 *
 * @package    CSCMS
 * @version    1.0.0
 * @author     Coder Studios Ltd
 * @license    MIT https://opensource.org/licenses/MIT
 * @copyright  (c) 2017, Coder Studios Ltd
 * @link       https://www.coderstudios.com
 */

namespace CoderStudios\CSCMS\Middleware;

use Closure;
use Session;
use Illuminate\Contracts\Cache\Repository as Cache;

class ClearCache
{
    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Cache\Repository  $cache
     * @return void
     */
    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     *
     */
    public function handle($request, Closure $next)
    {
        if (!config('app.coderstudios.cache_enabled')) {
            $this->cache->flush();
        }

        if (Session()->get('clear_cache')) {
            $this->cache->flush();
            Session()->remove('clear_cache');
        }

        return $next($request);
    }
}

Update to use Session helper

Update to use Session helper

Session no longer available with $request


<?php
/**
* @version      $Id$
* @category		Koowa
* @package		Koowa_Toolbar
* @subpackage	Button
* @copyright    Copyright (C) 2007 - 2009 Johan Janssens and Mathias Verraes. All rights reserved.
* @license      GNU GPL <http://www.gnu.org/licenses/gpl.html>
*/

/**
 * POST button class for a toolbar
 *
 * @author		Mathias Verraes <mathias@koowa.org>
 * @category	Koowa
 * @package		Koowa_Toolbar
 * @subpackage	Button
 */
abstract class KToolbarButtonPost extends KToolbarButtonAbstract
{
	protected $_fields = array();

	public function __construct(array $options = array())
	{
		parent::__construct($options);
		$this->setMethod('post');

		$script = Koowa::getURL('js').'koowa.js';
		KFactory::get('lib.joomla.document')->addScript($script);
	}

	public function getOnClick()
	{
		$js = '';
		foreach($this->_fields as $name => $value) {
			$js .= "Koowa.Form.addField('$name', '$value');";
		}
		$js .= "Koowa.Form.submit('{$this->_method}');";
		return $js;
	}

	public function setField($name, $value)
	{
		$this->_fields[$name] = $value;
		return $this;
	}
}

<?php
/**
* @version      $Id$
* @category		Koowa
* @package		Koowa_Toolbar
* @subpackage	Button
* @copyright    Copyright (C) 2007 - 2009 Johan Janssens and Mathias Verraes. All rights reserved.
* @license      GNU GPL <http://www.gnu.org/licenses/gpl.html>
*/

/**
 * POST button class for a toolbar
 *
 * @author		Mathias Verraes <mathias@koowa.org>
 * @category	Koowa
 * @package		Koowa_Toolbar
 * @subpackage	Button
 */
abstract class KToolbarButtonPost extends KToolbarButtonAbstract
{
	protected $_fields = array();

	public function __construct(array $options = array())
	{
		parent::__construct($options);
		$this->setMethod('post');

		KTemplate::loadHelper('script', Koowa::getURL('js').'koowa.js');
	}

	public function getOnClick()
	{
		$js = '';
		foreach($this->_fields as $name => $value) {
			$js .= "Koowa.Form.addField('$name', '$value');";
		}
		$js .= "Koowa.Form.submit('{$this->_method}');";
		return $js;
	}

	public function setField($name, $value)
	{
		$this->_fields[$name] = $value;
		return $this;
	}
}

Use KTemplate instead of KDocument to load script


<?php

$title = __('Neatline | Browse Exhibits');

echo head(array(
  'title' => $title,
  'content_class' => 'neatline'
)); ?>

  <?php echo flash(); ?>

<?php echo $title; ?>

  <?php if (nl_exhibitsHaveBeenCreated()): ?>

<?php echo pagination_links(); ?>

      <?php foreach (loop('NeatlineExhibit') as $e): ?>

          <?php echo nl_getExhibitLink(
            $e, 'show', nl_getExhibitField('title'),
            array('class' => 'neatline'), true
          );?>

<?php echo snippet_by_word_count(nl_getExhibitField('narrative'), 20); ?>.<?php echo nl_getExhibitLink(
            $e, 'show', 'Read more.',
            array('class' => 'neatline'), true
          );?>

      <?php endforeach; ?>

<?php echo pagination_links(); ?>

  <?php endif; ?>

<?php echo foot(); ?>

<?php

$title = __('Neatline | Browse Exhibits');

echo head(array(
  'title' => $title,
  'content_class' => 'neatline'
)); ?>

  <?php echo flash(); ?>

<?php echo $title; ?>

  <?php if (nl_exhibitsHaveBeenCreated()): ?>

<?php echo pagination_links(); ?>

      <?php foreach (loop('NeatlineExhibit') as $e): ?>

          <?php echo nl_getExhibitLink(
            $e, 'show', nl_getExhibitField('title'),
            array('class' => 'neatline'), true
          );?>

        <?php if ($description = snippet_by_word_count(nl_getExhibitField('narrative'), 20)) : ?>

<?php echo $description . nl_getExhibitLink($e, 'show', 'Read more.', array('class' => 'neatline'), true); ?>

        <?php endif; ?>
      <?php endforeach; ?>

<?php echo pagination_links(); ?>

  <?php endif; ?>

<?php echo foot(); ?>

Check if there's a narrative before displaying a Read More link.


<?php

namespace CultuurNet\UDB3\SavedSearches\Command;

use CultuurNet\UDB3\ValueObject\SapiVersion;
use ValueObjects\StringLiteral\StringLiteral;

abstract class SavedSearchCommand
{
    /**
     * @var SapiVersion
     */
    protected $sapiVersion;

    /**
     * @var StringLiteral
     */
    protected $userId;

    /**
     * @param SapiVersion $sapiVersion
     * @param StringLiteral $userId
     */
    public function __construct(
        SapiVersion $sapiVersion,
        StringLiteral $userId
    ) {
        $this->sapiVersion = $sapiVersion;
        $this->userId = $userId;
    }

    /**
     * @return SapiVersion
     */
    public function getSapiVersion(): SapiVersion
    {
        return $this->sapiVersion;
    }

    /**
     * @return StringLiteral
     */
    public function getUserId()
    {
        return $this->userId;
    }
}

<?php

namespace CultuurNet\UDB3\SavedSearches\Command;

use CultuurNet\UDB3\ValueObject\SapiVersion;
use ValueObjects\StringLiteral\StringLiteral;

abstract class SavedSearchCommand
{
    /**
     * @var string
     */
    protected $sapiVersion;

    /**
     * @var StringLiteral
     */
    protected $userId;

    /**
     * @param SapiVersion $sapiVersion
     * @param StringLiteral $userId
     */
    public function __construct(
        SapiVersion $sapiVersion,
        StringLiteral $userId
    ) {
        $this->sapiVersion = $sapiVersion->toNative();
        $this->userId = $userId;
    }

    /**
     * @return SapiVersion
     */
    public function getSapiVersion(): SapiVersion
    {
        return SapiVersion::fromNative($this->sapiVersion);
    }

    /**
     * @return StringLiteral
     */
    public function getUserId()
    {
        return $this->userId;
    }
}

III-2779: Fix exception about enums that can't be serialized, ensure native sapiVersion is serialized instead