<?php
/**
 * README plugin for HiDev
 *
 * @link      https://github.com/hiqdev/hidev-readme
 * @package   hidev-readme
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
 */

return [
    'controllerMap' => [
        'README' => [
            'class' => \hidev\readme\console\ReadmeController::class,
            'type' => 'text',
        ],
        'README.md' => [
            'class' => \hidev\readme\console\ReadmeController::class,
            'type' => 'markdown',
        ],
    ],
    'components' => [
        'readme' => [
            'class' => \hidev\readme\components\Readme::class,
            'knownBadges' => [
                'github.release'          => '[![GitHub release](https://img.shields.io/github/release/{{ app.github.full_name }}.svg)](https://github.com/{{ app.github.full_name }}/releases)',
                'github.version'          => '[![GitHub version](https://badge.fury.io/gh/{{ app.github.vendor }}%2F{{ app.github.name }}.svg)](https://badge.fury.io/gh/{{ app.github.vendor }}%2F{{ app.github.name }})',
            ],
        ],
        'view' => [
            'theme' => [
                'pathMap' => [
                    '@hidev/views' => ['@hidev/readme/views'],
                ],
            ],
        ],
    ],
];

<?php
/**
 * README plugin for HiDev
 *
 * @link      https://github.com/hiqdev/hidev-readme
 * @package   hidev-readme
 * @license   BSD-3-Clause
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
 */

return [
    'controllerMap' => [
        'README' => [
            'class' => \hidev\readme\console\ReadmeController::class,
            'type' => 'text',
        ],
        'README.md' => [
            'class' => \hidev\readme\console\ReadmeController::class,
            'type' => 'markdown',
        ],
    ],
    'components' => [
        'readme' => [
            'class' => \hidev\readme\components\Readme::class,
            'knownBadges' => [
                'github.release'          => '[![GitHub release](https://img.shields.io/github/release/{{ app.github.full_name }}.svg)](https://github.com/{{ app.github.full_name }}/releases)',
                'github.version'          => '[![GitHub version](https://badge.fury.io/gh/{{ app.github.vendor }}%2F{{ app.github.name }}.svg)](https://badge.fury.io/gh/{{ app.github.vendor }}%2F{{ app.github.name }})',
            ],
        ],
        'view' => [
            'theme' => [
                'pathMap' => [
                    '@hidev/views' => [dirname(__DIR__) . '/src/views'],
                ],
            ],
        ],
    ],
];

Use real path for views instead of alias


<?php
/*
Plugin Name: Comment Timeout
Plugin URI: http://www.jamesmckay.net/code/comment-timeout/
Description: Automatically closes comments on blog entries after a user-configurable period of time. It has options which allow you to keep the discussion open for longer on older posts which have had recent comments accepted, or to place a fixed limit on the total number of comments in the discussion. Activate the plugin and go to Options >> Comment Timeout to configure.
Version: 2.1.1
Author: James McKay
Author URI: http://www.jamesmckay.net/
*/

define('COMMENT_TIMEOUT_VERSION', '2.1.1');

if ((int)phpversion() < 5) {
	add_action('admin_notices', create_function('', 'echo \'

Comment Timeout no longer supports PHP 4. Please upgrade your server to PHP 5.2 or later.

\';'));
}
else {
	require_once(dirname(__FILE__) . '/comment-timeout/class.core.php');
}

<?php
/*
Plugin Name: Comment Timeout
Plugin URI: http://www.jamesmckay.net/code/comment-timeout/
Description: Automatically closes comments on blog entries after a user-configurable period of time. It has options which allow you to keep the discussion open for longer on older posts which have had recent comments accepted, or to place a fixed limit on the total number of comments in the discussion. Activate the plugin and go to Options >> Comment Timeout to configure.
Version: 2.1.1
Author: James McKay
Author URI: http://www.jamesmckay.net/
*/

define('COMMENT_TIMEOUT_VERSION', '2.1.1');

if (version_compare(phpversion(), '5.0', '<')) {
	add_action('admin_notices', create_function('', 'echo \'

Comment Timeout no longer supports PHP 4. Please upgrade your server to PHP 5.2 or later.

\';'));
}
else {
	require_once(dirname(__FILE__) . '/comment-timeout/class.core.php');
}

Use version_compare for PHP version verification.


<?php

namespace OldSound\RabbitMqBundle\RabbitMq;

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

class Consumer extends BaseConsumer
{
    public function consume($msgAmount)
    {
        $this->target = $msgAmount;

        $this->setUpConsumer();

        while (count($this->ch->callbacks))
        {
            $this->ch->wait();
        }
    }

    public function processMessage(AMQPMessage $msg)
    {
        try
        {
            call_user_func($this->callback, $msg);
            $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
            $this->consumed++;
            $this->maybeStopConsumer();
        }
        catch (\Exception $e)
        {
            throw $e;
        }
    }

}

<?php

namespace OldSound\RabbitMqBundle\RabbitMq;

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

class Consumer extends BaseConsumer
{
    public function consume($msgAmount)
    {
        $this->target = $msgAmount;

        $this->setUpConsumer();

        while (count($this->ch->callbacks))
        {
            $this->ch->wait();
        }
    }

    public function processMessage(AMQPMessage $msg)
    {
        try
        {
            // Remove message from queue only if callback return not false
            if (false !== call_user_func($this->callback, $msg))
            {
                $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
            }

            $this->consumed++;
            $this->maybeStopConsumer();
        }
        catch (\Exception $e)
        {
            throw $e;
        }
    }

}


<?php

namespace Enqueue\Consumption;

use Interop\Queue\Context;
use Interop\Queue\Processor;
use Interop\Queue\Queue as InteropQueue;

interface QueueConsumerInterface
{
    /**
     * In milliseconds.
     */
    public function setReceiveTimeout(int $timeout): void;

    /**
     * In milliseconds.
     */
    public function getReceiveTimeout(): int;

    public function getContext(): Context;

    /**
     * @param string|InteropQueue $queueName
     */
    public function bind($queueName, Processor $processor): self;

    /**
     * @param string|InteropQueue $queueName
     * @param mixed               $queue
     */
    public function bindCallback($queue, callable $processor): self;

    /**
     * Runtime extension - is an extension or a collection of extensions which could be set on runtime.
     * Here's a good example: @see LimitsExtensionsCommandTrait.
     *
     * @param ExtensionInterface|null $runtimeExtension
     *
     * @throws \Exception
     */
    public function consume(ExtensionInterface $runtimeExtension = null): void;
}

<?php

namespace Enqueue\Consumption;

use Interop\Queue\Context;
use Interop\Queue\Processor;
use Interop\Queue\Queue as InteropQueue;

interface QueueConsumerInterface
{
    /**
     * In milliseconds.
     */
    public function setReceiveTimeout(int $timeout): void;

    /**
     * In milliseconds.
     */
    public function getReceiveTimeout(): int;

    public function getContext(): Context;

    /**
     * @param string|InteropQueue $queueName
     */
    public function bind($queueName, Processor $processor): self;

    /**
     * @param string|InteropQueue $queueName
     */
    public function bindCallback($queueName, callable $processor): self;

    /**
     * Runtime extension - is an extension or a collection of extensions which could be set on runtime.
     * Here's a good example: @see LimitsExtensionsCommandTrait.
     *
     * @param ExtensionInterface|null $runtimeExtension
     *
     * @throws \Exception
     */
    public function consume(ExtensionInterface $runtimeExtension = null): void;
}

Fix deprecation notice: The method bindCallback will require a new argument in next major version

back_consumer_1   | consumer1 | [2019-05-24 12:57:13] php.INFO: User
Deprecated: The "Enqueue\Consumption\QueueConsumer::bindCallback()"
method will require a new "string|InteropQueue $queueName" argument in
the next major version of its parent class
"Enqueue\Consumption\QueueConsumerInterface", not defining it is
deprecated. {"exception":"[object] (ErrorException(code: 0): User
Deprecated: The \"Enqueue\\Consumption\\QueueConsumer::bindCallback()\"
method will require a new \"string|InteropQueue $queueName\" argument in
the next major version of its parent class
\"Enqueue\\Consumption\\QueueConsumerInterface\", not defining it is
deprecated. at /app/vendor/symfony/debug/DebugClassLoader.php:199)"} []


<?php

namespace Application\Module {

    class User extends \Application\Module {
        public function Index() {
            return $this->Login();
        }

        public function Login() {
            $Request = $this->getRequest();
            $User = $this->getModel("User");
            if (isset($Request['Arguments']['Email']) && $Request['Arguments']['Email'] !== "") {
                $User->setEmail($Request['Arguments']['Email']);
            }
            if (isset($Request['Arguments']['Password']) && $Request['Arguments']['Password'] !== "") {
                $User->setPassword($Request['Arguments']['Password']);
            }

            $Error = null;

            $Email = $User->getEmail();
            $Password = $User->getPassword();

            if (isset($Email)) ;
            else {
                $Error = "No email given.";
            };
            if (isset($Password)) ;
            else {
                $Error = "No password given.";
            }

            $User->Error = $Error;

            $View = $this->getView("Login.phtml", array("User" => $User));

            return $View;
        }

        protected function Info() {
            $User = $this->getModel("User");
            $View = $this->getView("User.phtml", array("User" => $User));

            return $View;
        }
    }
}

?>

<?php

namespace Application\Module {

    class User extends \Application\Module {
        public function Index() {
            return $this->Login();
        }

        public function Login() {
            $Request = $this->getRequest();
            $User = $this->getModel("User");
            if (!empty($Request['Arguments']['Email'])) {
                $User->setEmail($Request['Arguments']['Email']);
            }
            if (!empty($Request['Arguments']['Password'])) {
                $User->setPassword($Request['Arguments']['Password']);
            }

            $Error = null;

            $Email = $User->getEmail();
            $Password = $User->getPassword();

            if (isset($Email)) ;
            else {
                $Error = "No email given.";
            };
            if (isset($Password)) ;
            else {
                $Error = "No password given.";
            }

            $User->Error = $Error;

            $View = $this->getView("Login.phtml", array("User" => $User));

            return $View;
        }

        protected function Info() {
            $User = $this->getModel("User");
            $View = $this->getView("User.phtml", array("User" => $User));

            return $View;
        }
    }
}

?>

Fix email and password validation.

Fix email and password validation.


<?php

namespace Symfony\Cmf\Bundle\BlockBundle\Document;

use Doctrine\ODM\PHPCR\Mapping\Annotations as PHPCRODM;
use Doctrine\ODM\PHPCR\ChildrenCollection;
use Doctrine\Common\Collections\ArrayCollection;
use Sonata\BlockBundle\Model\BlockInterface;

/**
 * Block that contains other blocks ...
 *
 * @PHPCRODM\Document(referenceable=true)
 */
class ContainerBlock extends BaseBlock
{
    /** @PHPCRODM\Children */
    protected  $children;

    public function getType()
    {
        return 'symfony_cmf.block.container';
    }

    public function getChildren()
    {
        return $this->children;
    }

    public function setChildren(ChildrenCollection $children)
    {
        return $this->children = $children;
    }

    /**
     * Add a child to this container
     *
     * @param  BlockInterface $child
     * @param  string $key OPTIONAL
     * @return boolean
     */
    public function addChild(BlockInterface $child, $key = null)
    {
        if (null === $this->children) {
            $this->children = new ArrayCollection();
        }
        if ($key != null) {
            return $this->children->set($key, $child);
        }

        return $this->children->add($child);
    }
}

<?php

namespace Symfony\Cmf\Bundle\BlockBundle\Document;

use Doctrine\ODM\PHPCR\Mapping\Annotations as PHPCRODM;
use Doctrine\ODM\PHPCR\ChildrenCollection;
use Doctrine\Common\Collections\ArrayCollection;
use Sonata\BlockBundle\Model\BlockInterface;

/**
 * Block that contains other blocks ...
 *
 * @PHPCRODM\Document(referenceable=true)
 */
class ContainerBlock extends BaseBlock
{
    /** @PHPCRODM\Children */
    protected  $children;

    public function __construct($name = null)
    {
        $this->setName($name);
        $this->children = new ArrayCollection();
    }

    /**
     * {@inheritdoc}
     */
    public function getType()
    {
        return 'symfony_cmf.block.container';
    }

    public function getChildren()
    {
        return $this->children;
    }

    public function setChildren(ChildrenCollection $children)
    {
        return $this->children = $children;
    }

    /**
     * Add a child to this container
     *
     * @param  BlockInterface $child
     * @param  string $key OPTIONAL
     * @return boolean
     */
    public function addChild(BlockInterface $child, $key = null)
    {
        if ($key != null) {
            return $this->children->set($key, $child);
        }

        return $this->children->add($child);
    }
}

Refactor children initialisation in constructor


<?php

class CM_Response_Resource_Javascript_LibraryTest extends CMTest_TestCase {

    protected function setUp() {
        CMTest_TH::createLanguage();
    }

    protected function tearDown() {
        CMTest_TH::clearEnv();
    }

    public function testProcessLibrary() {
        $render = new CM_Frontend_Render(new CM_Frontend_Environment());
        $request = new CM_Request_Get($render->getUrlResource('library-js', 'library.js'));
        $response = new CM_Response_Resource_Javascript_Library($request);
        $response->process();
        $this->assertContains('function()', $response->getContent());
    }

    public function testProcessTranslations() {
        $render = new CM_Frontend_Render(new CM_Frontend_Environment());
        $request = new CM_Request_Get($render->getUrlResource('library-js', 'translations/123.js'));
        $response = new CM_Response_Resource_Javascript_Library($request);
        $response->process();
        $this->assertContains('cm.language.setAll', $response->getContent());
    }
}

<?php

class CM_Response_Resource_Javascript_LibraryTest extends CMTest_TestCase {

    /** @var CM_File */
    private $_configInternalFile;

    protected function setUp() {
        CMTest_TH::createLanguage();

        $this->_configInternalFile = new CM_File(DIR_ROOT . 'resources/config/js/internal.js');
        $this->_configInternalFile->write('console.log("hello world")');
    }

    protected function tearDown() {
        CMTest_TH::clearEnv();

        $this->_configInternalFile->delete();
    }

    public function testProcessLibrary() {
        $render = new CM_Frontend_Render(new CM_Frontend_Environment());
        $request = new CM_Request_Get($render->getUrlResource('library-js', 'library.js'));
        $response = new CM_Response_Resource_Javascript_Library($request);
        $response->process();
        $this->assertContains('function()', $response->getContent());
    }

    public function testProcessTranslations() {
        $render = new CM_Frontend_Render(new CM_Frontend_Environment());
        $request = new CM_Request_Get($render->getUrlResource('library-js', 'translations/123.js'));
        $response = new CM_Response_Resource_Javascript_Library($request);
        $response->process();
        $this->assertContains('cm.language.setAll', $response->getContent());
    }
}

Create internal.js config for javascript library test


<?php

/*
 * This file is part of Zippy.
 *
 * (c) Alchemy <info@alchemy.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Alchemy\Zippy\FileStrategy;

use Alchemy\Zippy\Adapter\AdapterContainer;

class ZipFileStrategy implements FileStrategyInterface
{
    private $container;

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

    /**
     * {@inheritdoc}
     */
    public function getAdapters()
    {
        return array(
            $this->container['Alchemy\\Zippy\\Adapter\\ZipExtensionAdapter'],
            $this->container['Alchemy\\Zippy\\Adapter\\ZipAdapter'],
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getFileExtension()
    {
        return 'zip';
    }
}

<?php

/*
 * This file is part of Zippy.
 *
 * (c) Alchemy <info@alchemy.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Alchemy\Zippy\FileStrategy;

use Alchemy\Zippy\Adapter\AdapterContainer;

class ZipFileStrategy implements FileStrategyInterface
{
    private $container;

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

    /**
     * {@inheritdoc}
     */
    public function getAdapters()
    {
        return array(
            $this->container['Alchemy\\Zippy\\Adapter\\ZipAdapter'],
            $this->container['Alchemy\\Zippy\\Adapter\\ZipExtensionAdapter'],
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getFileExtension()
    {
        return 'zip';
    }
}

Use binary zip adapter prior to ZIpExtension


<?php

namespace WP_Migrations\OptionVersions;

class Provider
{
    protected $repository;

    public function __construct(Repository $optionVersionRepository)
    {
        $this->repository = $optionVersionRepository;
    }

    public function init()
    {
        add_action('updated_option', [$this, 'updated_option'], 1, 3);
        add_action('admin_menu', [$this, 'optionversions_menu']);
    }

    public function updated_option($option,$old_value, $new_value)
    {
        if ($option[0] == '_') {
            return;
        }
        if ('wp-migrations-plugin-options' !== $option) {
            return;
        }

        $serialized_option = maybe_serialize( $new_value );

        $this->repository->log($option,$serialized_option,get_current_user_id());
    }

    public function optionversions_menu(){
        $title = __("Option Versions",'wp-migrations');
        add_management_page( $title, $title, 'manage_options', 'optionversions', [$this,'toolsPage'] );
    }

    public function toolsPage(){
        if( ! class_exists( 'WP_List_Table' ) ) {
            require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
        }

        $listTable = new ListTable();
        $listTable->prepare_items();

        include('assets/toolspage.php');
    }

}

<?php

namespace WP_Migrations\OptionVersions;

class Provider
{
    protected $repository;

    public function __construct(Repository $optionVersionRepository)
    {
        $this->repository = $optionVersionRepository;
    }

    public function init()
    {
        add_action('updated_option', [$this, 'updated_option'], 1, 3);
        add_action('admin_menu', [$this, 'optionversions_menu']);
    }

    public function updated_option($option,$old_value, $new_value)
    {
        if ($option[0] == '_') {
            return;
        }
        if ('wp-migrations-plugin-options' === $option) {
            return;
        }

        $serialized_option = maybe_serialize( $new_value );

        $this->repository->log($option,$serialized_option,get_current_user_id());
    }

    public function optionversions_menu(){
        $title = __("Option Versions",'wp-migrations');
        add_management_page( $title, $title, 'manage_options', 'optionversions', [$this,'toolsPage'] );
    }

    public function toolsPage(){
        if( ! class_exists( 'WP_List_Table' ) ) {
            require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
        }

        $listTable = new ListTable();
        $listTable->prepare_items();

        include('assets/toolspage.php');
    }

}

Fix blocking all options except OptionValues


<?php

namespace Yajra\CMS\DataTables;

use Yajra\Acl\Models\Role;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Services\DataTable;

class RolesDataTable extends DataTable
{
    /**
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->columns(trans('cms::role.dataTable.columns'))
                    ->minifiedAjax()
                    ->parameters(trans('cms::role.dataTable.parameters'));
    }

    /**
     * @return string
     */
    protected function filename()
    {
        return trans('cms::role.dataTable.filename');
    }

    /**
     * Build DataTable api response.
     *
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable()
    {
        return (new EloquentDataTable($this->query()))
            ->editColumn('system', function (Role $role) {
                return dt_check($role->system);
            })
            ->addColumn('users', function (Role $role) {
                return view('administrator.roles.datatables.users', compact('role'));
            })
            ->addColumn('permissions', function (Role $role) {
                return view('administrator.roles.datatables.permissions', compact('role'));
            })
            ->addColumn('action', 'administrator.roles.datatables.action')
            ->rawColumns(['system', 'users', 'permissions', 'action']);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query()
    {
        return $this->applyScopes(Role::query()->withCount('users')->withCount('permissions'));
    }
}

<?php

namespace Yajra\CMS\DataTables;

use Yajra\Acl\Models\Role;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Services\DataTable;

class RolesDataTable extends DataTable
{
    /**
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->columns(trans('cms::role.dataTable.columns'))
                    ->minifiedAjax()
                    ->parameters(trans('cms::role.dataTable.parameters'));
    }

    /**
     * @return string
     */
    protected function filename()
    {
        return trans('cms::role.dataTable.filename');
    }

    /**
     * Build DataTable api response.
     *
     * @param \Yajra\Acl\Models\Role $role
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable(Role $role)
    {
        $model = $role->newQuery()->withCount('users')->withCount('permissions');

        return (new EloquentDataTable($model))
            ->editColumn('system', function (Role $role) {
                return dt_check($role->system);
            })
            ->addColumn('users', function (Role $role) {
                return view('administrator.roles.datatables.users', compact('role'));
            })
            ->addColumn('permissions', function (Role $role) {
                return view('administrator.roles.datatables.permissions', compact('role'));
            })
            ->addColumn('action', 'administrator.roles.datatables.action')
            ->rawColumns(['system', 'users', 'permissions', 'action']);
    }
}

Implement method injection to fetch the query.


<?php
/**
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010-2013 Justin Hileman
 * @copyright Modifications are Copyright (c) 2013-2014 Vanilla Forums Inc.
 * @license MIT
 * @package Snidely
 * @link https://github.com/bobthecow/mustache.php/blob/master/src/Mustache/Parser.php Original file.
 */

namespace Snidely;

/**
 * Snidely syntax exception.
 */
class SyntaxException extends \Exception {
    protected $token;

    public function __construct($msg, array $token) {
        $this->token = $token;
        parent::__construct($msg);
    }

    public function getToken() {
        return $this->token;
    }

}

<?php
/**
 * @author Todd Burry <todd@vanillaforums.com>
 * @copyright 2010-2013 Justin Hileman
 * @copyright Modifications are Copyright (c) 2013-2014 Vanilla Forums Inc.
 * @license MIT
 * @package Snidely
 * @link https://github.com/bobthecow/mustache.php/blob/master/src/Mustache/Parser.php Original file.
 */

namespace Snidely;

/**
 * Snidely syntax exception.
 */
class SyntaxException extends \Exception {
    protected $token;

    public function __construct($msg, array $token) {
        $this->token = $token;
        parent::__construct($msg, 400);
    }

    public function getToken() {
        return $this->token;
    }

}

Make a SnytaxException a 400 error code.


<?php

include("file.php");

$experiment = new Experiment($_REQUEST['exp']);

$page_header = $experiment->getName();

if ($experiment->getStatus() != 'open') {
  $page = 'fully_subscribed';
}
else {

  $excluded_email_addresses = $experiment->getExclusionEmails();

  foreach ($experiment->getExclusions() as $exclusion) {
    $alt_experiment = new Experiment($exclusion);
    $excluded_email_addresses = array_merge($excluded_email_addresses, $alt_experiment->getExclusionEmails());
  }

  if (in_array($_REQUEST['email'], $excluded_email_addresses)) {
    $page = 'not_eligible';
    $user = new User($experiment->owner);
  }

  else {
    if ($experiment->getPerSlot() > 1) {
      $additional_message = "This experiment requires {$experiment->getPerSlot()} participants per timeslot. You will not be guaranteed a place on the experiment until {$experiment->getPerSlot()} people have signed up for your slot. If possible, please choose a slot that someone else has already signed up for (highlighted in green). You’ll receive an email to confirm when your slot has been filled.";
    }
  }

}

?>

<?php

include("file.php");

$experiment = new Experiment($_REQUEST['exp']);

$page_header = $experiment->getName();

if ($experiment->getStatus() != 'open') {
  $page = 'fully_subscribed';
}
else {

  $excluded_email_addresses = $experiment->getExclusionEmails();

  foreach ($experiment->getExclusions() as $exclusion) {
    $alt_experiment = new Experiment($exclusion);
    $excluded_email_addresses = array_merge($excluded_email_addresses, $alt_experiment->getExclusionEmails());
  }

  if (in_array(strtolower($_REQUEST['email']), $excluded_email_addresses)) {
    $page = 'not_eligible';
    $user = new User($experiment->owner);
  }

  else {
    if ($experiment->getPerSlot() > 1) {
      $additional_message = "This experiment requires {$experiment->getPerSlot()} participants per timeslot. You will not be guaranteed a place on the experiment until {$experiment->getPerSlot()} people have signed up for your slot. If possible, please choose a slot that someone else has already signed up for (highlighted in green). You’ll receive an email to confirm when your slot has been filled.";
    }
  }

}

?>

Make email lower case before checking exclusions


    <a class="brand" href="<?php echo home_url(); ?>/"><?php bloginfo('name'); ?>

      <?php
        if (has_nav_menu('primary_navigation')) :
          wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_class' => 'nav nav-pills'));
        endif;
      ?>

    <a class="brand" href="<?php echo home_url('/') ?>"><?php bloginfo('name'); ?>

      <?php
        if (has_nav_menu('primary_navigation')) :
          wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_class' => 'nav nav-pills'));
        endif;
      ?>

Add trailing slash using the parameter

Add trailing slash using the  parameter


<?php

require_once 'lib/Config.php';
require_once 'lib/Session.php';
require_once 'lib/functions.php';

require_once 'lib/Slim/Slim.php';

\Slim\Slim::registerAutoloader();

$db = new PDO(Config::get('datasource'));
$app = new \Slim\Slim();

/* Index */
$app->get('/', function() use ($app) {
   $app->redirect('https://decke.github.io/redports/', 301);
});

/* Jobs */
$app->get('/api/jobs/:jobid', 'isAllowed', function($jobid) use ($app) {
   $app->response->headers->set('Content-Type', 'application/json');
   $app->response->write(json_encode(array("jobid" => $jobid)));
})->conditions(array('jobid' => '[0-9]{1,}'));

$app->run();

<?php

require_once 'lib/Config.php';
require_once 'lib/Session.php';
require_once 'lib/functions.php';

require_once 'lib/Slim/Slim.php';

\Slim\Slim::registerAutoloader();

$db = new PDO(Config::get('datasource'));
$app = new \Slim\Slim();

/* Index */
$app->get('/', function() use ($app) {
   $app->redirect('https://decke.github.io/redports/', 301);
});

/* GitHub Webhooks */
$app->post('/github/', function() use ($app) {
   switch($app->request->headers->get('X-GitHub-Event'))
   {
      case 'ping':
         $app->response->write('pong');
      break;
      case 'push':
         $app->response->write('Push event not implemented yet');
      break;
      default:
         $app->response->write('Event type not implemented');
      break;
   }
});

/* Jobs */
$app->get('/api/jobs/:jobid', 'isAllowed', function($jobid) use ($app) {
   $app->response->headers->set('Content-Type', 'application/json');
   $app->response->write(json_encode(array("jobid" => $jobid)));
})->conditions(array('jobid' => '[0-9]{1,}'));

$app->run();

Add simple stub for GitHub Webhooks

Add simple stub for GitHub Webhooks


<?php

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

// select_month.php Chris Dart Dec 29, 2013 5:04:43 PM
// chrisdart@cerebratorium.com
$buttons[] = array(
        "item" => "expense",
        "text" => "Go",
        "type" => "span",
        "class" => "button go-to-month"
);
$buttons[] = array(
        "item" => "expense",
        "text" => "Current Month",
        "type" => "span",
        "class" => "button show-current-month"
);

?>

<?php echo form_dropdown("search-month",$month_list,$default_month,"id='search-month'");?>
 <input
			type="text"
			size="5"
			maxlength="4"
			id="search-year"
			name="search-year"
			value="<?php echo $default_year;?>" />

		<?php echo create_button_bar($buttons);?>

<?php

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

// select_month.php Chris Dart Dec 29, 2013 5:04:43 PM
// chrisdart@cerebratorium.com
$buttons[] = array(
        "item" => "expense",
        "text" => "Go",
        "type" => "span",
        "class" => "button btn btn-sm btn-primary go-to-month"
);
$buttons[] = array(
        "item" => "expense",
        "text" => "Current Month",
        "type" => "span",
        "class" => "button btn btn-sm btn-primary show-current-month"
);

?>

<?php echo form_dropdown("search-month",$month_list,$default_month,"id='search-month'");?>
 <input
			type="text"
			size="5"
			maxlength="4"
			id="search-year"
			name="search-year"
			value="<?php echo $default_year;?>" />

		<?php echo create_button_bar($buttons);?>

Update theming for select month view

Update theming for select month view


<?php

namespace Blogger\BlogBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class PageControllerTest extends WebTestCase
{
    public function testAbout()
    {
        $client = static::createClient();

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

        $this->assertEquals(1, $crawler->filter('h1:contains("Про автора Blogger 2015")')->count());
    }

    public function testIndex()
    {
        $client = static::createClient();

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

        // Check there are some blog entries on the page
        $this->assertTrue($crawler->filter('article.blog')->count() >0);

        // Find the first link, get the title, ensure this is loaded on the next page
        $blogLink   = $crawler->filter('article.blog h2 a')->first();
        $blogTitle  = $blogLink->text();
        $crawler    = $client->click($blogLink->link());
    }
}

<?php

namespace Blogger\BlogBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class PageControllerTest extends WebTestCase
{
    public function testAbout()
    {
        $client = static::createClient();

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

        $this->assertEquals(1, $crawler->filter('h1:contains("Про автора Blogger 2015")')->count());
    }

    public function testIndex()
    {
        $client = static::createClient();

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

        // Check there are some blog entries on the page
        $this->assertTrue($crawler->filter('article.blog')->count() >0);

        // Find the first link, get the title, ensure this is loaded on the next page
        $blogLink   = $crawler->filter('article.blog h2 a')->first();
        $blogTitle  = $blogLink->text();
        $crawler    = $client->click($blogLink->link());

        // Check the h2 has the blog title in it
        $this->assertEquals(1, $crawler->filter('h2:contains("' . $blogTitle .'")')->count());
    }
}

Check the h2 has the blog title in it

Check the h2 has the blog title in it


<?php

namespace Sentry\Laravel\Integration;

use Sentry\Event;
use Sentry\EventHint;
use Sentry\State\Scope;
use Sentry\Integration\IntegrationInterface;

class ExceptionContextIntegration implements IntegrationInterface
{
    public function setupOnce(): void
    {
        Scope::addGlobalEventProcessor(static function (Event $event, ?EventHint $hint = null): Event {
            if ($hint === null || $hint->exception === null) {
                return $event;
            }

            if (!method_exists($hint->exception, 'context')) {
                return $event;
            }

            $context = $hint->exception->context();

            if (is_array($context)) {
                $event->setExtra(['exception_context' => $context]);
            }

            return $event;
        });
    }
}

<?php

namespace Sentry\Laravel\Integration;

use Sentry\Event;
use Sentry\EventHint;
use Sentry\SentrySdk;
use Sentry\State\Scope;
use Sentry\Integration\IntegrationInterface;

class ExceptionContextIntegration implements IntegrationInterface
{
    public function setupOnce(): void
    {
        Scope::addGlobalEventProcessor(static function (Event $event, ?EventHint $hint = null): Event {
            $self = SentrySdk::getCurrentHub()->getIntegration(self::class);

            if (!$self instanceof self) {
                return $event;
            }

            if ($hint === null || $hint->exception === null) {
                return $event;
            }

            if (!method_exists($hint->exception, 'context')) {
                return $event;
            }

            $context = $hint->exception->context();

            if (is_array($context)) {
                $event->setExtra(['exception_context' => $context]);
            }

            return $event;
        });
    }
}

Add some boilerplate checks to the exception context integration


<?php
// (c) Copyright 2002-2017 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

function prefs_sitemap_list()
{
	return array(
		'sitemap_enable' => array(
			'name' => tra('Sitemap protocol'),
			'description' => tra('Allows generating site maps based on the Sitemap protocol, in the form of XML documents. Mostly used to facilitate indexation of a site by web search engines.'),
			'type' => 'flag',
			'help' => 'https://www.sitemaps.org/protocol.html',
			'default' => 'n',
			'size' => '18',
			'tags' => array('advanced'),
		),
	);
}

<?php
// (c) Copyright 2002-2017 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

function prefs_sitemap_list()
{
	return array(
		'sitemap_enable' => array(
			'name' => tra('Sitemap protocol'),
			'description' => tra('Allows generating site maps based on the Sitemap protocol, in the form of XML documents. Mostly used to facilitate indexation of a site by web search engines.'),
			'type' => 'flag',
			'help' => 'https://www.sitemaps.org/protocol.html',
			'default' => 'n',
			'since' => '18',
			'tags' => array('advanced'),
		),
	);
}

Fix typo should be since not size

[FIX] Fix typo should be since not size

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@63771 b456876b-0849-0410-b77d-98878d47e9d5


<?php namespace Dxi\Commands\Dataset\Contact;

use Dxi\Commands\Command;

class Create extends Command {

    /**
     * Get the payload for the command
     *
     * @return array
     */
    public function getRequiredParams()
    {
        return [
            'firstname',
            'dataset',
            [
                'ddi_home',
                'ddi_mobile',
                'ddi_work'
            ]
        ];
    }

    /**
     * Set the phone number
     *
     * @param $phone
     * @return $this
     */
    public function getPhone($phone)
    {
        $phoneType = (preg_match('/^(07|\+447)/', $phone, $ret) ? 'ddi_mobile' : 'ddi_home');
        $this->params[$phoneType] = $phone;
        return $this;
    }

    /**
     * Get the method for the command
     *
     * @return string
     */
    public function getMethod()
    {
        return 'ecnow_data';
    }

    /**
     * Get the url path
     *
     * @return string
     */
    public function getUrlPath()
    {
        return '/database.php';
    }

    /**
     * Get the action for the command
     *
     * @return string
     */
    public function getAction()
    {
        return strtolower(class_basename(__CLASS__));
    }
}

<?php namespace Dxi\Commands\Dataset\Contact;

use Dxi\Commands\Command;

class Create extends Command {

    /**
     * Get the payload for the command
     *
     * @return array
     */
    public function getRequiredParams()
    {
        return [
            'firstname',
            'dataset',
            [
                'ddi_home',
                'ddi_mobile',
                'ddi_work'
            ]
        ];
    }

    /**
     * Set the phone number
     *
     * @param $phone
     * @return $this
     */
    public function getPhone($phone)
    {
        $phoneType = (preg_match('/^(07|\+447)/', $phone, $ret) ? 'ddi_mobile' : 'ddi_home');
        $this->params[$phoneType] = $phone;
        return $this;
    }

    /**
     * Get the method for the command
     *
     * @return string
     */
    public function getMethod()
    {
        return 'ecnow_records';
    }

    /**
     * Get the url path
     *
     * @return string
     */
    public function getUrlPath()
    {
        return '/ecnow.php';
    }

    /**
     * Get the action for the command
     *
     * @return string
     */
    public function getAction()
    {
        return strtolower(class_basename(__CLASS__));
    }
}

Change api endpoints due to undocumented breaking changes


<?php

/**
 * @file
 * Contains \Eloqua\Api\DestroyableInterface
 */

namespace Eloqua\Api;

interface DestroyableInterface {

  /**
   * Delete a record of this type.
   *
   * @param array $id
   *   The ID of the individual record to be destroyed.
   *
   * @return null
=   */
  public function remove($id);

}

<?php

/**
 * @file
 * Contains \Eloqua\Api\DestroyableInterface
 */

namespace Eloqua\Api;

interface DestroyableInterface {

  /**
   * Delete a record of this type.
   *
   * @param array $id
   *   The ID of the individual record to be destroyed.
   *
   * @return null
   */
  public function remove($id);

}

Fix a minor typo inside comment block

Fix a minor typo inside comment block


<?php

namespace GeoJson\Geometry;

/**
 * Polygon geometry object.
 *
 * Coordinates consist of an array of LinearRing coordinates.
 *
 * @see http://www.geojson.org/geojson-spec.html#polygon
 * @since 1.0
 */
class Polygon extends Geometry
{
    protected $type = 'Polygon';

    /**
     * Constructor.
     *
     * @param float[][][]|LinearRing[] $linearRings
     * @param CoordinateResolutionSystem|BoundingBox $arg,...
     */
    public function __construct(array $linearRings)
    {
        $this->coordinates = array_map(
            function($linearRing) {
                if ( ! $linearRing instanceof LinearRing) {
                    $linearRing = new LinearRing($linearRing);
                }

                return $linearRing->getCoordinates();
            },
            $linearRings
        );

        if (func_num_args() > 1) {
            $this->setOptionalConstructorArgs(array_slice(func_get_args(), 1));
        }
    }
}

<?php

namespace GeoJson\Geometry;

/**
 * Polygon geometry object.
 *
 * Coordinates consist of an array of LinearRing coordinates.
 *
 * @see http://www.geojson.org/geojson-spec.html#polygon
 * @since 1.0
 */
class Polygon extends Geometry
{
    protected $type = 'Polygon';

    /**
     * Constructor.
     *
     * @param float[][][]|LinearRing[] $linearRings
     * @param CoordinateResolutionSystem|BoundingBox $arg,...
     */
    public function __construct(array $linearRings)
    {
        foreach ($linearRings as $linearRing) {
            if ( ! $linearRing instanceof LinearRing) {
                $linearRing = new LinearRing($linearRing);
            }
            $this->coordinates[] = $linearRing->getCoordinates();
        }

        if (func_num_args() > 1) {
            $this->setOptionalConstructorArgs(array_slice(func_get_args(), 1));
        }
    }
}

Fix php warning on LinearRing creation with invalid params


<?php

namespace Vinkla\Base62;

class Base62
{
	/**
	 * The base string.
	 *
	 * @var string
	 */
	protected $base;

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

	/**
	 * Decode a string to a integer.
	 *
	 * @param string $value
	 * @param int $b
	 * @return int
	 */
	public function decode($value, $b = 62)
	{
		$limit = strlen($value);
		$result = strpos($this->base, $value[0]);

		for ($i = 1; $i < $limit; $i++)
		{
			$result = $b * $result + strpos($this->base, $value[$i]);
		}

		return $result;
	}

	/**
	 * Encode an integer to a string.
	 *
	 * @param int $value
	 * @param int $b
	 * @return string
	 */
	public function encode($value, $b = 62)
	{
		$r = (int) $value % $b;
		$result = $this->base[$r];
		$q = floor((int) $value / $b);

		while ($q)
		{
			$r = $q % $b;
			$q = floor($q / $b);
			$result = $this->base[$r] . $result;
		}

		return $result;
	}
}

Fix new line on while and for statements.


<?php

namespace Guttmann\SilverStripe;

use Extension;
use Subsite;

class MenuAdminExtension extends Extension
{

    public function updateEditForm($form)
    {
        $gridField = $form->Fields()->fieldByName('MenuSet');

        $list = $gridField->getList();
        $filteredList = $list->filter(array(
            'SubsiteID' => Subsite::currentSubsiteID()
        ));

        $gridField->setList($filteredList);
    }

}

<?php

namespace Guttmann\SilverStripe;

use Extension;
use Subsite;

class MenuAdminExtension extends Extension
{

    public function updateEditForm($form)
    {
        $gridField = $form->Fields()->fieldByName('MenuSet');

        if($gridField) {
            $list = $gridField->getList();
            $filteredList = $list->filter(array(
                'SubsiteID' => Subsite::currentSubsiteID()
            ));

            $gridField->setList($filteredList);
        }

    }

}

BUGFIX: Check that the MenuSet gridfield exists before filtering


<?php return [

	'listing.pending_save' => ' You must save before you can add :model.',

	'actions.save_new' => 'Go to create form after saving',
	'actions.save_back' => 'Return to listing after saving',

];

Fix PSR-2 for language file(s)

Fix PSR-2 for language file(s)


<?php
namespace App\Model\Table;

use CakeDC\Users\Model\Table\UsersTable as Table;
use CsvMigrations\ConfigurationTrait;
use CsvMigrations\FieldTrait;

/**
 * Users Model
 */
class UsersTable extends Table
{
    use ConfigurationTrait;
    use FieldTrait;

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        // set table/module configuration
        $this->_setConfiguration($this->table());
    }
}

<?php
namespace App\Model\Table;

use CakeDC\Users\Model\Table\UsersTable as Table;
use CsvMigrations\ConfigurationTrait;
use CsvMigrations\FieldTrait;

/**
 * Users Model
 */
class UsersTable extends Table
{
    use ConfigurationTrait;
    use FieldTrait;

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        // set table/module configuration
        $this->setConfig($this->table());
    }
}

Fix setting of configuration on custom Users table


<?php

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

class UpdateForumTableCategories extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('forum_categories', function (Blueprint $table)
        {
            $table->renameColumn('parent_category', 'category_id');
            $table->renameColumn('subtitle', 'description');
        });

        Schema::table('forum_categories', function (Blueprint $table)
        {
            $table->integer('category_id')->default(0)->change();
            $table->string('subtitle')->nullable()->change();
            $table->integer('weight')->default(0)->change();

            $table->boolean('enable_threads')->default(0);
            $table->boolean('private')->default(0);

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('forum_categories', function (Blueprint $table)
        {
            $table->renameColumn('category_id', 'parent_category');
            $table->dropColumn(['created_at', 'updated_at', 'enable_threads', 'private']);
            $table->renameColumn('description', 'subtitle');
        });
    }
}

<?php

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

class UpdateForumTableCategories extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('forum_categories', function (Blueprint $table)
        {
            $table->renameColumn('parent_category', 'category_id');
            $table->renameColumn('subtitle', 'description');
        });

        Schema::table('forum_categories', function (Blueprint $table)
        {
            $table->integer('category_id')->default(0)->change();
            $table->string('description')->nullable()->change();
            $table->integer('weight')->default(0)->change();

            $table->boolean('enable_threads')->default(0);
            $table->boolean('private')->default(0);

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('forum_categories', function (Blueprint $table)
        {
            $table->renameColumn('category_id', 'parent_category');
            $table->dropColumn(['created_at', 'updated_at', 'enable_threads', 'private']);
            $table->renameColumn('description', 'subtitle');
        });
    }
}

Correct column name in migration

Correct column name in migration


<?php namespace JohnRivs\Wunderlist;

trait Webhook {

    /**
     * Show all the webhooks for a list.
     *
     * @param  array $attributes
     * @return array
     */
    public function getWebhooks(array $attributes = [])
    {
        $this->requires(['list_id'], $attributes);

        return $this->call('GET', 'webhooks', ['query' => $attributes]);
    }

    /**
     * Create a webhook for a list.
     *
     * @param  array $attributes
     * @return array
     */
    public function createWebhook(array $attributes = [])
    {
        $this->requires(['list_id', 'url', 'processor_type', 'configuration'], $attributes);

        return $this->call('POST', 'webhooks', ['json' => $attributes]);
    }

    /**
     * Delete a webhook for a list.
     *
     * @param  int $webhookId The id of the webhook.
     * @return int
     */
    public function deleteWebhook($webhookId)
    {
        $this->call('DELETE', "webhooks/{$webhookId}");

        return $this->getStatusCode();
    }

    /**
     * Deletes all webhooks for a list.
     *
     * @param  $listId The id of the list.
     * @return int
     */
    public function deleteWebhooks($listId)
    {
        $webhooks = $this->getWebhooks($listId);

        foreach ($webhooks as $webhook) {
            $this->deleteWebhook($webhook['id']);
        }

        return $this->getStatusCode();
    }

}

<?php namespace JohnRivs\Wunderlist;

trait Webhook {

    /**
     * Show all the webhooks for a list.
     *
     * @param  array $attributes
     * @return array
     */
    public function getWebhooks(array $attributes = [])
    {
        $this->requires(['list_id'], $attributes);

        return $this->call('GET', 'webhooks', ['query' => $attributes]);
    }

    /**
     * Create a webhook for a list.
     *
     * @param  array $attributes
     * @return array
     */
    public function createWebhook(array $attributes = [])
    {
        $this->requires(['list_id', 'url', 'processor_type', 'configuration'], $attributes);

        return $this->call('POST', 'webhooks', ['json' => $attributes]);
    }

    /**
     * Delete a webhook for a list.
     *
     * @param  int $webhookId The id of the webhook.
     * @return int
     */
    public function deleteWebhook($webhookId)
    {
        $this->call('DELETE', "webhooks/{$webhookId}");

        return $this->getStatusCode();
    }

    /**
     * Deletes all webhooks for a list.
     *
     * @param  $listId The id of the list.
     * @return int
     */
    public function deleteWebhooks($listId)
    {
        $webhooks = $this->getWebhooks(['list_id' => $listId]);

        foreach ($webhooks as $webhook) {
            $this->deleteWebhook($webhook['id']);
        }

        return $this->getStatusCode();
    }

}

Fix deleting all webhooks for a list

Fix deleting all webhooks for a list


<?php

namespace Akhann\StaticPageBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

abstract class DefaultController extends Controller
{
    abstract public function getIndexTemplate();
    abstract public function getShowTemplateNamespace();

    public function indexAction()
    {
        return $this->render($this->getIndexTemplate());
    }

    public function showAction($pageId)
    {
        $template = $this->getShowTemplate($pageId);
        $templating = $this->get('templating');

        if (!$templating->exists($template))
        {
            throw $this->createNotFoundException(sprintf('Page not found. Create template %s', $template));
        }

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

    public function subShowAction($parentPageId, $pageId)
    {
        $template = $this->getShowTemplate($parentPageId, $pageId);
        $templating = $this->get('templating');

        if (!$templating->exists($template))
        {
            throw $this->createNotFoundException(sprintf('Page not found. Create template %s', $template));
        }

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

    protected function getShowTemplate($parentPageId, $pageId=null)
    {
        if (is_null($pageId)) {
            $pageId = $parentPageId;
        }

        $pageId = sprintf('%s_%s', $parentPageId, $pageId);

        return sprintf('%s:%s.html.twig', $this->getShowTemplateNamespace(), $pageId);
    }

}

<?php

namespace Akhann\StaticPageBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

abstract class DefaultController extends Controller
{
    abstract public function getIndexTemplate();
    abstract public function getShowTemplateNamespace();

    public function indexAction()
    {
        return $this->render($this->getIndexTemplate());
    }

    public function showAction($pageId)
    {
        $template = $this->getShowTemplate($pageId);
        $templating = $this->get('templating');

        if (!$templating->exists($template))
        {
            throw $this->createNotFoundException(sprintf('Page not found. Create template %s', $template));
        }

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

    public function subShowAction($parentPageId, $pageId)
    {
        $template = $this->getShowTemplate($parentPageId, $pageId);
        $templating = $this->get('templating');

        if (!$templating->exists($template))
        {
            throw $this->createNotFoundException(sprintf('Page not found. Create template %s', $template));
        }

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

    protected function getShowTemplate($parentPageId, $pageId=null)
    {
        if (is_null($pageId)) {
            $pageId = $parentPageId;
        }
        else {
            $pageId = sprintf('%s_%s', $parentPageId, $pageId);
        }

        return sprintf('%s:%s.html.twig', $this->getShowTemplateNamespace(), $pageId);
    }

}

Fix bug wrong pageId in showAction

Fix bug wrong pageId in showAction


<?php

require_once 'Site/exceptions/SiteNotFoundException.php';
require_once 'Site/layouts/SiteXMLRPCServerLayout.php';
require_once 'Site/SitePageFactory.php';

/**
 * @package   Site
 * @copyright 2006 silverorange
 */
abstract class SiteXMLRPCServerFactory extends SitePageFactory
{
	// {{{ public function resolvePage()

	public function resolvePage($app, $source)
	{
		$layout = $this->resolveLayout($app, $source);
		$map = $this->getPageMap();

		if (isset($map[$source])) {
			$class = $map[$source];
			$params = array($app, $layout);
			$page = $this->instantiatePage($class, $params);
			return $page;
		}

		throw new SiteNotFoundException();
	}

	// }}}
	// {{{ protected function resolveLayout()

	protected function resolveLayout($app, $source)
	{
		return new SiteXMLRPCServerLayout($app);
	}

	// }}}
}

?>

<?php

require_once 'Site/exceptions/SiteNotFoundException.php';
require_once 'Site/layouts/SiteXMLRPCServerLayout.php';
require_once 'Site/SitePageFactory.php';

/**
 * @package   Site
 * @copyright 2006 silverorange
 */
abstract class SiteXMLRPCServerFactory extends SitePageFactory
{
	// {{{ public function resolvePage()

	public function resolvePage(SiteWebApplication $app, $source)
	{
		$layout = $this->resolveLayout($app, $source);
		$map = $this->getPageMap();

		if (isset($map[$source])) {
			$class = $map[$source];
			$params = array($app, $layout);
			$page = $this->instantiatePage($class, $params);
			return $page;
		}

		throw new SiteNotFoundException();
	}

	// }}}
	// {{{ protected function resolveLayout()

	protected function resolveLayout($app, $source)
	{
		return new SiteXMLRPCServerLayout($app);
	}

	// }}}
}

?>

Make type-hinting in function signature mathc in subclass.

Is this going to be problem for system scripts too?

svn commit r13063


<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

class UploadModuleTest extends BackendWebTestCase
{
    public function testAuthenticationIsNeeded(Client $client): void
    {
        self::assertAuthenticationIsNeeded($client, '/private/en/extensions/upload_module');
    }

    public function testUploadPage(Client $client): void
    {
        $this->login($client);

        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/extensions/upload_module',
            [
                'Install',
                '<label for="file" class="custom-file-label">',
            ]
        );
    }
}

<?php

namespace Backend\Modules\ContentBlocks\Tests\Action;

use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

class UploadModuleTest extends BackendWebTestCase
{
    public function testAuthenticationIsNeeded(Client $client): void
    {
        self::assertAuthenticationIsNeeded($client, '/private/en/extensions/upload_module');
    }

    public function testUploadPage(Client $client): void
    {
        $this->login($client);

        self::assertPageLoadedCorrectly(
            $client,
            '/private/en/extensions/upload_module',
            [
                'Install',
                '<label for="file" class="form-label">',
            ]
        );
    }
}

Update test because the css class has changes by updating to Bootstrap5


<?php

namespace Artesaos\Zenvia\Contracts;

use Artesaos\Zenvia\Exceptions\ZenviaResponseException;
use Psr\Http\Message\ResponseInterface;

interface ResponseHandlerInterface
{

    /**
     * Convert a PSR-7 response to a data type you want to work with.
     *
     * @param ResponseInterface $response
     * @param string            $format
     *
     * @return ResponseInterface|\Psr\Http\Message\StreamInterface|\SimpleXMLElement|string
     *
     * @throws \InvalidArgumentException
     */
    public function convert(ResponseInterface $response, $format);

    /**
     * @param ResponseInterface $response
     *
     * @return string
     */
    public function convertToArray(ResponseInterface $response);

    /**
     * @param ResponseInterface $response
     *
     * @return \SimpleXMLElement
     *
     * @throws ZenviaResponseException
     */
    public function convertToSimpleXml(ResponseInterface $response);
}

<?php

namespace Artesaos\Zenvia\Contracts;

use Artesaos\Zenvia\Exceptions\ZenviaResponseException;
use Psr\Http\Message\ResponseInterface;

interface ResponseHandlerInterface
{

    /**
     * Convert a PSR-7 response to a data type you want to work with.
     *
     * @param ResponseInterface $response
     * @param string            $format
     *
     * @return ResponseInterface|\Psr\Http\Message\StreamInterface|\SimpleXMLElement|string
     *
     * @throws \InvalidArgumentException
     */
    public static function convert(ResponseInterface $response, $format);

    /**
     * @param ResponseInterface $response
     *
     * @return string
     */
    public static function convertToArray(ResponseInterface $response);

    /**
     * @param ResponseInterface $response
     *
     * @return \SimpleXMLElement
     *
     * @throws ZenviaResponseException
     */
    public static function convertToSimpleXml(ResponseInterface $response);
}

Add methods for convert responses

Add methods for convert responses


<?php
// This file patches test case files containing setUp and tearDown methods.
// It's a hacky workaround needed until we drop support of PHP < 7.2.
// Cause: newer PHPUnit has added typehints to its setUp and tearDown methods
// but ClosureTable 6.x must support PHP 5.6-7.0 as well,
// so we cannot use typehints by default.

if (PHP_VERSION_ID < 70100) {
    exit(0);
}

require_once './vendor/autoload.php';

use Symfony\Component\Finder\Finder;

$finder = new Finder();
$finder->files()
    ->ignoreVCS(false)
    ->in(__DIR__)
    ->name('*.php')
    ->notName('script-change-testcase-return-type.php')->contains('use Orchestra\Testbench\TestCase;');

foreach ($finder as $file) {
    $absoluteFilePath = $file->getRealPath();
    $contents = file_get_contents($path);
    $contents = str_replace(
        ['public function setUp()', 'public function tearDown()'],
        ['public function setUp(): void', 'public function tearDown(): void'],
        $contents
    );

    file_put_contents($path, $contents);
}

<?php
// This file patches test case files containing setUp and tearDown methods.
// It's a hacky workaround needed until we drop support of PHP < 7.2.
// Cause: newer PHPUnit has added typehints to its setUp and tearDown methods
// but ClosureTable 6.x must support PHP 5.6-7.0 as well,
// so we cannot use typehints by default.

if (PHP_VERSION_ID < 70100) {
    exit(0);
}

require_once './vendor/autoload.php';

use Symfony\Component\Finder\Finder;

$finder = new Finder();
$finder->files()
    ->ignoreVCS(false)
    ->in(__DIR__)
    ->name('*.php')
    ->notName('script-change-testcase-return-type.php')
    ->contains('use Orchestra\Testbench\TestCase;');

foreach ($finder as $file) {
    $path = $file->getRealPath();
    $contents = file_get_contents($path);
    $contents = str_replace(
        ['public function setUp()', 'public function tearDown()'],
        ['public function setUp(): void', 'public function tearDown(): void'],
        $contents
    );

    file_put_contents($path, $contents);
}

Update after rebase to use array approach


<?php

use Mockery as m;

class AcTestCase extends Orchestra\Testbench\TestCase
{
    protected $app;
    protected $router;

    public function tearDown()
    {
        parent::tearDown();
        m::close();
    }

    protected function mock($className)
    {
        $mock = m::mock($className);
        App::bind($className, function($app, $parameters = []) use($mock) {
            if(is_array($parameters) && is_array($attributes=array_get($parameters, 0, []))) {
                $mock = $this->fillMock($mock, $attributes);
            }

            return $mock;
        });

        return $mock;
    }

    protected function fillMock($mock, $attributes = [])
    {
        $instance = $mock->makePartial();
        foreach ($attributes as $key => $value) {
            $instance->$key = $value;
        }

        return $instance;
    }

    protected function getPackageProviders()
    {
        return [
            'Efficiently\AuthorityController\AuthorityControllerServiceProvider',
        ];
    }

    protected function getPackageAliases()
    {
        return [
            'Authority' => 'Efficiently\AuthorityController\Facades\Authority',
            'Params'    => 'Efficiently\AuthorityController\Facades\Params',
        ];
    }

}

<?php

use Mockery as m;

class AcTestCase extends Orchestra\Testbench\TestCase
{
    protected $app;
    protected $router;

    public function tearDown()
    {
        parent::tearDown();
        m::close();
    }

    protected function mock($className)
    {
        $mock = m::mock($className);
        App::bind($className, function($app, $parameters = []) use($mock) {
            if(is_array($parameters) && is_array($attributes=array_get($parameters, 0, [])) && respond_to($mock, "fill")) {
                $mock = $this->fillMock($mock, $attributes);
            }

            return $mock;
        });

        return $mock;
    }

    protected function fillMock($mock, $attributes = [])
    {
        $instance = $mock->makePartial();
        foreach ($attributes as $key => $value) {
            $instance->$key = $value;
        }

        return $instance;
    }

    protected function getPackageProviders()
    {
        return [
            'Efficiently\AuthorityController\AuthorityControllerServiceProvider',
        ];
    }

    protected function getPackageAliases()
    {
        return [
            'Authority' => 'Efficiently\AuthorityController\Facades\Authority',
            'Params'    => 'Efficiently\AuthorityController\Facades\Params',
        ];
    }

}

Add more security to the mock system who simulates Eloquent's constructor method.


<?php

// --------------------------
// Custom Backpack Routes
// --------------------------
// This route file is loaded automatically by Backpack\Base.
// Routes you generate using Backpack\Generators will be placed here.

Route::group([
    'prefix'     => config('backpack.base.route_prefix', 'admin'),
    'middleware' => [config('backpack.base.middleware_key', 'admin')],
    'namespace'  => 'App\Http\Controllers\Admin',
], function () { // custom admin routes
}); // this should be the absolute last line of this file

<?php

// --------------------------
// Custom Backpack Routes
// --------------------------
// This route file is loaded automatically by Backpack\Base.
// Routes you generate using Backpack\Generators will be placed here.

Route::group([
    'prefix'     => config('backpack.base.route_prefix', 'admin'),
    'middleware' => ['web', config('backpack.base.middleware_key', 'admin')],
    'namespace'  => 'App\Http\Controllers\Admin',
], function () { // custom admin routes
}); // this should be the absolute last line of this file

Add the web middleware stack

Add the web middleware stack

Couple of people on gitter have noticed the new `custom.php` does not load the `web` middleware, so login sessions don't work.

Maybe this was an oversight or intentional?

Either way either documentation clarification is needed, or a fix in the code :)


<?php

namespace Enqueue\AsyncCommand\DependencyInjection;

use Enqueue\AsyncCommand\Commands;
use Enqueue\AsyncCommand\RunCommandProcessor;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;

class AsyncCommandExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        foreach ($configs['clients'] as $client) {
            // BC compatibility
            if (!is_array($client)) {
                $client = [
                    'name' => $client,
                    'command_name' => Commands::RUN_COMMAND,
                    'queue_name' => Commands::RUN_COMMAND,
                    'timeout' => 60,
                ];
            }

            $id = sprintf('enqueue.async_command.%s.run_command_processor', $client['name']);
            $container->register($id, RunCommandProcessor::class)
                ->addArgument('%kernel.project_dir%', $client['timeout'])
                ->addTag('enqueue.processor', [
                    'client' => $client['name'],
                    'command' => $client['command_name'] ?? Commands::RUN_COMMAND,
                    'queue' => $client['queue_name'] ?? Commands::RUN_COMMAND,
                    'prefix_queue' => false,
                    'exclusive' => true,
                ])
                ->addTag('enqueue.transport.processor')
            ;
        }
    }
}

<?php

namespace Enqueue\AsyncCommand\DependencyInjection;

use Enqueue\AsyncCommand\Commands;
use Enqueue\AsyncCommand\RunCommandProcessor;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;

class AsyncCommandExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        foreach ($configs['clients'] as $client) {
            // BC compatibility
            if (!is_array($client)) {
                $client = [
                    'name' => $client,
                    'command_name' => Commands::RUN_COMMAND,
                    'queue_name' => Commands::RUN_COMMAND,
                    'timeout' => 60,
                ];
            }

            $id = sprintf('enqueue.async_command.%s.run_command_processor', $client['name']);
            $container->register($id, RunCommandProcessor::class)
                ->addArgument('%kernel.project_dir%')
                ->addArgument($client['timeout'])
                ->addTag('enqueue.processor', [
                    'client' => $client['name'],
                    'command' => $client['command_name'] ?? Commands::RUN_COMMAND,
                    'queue' => $client['queue_name'] ?? Commands::RUN_COMMAND,
                    'prefix_queue' => false,
                    'exclusive' => true,
                ])
                ->addTag('enqueue.transport.processor')
            ;
        }
    }
}

[async-command] Fix service definition to apply the timeout

addArgument add only one argument at a time to the construtor, right now the timeout configured by the user is never applied and it's always the default (60) value, this fixes it.


<?php declare(strict_types=1);

namespace ApiClients\Tests\Foundation\Transport\CommandBus\Command;

use ApiClients\Foundation\Transport\CommandBus\Command\SimpleRequestCommand;
use ApiClients\Tests\Foundation\Hydrator\TestCase;
use Psr\Http\Message\RequestInterface;

class SimpleRequestCommandTest extends TestCase
{
    public function _testCommand()
    {
        $method = 'GET';
        $path = '/foo/bar.json';
        $refresh = true;
        $command = new SimpleRequestCommand($path, $refresh);
        $this->assertInstanceOf(RequestInterface::class, $command->getRequest());
        $this->assertSame($method, $command->getRequest()->getMethod());
        $this->assertSame($path, $command->getRequest()->getUri()->getPath());
        $this->assertSame($refresh, $command->getRefresh());
    }

    public function testCommandDefaultRefresh()
    {
        $method = 'GET';
        $path = '/foo/bar.json';
        $refresh = false;
        $command = new SimpleRequestCommand($path);
        $this->assertInstanceOf(RequestInterface::class, $command->getRequest());
        $this->assertSame($method, $command->getRequest()->getMethod());
        $this->assertSame($path, $command->getRequest()->getUri()->getPath());
        $this->assertSame($refresh, $command->getRefresh());
    }
}

<?php declare(strict_types=1);

namespace ApiClients\Tests\Foundation\Transport\CommandBus\Command;

use ApiClients\Foundation\Transport\CommandBus\Command\SimpleRequestCommand;
use ApiClients\Tests\Foundation\Hydrator\TestCase;
use Psr\Http\Message\RequestInterface;

class SimpleRequestCommandTest extends TestCase
{
    public function testCommand()
    {
        $method = 'GET';
        $path = '/foo/bar.json';
        $refresh = true;
        $command = new SimpleRequestCommand($path, $refresh);
        $this->assertInstanceOf(RequestInterface::class, $command->getRequest());
        $this->assertSame($method, $command->getRequest()->getMethod());
        $this->assertSame($path, $command->getRequest()->getUri()->getPath());
        $this->assertSame($refresh, $command->getRefresh());
    }

    public function testCommandDefaultRefresh()
    {
        $method = 'GET';
        $path = '/foo/bar.json';
        $refresh = false;
        $command = new SimpleRequestCommand($path);
        $this->assertInstanceOf(RequestInterface::class, $command->getRequest());
        $this->assertSame($method, $command->getRequest()->getMethod());
        $this->assertSame($path, $command->getRequest()->getUri()->getPath());
        $this->assertSame($refresh, $command->getRefresh());
    }
}

Make sure to run test command tests

Make sure to run test command tests


<?php
/*
 * This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Mage\Task\BuiltIn\Composer;

use Mage\Task\AbstractTask;

/**
 * Abstract Task for Composer
 *
 * @author Andrés Montañez <andres@andresmontanez.com>
 */
abstract class ComposerAbstractTask extends AbstractTask
{
    protected function getComposerCmd()
    {
        $composerCmd = $this->getParameter('composer_cmd', 'php composer.phar');
        return $this->getConfig()->general('composer_cmd', $composerCmd);
    }
}

<?php
/*
 * This file is part of the Magallanes package.
*
* (c) Andrés Montañez <andres@andresmontanez.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Mage\Task\BuiltIn\Composer;

use Mage\Task\AbstractTask;

/**
 * Abstract Task for Composer
 *
 * @author Andrés Montañez <andres@andresmontanez.com>
 */
abstract class ComposerAbstractTask extends AbstractTask
{
    protected function getComposerCmd()
    {
        $composerCmd = $this->getParameter('composer_cmd', $this->getConfig()->general('composer_cmd', 'php composer.phar'));
        return $this->getConfig()->general('composer_cmd', $composerCmd);
    }
}

Add possibility for defining the composer_cmd in the global config.


<?php
use Zend\ServiceManager\ServiceManager,
    Zend\Mvc\Service\ServiceManagerConfiguration;

chdir(dirname(__DIR__));

// Composer autoloading
if (!include_once('vendor/autoload.php')) {
    throw new RuntimeException('vendor/autoload.php could not be found. Did you run `php composer.phar install`?');
}

// Get application stack configuration
$configuration = include 'config/application.config.php';

// Setup service manager
$serviceManager = new ServiceManager(new ServiceManagerConfiguration($configuration['service_manager']));
$serviceManager->setService('ApplicationConfiguration', $configuration);
$serviceManager->get('ModuleManager')->loadModules();

// Run application
$serviceManager->get('Application')->bootstrap()->run()->send();

<?php
use Zend\Loader\AutoloaderFactory;
use Zend\ServiceManager\ServiceManager;
use Zend\Mvc\Service\ServiceManagerConfiguration;

chdir(dirname(__DIR__));

// Allow using an alternative copy of ZF2
if (getenv('ZF2_PATH')) {
    require_once getenv('ZF2_PATH') . '/Zend/Loader/AutoloaderFactory.php';
    AutoloaderFactory::factory();
}

// Composer autoloading
if (!include_once('vendor/autoload.php')) {
    throw new RuntimeException('vendor/autoload.php could not be found. Did you run `php composer.phar install`?');
}

// Get application stack configuration
$configuration = include 'config/application.config.php';

// Setup service manager
$serviceManager = new ServiceManager(new ServiceManagerConfiguration($configuration['service_manager']));
$serviceManager->setService('ApplicationConfiguration', $configuration);
$serviceManager->get('ModuleManager')->loadModules();

// Run application
$serviceManager->get('Application')->bootstrap()->run()->send();

Add conditional check for allowing ZF2_PATH env variable to be used


<?php
namespace Concrete\Controller\SinglePage;

use PageController;
use User;
use Config;

class PageForbidden extends PageController
{
    protected $viewPath = '/frontend/page_forbidden';

    public function view()
    {
        $u = new User();
        if (!$u->isRegistered() && Config::get('concrete.permissions.forward_to_login')) { //if they are not logged in, and we show guests the login...
            $this->redirect('/login');
        }
    }
}

<?php
namespace Concrete\Controller\SinglePage;

use PageController;
use User;
use Config;

class PageForbidden extends PageController
{
    protected $viewPath = '/frontend/page_forbidden';

    public function on_start()
    {
        $u = new User();
        if (!$u->isRegistered() && Config::get('concrete.permissions.forward_to_login')) { //if they are not logged in, and we show guests the login...
            $this->redirect('/login');
        }
    }
}

Fix an issue where concrete.permissions.forward_to_login didn't work


<?php
class PhpTemplate
{
    protected $_dir     = Null;
    protected $_data    = Array();
    protected $_headers = Array();

    public $app    = Null;
    public $router = Null;

    public function __construct()
    {
        ini_set('output_buffering', 'On');

        $this->_dir   = '../views/';
        $this->app    = App::instance();
        $this->router = Router::instance();
    }

    public function render($__view, $data = Array())
    {
        $content = $this->renderPartial($__view, $data);

        echo $this->renderPartial(App::instance()->config['default_layout'], array('content' => $content));
    }

    public function renderPartial($__view, $__data = Array())
    {
        $this->_data = array_merge($__data, $this->_data);

        ob_start();

        include($this->_dir.$__view.'.php');

        $content = ob_get_contents();

        ob_end_clean();

        return $content;
    }

    public function addHeader($header)
    {
        if (!in_array($header, $this->_headers))
            $this->_headers[] = $header;
    }

    public function getHeaders()
    {
        return $this->_headers;
    }

    public function __set($key, $value)
    {
        $this->_data[$key] = $value;
    }

    public function __get($key)
    {
        return isset($this->_data[$key]) ? $this->_data[$key] : Null;
    }

    public function __isset($key)
    {
        return isset($this->_data[$key]);
    }
}

<?php
class PhpTemplate
{
    protected $_dir     = Null;
    protected $_data    = Array();
    protected $_headers = Array();

    public $app    = Null;
    public $router = Null;

    public function __construct()
    {
        ini_set('output_buffering', 'On');
        ini_set('short_open_tag', 'On');

        $this->_dir   = '../views/';
        $this->app    = App::instance();
        $this->router = Router::instance();
    }

    public function render($__view, $data = Array())
    {
        $content = $this->renderPartial($__view, $data);

        echo $this->renderPartial(App::instance()->config['default_layout'], array('content' => $content));
    }

    public function renderPartial($__view, $__data = Array())
    {
        $this->_data = array_merge($__data, $this->_data);

        ob_start();

        include($this->_dir.$__view.'.php');

        $content = ob_get_contents();

        ob_end_clean();

        return $content;
    }

    public function addHeader($header)
    {
        if (!in_array($header, $this->_headers))
            $this->_headers[] = $header;
    }

    public function getHeaders()
    {
        return $this->_headers;
    }

    public function __set($key, $value)
    {
        $this->_data[$key] = $value;
    }

    public function __get($key)
    {
        return isset($this->_data[$key]) ? $this->_data[$key] : Null;
    }

    public function __isset($key)
    {
        return isset($this->_data[$key]);
    }
}

Set short open tags to on by default

Set short open tags to on by default


<?php

	require_once __DIR__ . '/autoloader.php';

	$files		= ['Example.class.php'];

	$SwaggerGen = new \SwaggerGen\SwaggerGen($_SERVER['HTTP_HOST'],  dirname($_SERVER['REQUEST_URI']));
	//$SwaggerGen->define('admin');
	//$SwaggerGen->define('root');
	$array = $SwaggerGen->getSwagger($files);

	header('Content-type: application/json');
	echo json_encode($array, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);

<?php

	require_once __DIR__ . '/autoloader.php';

	$files		= array('Example.class.php');

	$SwaggerGen = new \SwaggerGen\SwaggerGen($_SERVER['HTTP_HOST'],  dirname($_SERVER['REQUEST_URI']));
	//$SwaggerGen->define('admin');
	//$SwaggerGen->define('root');
	$array = $SwaggerGen->getSwagger($files);

	header('Content-type: application/json');
	echo json_encode($array, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);

Fix unnecessary incompatibility with old PHP versions


<?php

namespace Pipe\Test;

use Pipe\Manifest;
use Pipe\Environment;
use org\bovigo\vfs\vfsStream;

class ManifestTest extends \PHPUnit_Framework_TestCase
{
    function testManifestDumpsAssets()
    {
        $dir = vfsStream::setup('assets');

        $env = new Environment;
        $env->appendPath(__DIR__ . '/fixtures');

        $asset = $env->find('asset1.js', array('bundled' => true));
        $digestName = $asset->getDigestName();

        $manifest = new Manifest($env, vfsStream::url('assets') . '/manifest.json');
        $manifest->compress = true;
        $manifest->compile('asset1.js');

        $json = json_decode($manifest->toJSON(), true);

        $this->assertEquals($digestName, $json["assets"]["asset1.js"]);

        $this->assertNotEmpty($json["files"][$digestName]);

        $this->assertTrue($dir->hasChild('manifest.json'));
        $this->assertTrue($dir->hasChild($digestName));
        $this->assertTrue($dir->hasChild($digestName . '.gz'));
    }
}

<?php

namespace Pipe\Test;

use Pipe\Manifest;
use Pipe\Environment;
use org\bovigo\vfs\vfsStream;

class ManifestTest extends \PHPUnit_Framework_TestCase
{
    function testManifestDumpsAssets()
    {
        $dir = vfsStream::setup('assets');

        $env = new Environment;
        $env->appendPath(__DIR__ . '/fixtures');

        $asset = $env->find('asset1.js', array('bundled' => true));
        $digestName = $asset->getDigestName();

        $manifest = new Manifest($env, vfsStream::url('assets') . '/manifest.json');
        $manifest->compress = true;
        $manifest->compile('asset1.js');

        $json = json_decode($manifest->toJSON(), true);

        $this->assertEquals($digestName, $json["assets"]["asset1.js"]);

        $fileInfo = $json['files'][$digestName];

        $this->assertArrayHasKey('size', $fileInfo);
        $this->assertArrayHasKey('logical_path', $fileInfo);
        $this->assertArrayHasKey('content_type', $fileInfo);
        $this->assertArrayHasKey('digest', $fileInfo);

        $this->assertTrue($dir->hasChild('manifest.json'));
        $this->assertTrue($dir->hasChild($digestName));
        $this->assertTrue($dir->hasChild($digestName . '.gz'));
    }
}

Test for file info fields in Manifest test


<?php
namespace phpSmug\Tests;

use phpSmug\Client;

class ClientTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function shouldNotHaveToPassHttpClientToConstructor()
    {
      $client = new Client();

      $this->assertInstanceOf('phpSmug\HttpClient\HttpClient', $client->getHttpClient());
    }

}

?>

<?php
namespace phpSmug\Tests;

use phpSmug\Client;

class ClientTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function shouldNotHaveToPassHttpClientToConstructor()
    {
      $client = new Client();

      $this->assertInstanceOf('phpSmug\HttpClient\HttpClient', $client->getHttpClient());
    }

    /**
     * @test
     */
    public function shouldPassHttpClientInterfaceToConstructor()
    {
        $client = new Client($this->getHttpClientMock());

        $this->assertInstanceOf('phpSmug\HttpClient\HttpClientInterface', $client->getHttpClient());
    }

    public function getHttpClientMock(array $methods = array())
    {
        $methods = array_merge(
            array('get', 'post', 'patch', 'put', 'delete', 'request', 'setOption', 'setHeaders', 'authenticate'),
            $methods
        );

        return $this->getMock('phpSmug\HttpClient\HttpClientInterface', $methods);
    }
}

?>

Add shouldPassHttpClientInterfaceToConstructor test and mock function


<?php header('Content-Type: application/ld+json'); ?>
<?php header('Access-Control-Allow-Origin: *'); ?>
{
    "@context": "<?php echo get_option('ldp_context', 'http://owl.openinitiative.com/oicontext.jsonld'); ?>",
    "@graph": [
<?php while (have_posts()) : the_post(); ?>
        {
          <?php
            $value = get_the_terms($post->ID, 'ldp_container')[0];
            $termMeta = get_option("ldp_container_$value->term_id");
            $modelsDecoded = json_decode($termMeta["ldp_model"]);
            $fields = $modelsDecoded->{$value->slug}->fields;

            foreach($fields as $field) {
              if(substr($field->name, 0, 4) == "ldp_") {
                  echo('"'.substr($field->name, 4).'": ');
                  echo('"'.get_post_custom_values($field->name)[0].'",');
                  echo "\n        ";
              }
            }
          ?>

        "@id": "<?php the_permalink(); ?>"
        }
<?php endwhile; ?>
    ]
}

<?php header('Content-Type: application/ld+json'); ?>
<?php header('Access-Control-Allow-Origin: *'); ?>
{
    "@context": "<?php echo get_option('ldp_context', 'http://owl.openinitiative.com/oicontext.jsonld'); ?>",
    "@graph": [
<?php while (have_posts()) : the_post(); ?>
        {
          <?php
            $value = get_the_terms($post->ID, 'ldp_container')[0];
            $termMeta = get_option("ldp_container_$value->term_id");
            $modelsDecoded = json_decode($termMeta["ldp_model"]);
            $fields = $modelsDecoded->{$value->slug}->fields;

            foreach($fields as $field) {
              if(substr($field->name, 0, 4) == "ldp_") {
                  echo('"'.substr($field->name, 4).'": ');
                  echo('' . json_encode(get_post_custom_values($field->name)[0]) . ',');
                  echo "\n        ";
              }
            }
          ?>

        "@id": "<?php the_permalink(); ?>"
        }
<?php endwhile; ?>
    ]
}

Fix missing json encoding for support of large text chunks


<?php

class B3_Heartbeat_Comments {

    public function get_last_updated() {
        $comments = get_comments(
            array(
                'date_query' => $this->get_date_query()
            )
        );

        return $this->filter_comments($comments);
    }

    private function get_date_query() {
        return array(
            array(
                'after' => '15 minutes ago',
            )
        );
    }

    private function filter_comments( $comments ) {
        $result = array();
        foreach ($comments as $comment) {
            array_push($result, $comment->comment_ID);
        }

        return $result;
    }
}

<?php

class B3_Heartbeat_Comments {

    public function get_last_updated() {
        $comments = get_comments(
            array(
                'date_query' => $this->get_date_query()
            )
        );

        return $this->filter_comments($comments);
    }

    private function get_date_query() {
        return array(
            array(
                'after' => '15 minutes ago',
            )
        );
    }

    private function filter_comments( $comments ) {
        $result = array();
        foreach ($comments as $comment) {
            array_push($result, (int)$comment->comment_ID);
        }

        return $result;
    }
}

Convert comment ID to int

Convert comment ID to int


<?php

namespace Plummer\Calendar;

class CalendarFactory
{
	public static function fromRegistry(CalendarAbstract $calendar, RegistryInterface $eventsRegistry, RegistryInterface $recurrencesRegistry)
	{
		$calendar->addEvents($eventsRegistry->getAll());
		$calendar->addRecurrenceTypes($recurrencesRegistry->getAll());

		return $calendar;
	}
}

<?php

namespace Plummer\Calendar;

class CalendarFactory
{
	public static function fromRegistry(CalendarAbstract $calendar, RegistryInterface $eventsRegistry, RegistryInterface $recurrencesRegistry)
	{
		$events = $eventsRegistry->hasFilters() ?
			$eventsRegistry->getFiltered() :
			$eventsRegistry->getAll();

		$recurrences = $recurrencesRegistry->hasFilters() ?
			$recurrencesRegistry->getFiltered() :
			$recurrencesRegistry->getAll();

		$calendar->addEvents($events);
		$calendar->addRecurrenceTypes($recurrences);

		return $calendar;
	}
}

Check whether to retrieve all items or filter them based on params.


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', 'fe80::1', '::1']) || php_sapi_name() === 'cli-server')
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

/**
 * @var Composer\Autoload\ClassLoader $loader
 */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
//if (isset($_SERVER['HTTP_CLIENT_IP'])
//    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
//    || !(in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', 'fe80::1', '::1']) || php_sapi_name() === 'cli-server')
//) {
//    header('HTTP/1.0 403 Forbidden');
//    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
//}

/**
 * @var Composer\Autoload\ClassLoader $loader
 */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Remove restrictions for dev front controller.


<?php
/**
 *
 */

namespace Mvc5\Service;

use Mvc5\Exception;

final class Context
{
    /**
     * @var Service
     */
    protected static $service;

    /**
     * @param Service|null $service
     */
    function __construct(Service $service = null)
    {
        $service && $this->bind($service);
    }

    /**
     * @param Service $service
     * @return callable|Manager|Service
     */
    static function bind(Service $service)
    {
        isset(static::$service) &&
            Exception::runtime('Service already exists');

        return static::$service = $service;
    }

    /**
     * @return callable|Manager|Service
     */
    static function service()
    {
        return static::$service ?: Exception::runtime('Service does not exist');
    }

    /**
     * @param Service $service
     */
    function __invoke(Service $service)
    {
        $this->bind($service);
    }
}

<?php
/**
 *
 */

namespace Mvc5\Service;

use Mvc5\Exception;

final class Context
{
    /**
     * @var Service
     */
    protected static $service;

    /**
     * @param Service|null $service
     */
    function __construct(Service $service = null)
    {
        $service && $this->bind($service);
    }

    /**
     * @param Service $service
     * @return callable|Manager|Service
     */
    static function bind(Service $service)
    {
        isset(static::$service) &&
            Exception::runtime('Service already exists');

        return static::$service = $service;
    }

    /**
     * @return callable|Manager|Service
     */
    static function service()
    {
        return static::$service ?: Exception::runtime('Service does not exist');
    }

    /**
     * @param $name
     * @param array $args
     * @return mixed
     */
    static function __callStatic($name, array $args)
    {
        return static::service()->call($name, $args);
    }

    /**
     * @param Service $service
     */
    function __invoke(Service $service)
    {
        $this->bind($service);
    }
}

Add call static helper method to service context


<?php

namespace Juy\ActiveMenu;

use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;

class ServiceProvider extends IlluminateServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Register the application services
     *
     * @return void
     */
    public function register()
    {
        // Default package configuration
        $this->mergeConfigFrom(
            __DIR__ . '/../config/activemenu.php', 'activemenu'
        );

        $this->app->singleton('active', function($app) {
           return new Active($app['router']->current()->getName());
        });
    }

    /**
     * Perform post-registration booting of services
     *
     * @return void
     */
    public function boot()
    {
        // Add custom blade directive @ifActiveUrl
        \Blade::directive('ifActiveRoute', function($expression) {
            return "<?php if (Active::route({$expression})): ?>";
        });

        // Publish the config file
        $this->publishConfig();
    }

    /**
     * Publish the config file
     */
    protected function publishConfig()
    {
        $this->publishes([
            __DIR__ . '/../config/activemenu.php' => config_path('activemenu.php')
        ], 'config');
    }

}

<?php

namespace Juy\ActiveMenu;

use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;

class ServiceProvider extends IlluminateServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Register the application services
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('active', function($app) {
           return new Active($app['router']->current()->getName());
        });
    }

    /**
     * Perform post-registration booting of services
     *
     * @return void
     */
    public function boot()
    {
        // Add custom blade directive @ifActiveUrl
        \Blade::directive('ifActiveRoute', function($expression) {
            return "<?php if (Active::route({$expression})): ?>";
        });

        // Register configurations
        $this->registerConfigurations();
    }

    /**
     * Register configurations
     *
     * @return void
     */
    protected function registerConfigurations()
    {
        // Default package configuration
        $this->mergeConfigFrom(
            __DIR__ . '/../config/activemenu.php', 'activemenu'
        );

        // Publish the config file
        $this->publishes([
            __DIR__ . '/../config/activemenu.php' => config_path('activemenu.php')
        ], 'config');
    }

}

Create "Register configurations" method and move config codes


<?php
/**
 * @link      https://github.com/sydes/framework
 * @copyright 2011-2017, ArtyGrand <artygrand.ru>
 * @license   MIT license; see LICENSE
 */
namespace Sydes\Router;

class Router
{
    /**
     * Path to fast route cache file.
     */
    protected $cacheFile = false;

    /** @var \FastRoute\Dispatcher */
    protected $dispatcher;

    /**
     * @param string $file
     */
    public function setCacheFile($file)
    {
        $this->cacheFile = $file;
    }

    /**
     * Dispatch router for request
     *
     * @param $method
     * @param $uri
     * @return array
     * @link   https://github.com/nikic/FastRoute/blob/master/src/Dispatcher.php
     */
    public function dispatch($modules, $method, $uri)
    {
        $callback = function (Route $r) use ($modules) {
            foreach ($modules as $module) {
                $class = 'Module\\'.$module.'\\Controller';
                if (method_exists($class, 'routes')) {
                    $class::routes($r);
                }
            }
        };

        return $this->createDispatcher($callback)->dispatch($method, $uri);
    }

    /**
     * @return \FastRoute\Dispatcher
     */
    protected function createDispatcher($callback)
    {
        $this->dispatcher = \FastRoute\cachedDispatcher($callback, [
            'cacheFile'     => $this->cacheFile,
            'cacheDisabled' => is_bool($this->cacheFile),
            'routeCollector' => 'Sydes\Router\Route',
        ]);

        return $this->dispatcher;
    }
}

<?php
/**
 * @link      https://github.com/sydes/framework
 * @copyright 2011-2017, ArtyGrand <artygrand.ru>
 * @license   MIT license; see LICENSE
 */
namespace Sydes\Router;

class Router
{
    /**
     * Path to fast route cache file.
     */
    protected $cacheFile = false;

    /** @var \FastRoute\Dispatcher */
    protected $dispatcher;

    /**
     * @param string $file
     */
    public function setCacheFile($file)
    {
        $this->cacheFile = $file;
    }

    /**
     * Dispatch router for request
     *
     * @param array $files
     * @param string $method
     * @param string $uri
     * @return array
     * @link   https://github.com/nikic/FastRoute/blob/master/src/Dispatcher.php
     */
    public function dispatch(array $files, $method, $uri)
    {
        $callback = function (Route $r) use ($files) {
            foreach ($files as $file) {
                if (file_exists($file)) {
                    include $file;
                }
            }
        };

        return $this->createDispatcher($callback)->dispatch($method, $uri);
    }

    /**
     * @return \FastRoute\Dispatcher
     */
    protected function createDispatcher($callback)
    {
        $this->dispatcher = \FastRoute\cachedDispatcher($callback, [
            'cacheFile'     => $this->cacheFile,
            'cacheDisabled' => is_bool($this->cacheFile),
            'routeCollector' => 'Sydes\Router\Route',
        ]);

        return $this->dispatcher;
    }
}

Remove route defenitions from controllers