<?php

namespace OpenDominion\Http\Controllers\Auth;

use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use OpenDominion\Http\Controllers\AbstractController;
use OpenDominion\Models\User;
use OpenDominion\Services\AnalyticsService;
use OpenDominion\Services\DominionSelectorService;

class LoginController extends AbstractController
{
    use AuthenticatesUsers;

    protected $redirectTo = '/dashboard';

    public function getLogin()
    {
        return view('pages.auth.login');
    }

    public function postLogin(Request $request)
    {
        return $this->login($request);
    }

    protected function authenticated(Request $request, User $user)
    {
        if ($user->dominions->count() === 1) {
            $dominionSelectorService = app()->make(DominionSelectorService::class);
            $dominionSelectorService->selectUserDominion($user->dominions->first());
        }

        // todo: fire laravel event
        $analyticsService = app()->make(AnalyticsService::class);
        $analyticsService->queueFlashEvent(new AnalyticsService\Event(
            'user',
            'login'
        ));
    }

    public function postLogout(Request $request)
    {
        $response = $this->logout($request);

        // todo: fire laravel event
        $analyticsService = app()->make(AnalyticsService::class);
        $analyticsService->queueFlashEvent(new AnalyticsService\Event(
            'user',
            'logout'
        ));

        session()->flash('alert-success', 'You have been logged out.');

        return $response;
    }
}

<?php

namespace OpenDominion\Http\Controllers\Auth;

use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use OpenDominion\Http\Controllers\AbstractController;
use OpenDominion\Models\User;
use OpenDominion\Services\AnalyticsService;
use OpenDominion\Services\DominionSelectorService;

class LoginController extends AbstractController
{
    use AuthenticatesUsers;

    protected $redirectTo = '/dashboard';

    public function getLogin()
    {
        return view('pages.auth.login');
    }

    public function postLogin(Request $request)
    {
        return $this->login($request);
    }

    protected function authenticated(Request $request, User $user)
    {
        if ($user->dominions->count() === 1) {
            $dominionSelectorService = app()->make(DominionSelectorService::class);
            $dominionSelectorService->selectUserDominion($user->dominions->first());
            $this->redirectTo = '/dominion/status';
        }

        // todo: fire laravel event
        $analyticsService = app()->make(AnalyticsService::class);
        $analyticsService->queueFlashEvent(new AnalyticsService\Event(
            'user',
            'login'
        ));
    }

    public function postLogout(Request $request)
    {
        $response = $this->logout($request);

        // todo: fire laravel event
        $analyticsService = app()->make(AnalyticsService::class);
        $analyticsService->queueFlashEvent(new AnalyticsService\Event(
            'user',
            'logout'
        ));

        session()->flash('alert-success', 'You have been logged out.');

        return $response;
    }
}

Fix login with active dominion not being redirect to status screen


<?php namespace Pingpong\Modules\Commands;

use Illuminate\Console\Command;

class ListCommand extends Command {

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Show list of all modules.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $this->table(['Name', 'Status', 'Priority', 'Path'], $this->getRows());
    }

    /**
     * Get table rows.
     *
     * @return array
     */
    public function getRows()
    {
        $rows = [];

        foreach ($this->laravel['modules']->getOrdered() as $module)
        {
            $rows[] = [
                $module->getStudlyName(),
                $module->enabled() ? 'Enabled' : 'Disabled',
                $module->get('priority'),
                $module->getPath(),
            ];
        }

        return $rows;
    }

}

<?php namespace Pingpong\Modules\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;

class ListCommand extends Command {

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Show list of all modules.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $this->table(['Name', 'Status', 'Order', 'Path'], $this->getRows());
    }

    /**
     * Get table rows.
     *
     * @return array
     */
    public function getRows()
    {
        $rows = [];

        foreach ($this->getModules() as $module)
        {
            $rows[] = [
                $module->getStudlyName(),
                $module->enabled() ? 'Enabled' : 'Disabled',
                $module->get('order'),
                $module->getPath(),
            ];
        }

        return $rows;
    }

    public function getModules()
    {
        switch ($this->option('only')) {
            case 'enabled':
                return $this->laravel['modules']->getByStatus(1);
                break;

            case 'disabled':
                return $this->laravel['modules']->getByStatus(0);
                break;

            case 'ordered':
                return $this->laravel['modules']->getOrdered($this->option('direction'));
                break;

            default:
                return $this->laravel['modules']->all();
                break;
        }
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('only', null, InputOption::VALUE_OPTIONAL, 'Types of modules will be displayed.', null),
            array('direction', 'd', InputOption::VALUE_OPTIONAL, 'The direction of ordering.', 'asc'),
        );
    }

}

Add new option --only & --direction flags


<?php

namespace Darvin\ImageBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class DarvinImageExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('darvin_image.imagine_filter', $config['imagine_filter']);
        $container->setParameter('darvin_image.upload_path', $config['upload_path']);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('image.yml');
        $loader->load('image_creator.yml');
    }
}

<?php

namespace Darvin\ImageBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class DarvinImageExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('darvin_image.imagine_filter', $config['imagine_filter']);
        $container->setParameter('darvin_image.upload_path', $config['upload_path']);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('image.yml');
        $loader->load('size.yml');
        $loader->load('url_builder.yml');
    }
}

Load new configs in bundle extension.

Load new configs in bundle extension.


<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Cache;

class CategoriesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $output = Cache::rememberForever('categories', function () {
            return ['data' => ['categories' => Category::categoryAsc()->get()]];
        });

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

    /**
     * Get the category JSON by a given category_id
     * route: api/categories/<category_id>
     * @param  int $category_id
     * @return json {"success": true or false, "data": {"category": category}};
     */
    public function show($categoryd)
    {
        $category = Category::find($categoryId);
        if ($category === null) {
            return response()->json(['success' => false]);
        }
        return response()->json(["success" => true, "data" => ["category" => $category]]);
    }
}

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Cache;

class CategoriesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $output = Cache::rememberForever('categories', function () {
            return ['data' => ['categories' => Category::categoryAsc()->get()]];
        });

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

    /**
     * Get the category JSON by a given category_id
     * route: api/categories/<category_id>
     * @param  int $category_id
     * @return json {"success": true or false, "data": {"category": category}};
     */
    public function show($categoryId)
    {
        $category = Category::find($categoryId);
        if ($category === null) {
            return response()->json(['success' => false]);
        }
        return response()->json(["success" => true, "data" => ["category" => $category]]);
    }
}

Fix typo when displaying individual category details


<?php

namespace Oro\Bundle\EmailBundle\Provider;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

use Oro\Bundle\EmailBundle\Event\EmailRecipientsLoadEvent;

class EmailRecipientsProvider
{
    /** @var EventDispatcherInterface */
    protected $dispatcher;

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

    /**
     * @param object|null $relatedEntity
     * @param string|null $query
     * @param int $limit
     *
     * @return array
     */
    public function getEmailRecipients($relatedEntity = null, $query = null, $limit = 100)
    {
        if (!$this->dispatcher->hasListeners(EmailRecipientsLoadEvent::NAME)) {
            return [];
        }

        $event = new EmailRecipientsLoadEvent($relatedEntity, $query, $limit);
        $this->dispatcher->dispatch(EmailRecipientsLoadEvent::NAME, $event);

        return $event->getResults();
    }
}

<?php

namespace Oro\Bundle\EmailBundle\Provider;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

use Oro\Bundle\EmailBundle\Event\EmailRecipientsLoadEvent;

class EmailRecipientsProvider
{
    /** @var EventDispatcherInterface */
    protected $dispatcher;

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

    /**
     * @param object|null $relatedEntity
     * @param string|null $query
     * @param int $limit
     *
     * @return array
     */
    public function getEmailRecipients($relatedEntity = null, $query = null, $limit = 100)
    {
        if (!$this->dispatcher->hasListeners(EmailRecipientsLoadEvent::NAME)) {
            return [];
        }

        $event = new EmailRecipientsLoadEvent($relatedEntity, $query, $limit);
        $this->dispatcher->dispatch(EmailRecipientsLoadEvent::NAME, $event);

        return $this->valuesAsKeys($event->getResults());
    }

    /**
     * @param array $data
     *
     * @return array
     */
    public function valuesAsKeys(array $data)
    {
        foreach ($data as $key => $record) {
            if (isset($record['children'])) {
                $data[$key]['children'] = $this->valuesAsKeys($record['children']);
            } else {
                $data[$key]['id'] = $record['text'];
            }
        }

        return $data;
    }
}

CRM-3533: Add autocomplete for to, cc, bcc fields with possibility to type new email address


<?php

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

class EcontDispatching extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::setConnection(DB::connection(Config::get('econt.connection')))->create('econt_dispatching', function (Blueprint $table) {
            $table->unsignedInteger('settlement_id');
            $table->enum('direction', ['from', 'to'])->index('idx_direction');
            $table->enum('shipment', ['courier', 'cargo_pallet', 'cargo_express', 'post'])->index('idx_shipment');
            $table->unsignedInteger('office_code');

            $table->primary(['settlement_id', 'direction', 'type', 'office_code']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::setConnection(DB::connection(Config::get('econt.connection')))->dropIfExists('econt_dispatching');
    }
}

<?php

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

class EcontDispatching extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::setConnection(DB::connection(Config::get('econt.connection')))->create('econt_dispatching', function (Blueprint $table) {
            $table->unsignedInteger('settlement_id');
            $table->enum('direction', ['from', 'to'])->index('idx_direction');
            $table->enum('shipment', ['courier', 'cargo_pallet', 'cargo_express', 'post'])->index('idx_shipment');
            $table->unsignedInteger('office_code');

            $table->primary(['settlement_id', 'direction', 'shipment', 'office_code']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::setConnection(DB::connection(Config::get('econt.connection')))->dropIfExists('econt_dispatching');
    }
}

Change type to shipment in dispatching.

Change type to shipment in dispatching.


<?php

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;

$console = new Application('Silex - Kitchen Edition', '0.1');

$app->boot();

$console
    ->register('assetic:dump')
    ->setDescription('Dumps all assets to the filesystem')
    ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
        if (!$app['assetic.enabled']) {
            return false;
        }

        $dumper = $app['assetic.dumper'];
        if (isset($app['twig'])) {
            $dumper->addTwigAssets();
        }
        $dumper->dumpAssets();
        $output->writeln('<info>Dump finished</info>');
    })
;

if (isset($app['cache.path'])) {
    $console
        ->register('cache:clear')
        ->setDescription('Clears the cache')
        ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {

            $cacheDir = $app['cache.path'];
            $finder = Finder::create()->in($cacheDir)->notName('.gitkeep');

            $filesystem = new Filesystem();
            $filesystem->remove($finder);

            $output->writeln(sprintf("%s <info>success</info>", 'cache:clear'));
    });
}

return $console;

<?php

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;

$console = new Application('SMART Search - Livenews. Search view', '0.1');

$app->boot();

$console
    ->register('assetic:dump')
    ->setDescription('Dumps all assets to the filesystem')
    ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
        if (!$app['assetic.enabled']) {
            return false;
        }

        $dumper = $app['assetic.dumper'];
        if (isset($app['twig'])) {
            $dumper->addTwigAssets();
        }
        $dumper->dumpAssets();
        $output->writeln('<info>Dump finished</info>');
    })
;

if (isset($app['cache.path'])) {
    $console
        ->register('cache:clear')
        ->setDescription('Clears the cache')
        ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {

            $cacheDir = $app['cache.path'];
            $finder = Finder::create()->in($cacheDir)->notName('.gitkeep');

            $filesystem = new Filesystem();
            $filesystem->remove($finder);

            $output->writeln(sprintf("%s <info>success</info>", 'cache:clear'));
    });
}

return $console;

Update the name of the app

Update the name of the app


<?php

namespace Dakatsuka\MonologFluentHandler\Tests;

use Dakatsuka\MonologFluentHandler\FluentHandler;
use Monolog\Logger;

class FluentHandlerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var array
     */
    protected $record;

    protected function setUp()
    {
        $record = array();
        $record['channel']   = 'debug';
        $record['message']   = 'monolog.fluent';
        $record['context']   = ['foo' => 'bar'];
        $record['formatted'] = 'formatted message';
        $record['level']     = Logger::DEBUG;

        $this->record = $record;
    }

    public function testWrite()
    {
        $context = $this->record['context'];
        $context['level'] = Logger::getLevelName($this->record['level']);

        $loggerMock = $this->getMockBuilder('Fluent\Logger\FluentLogger')
            ->disableOriginalConstructor()
            ->getMock();
        $loggerMock
            ->expects($this->once())
            ->method('post')
            ->with('debug.monolog.fluent', $context);

        $handler = new FluentHandler($loggerMock);
        $handler->write($this->record);
    }
}

<?php

namespace Dakatsuka\MonologFluentHandler\Tests;

use Dakatsuka\MonologFluentHandler\FluentHandler;
use Monolog\Logger;

class FluentHandlerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var array
     */
    protected $record;

    protected function setUp()
    {
        $record = array();
        $record['channel']   = 'debug';
        $record['message']   = 'monolog.fluent';
        $record['context']   = array('foo' => 'bar');
        $record['formatted'] = 'formatted message';
        $record['level']     = Logger::DEBUG;

        $this->record = $record;
    }

    public function testWrite()
    {
        $context = $this->record['context'];
        $context['level'] = Logger::getLevelName($this->record['level']);

        $loggerMock = $this->getMockBuilder('Fluent\Logger\FluentLogger')
            ->disableOriginalConstructor()
            ->getMock();
        $loggerMock
            ->expects($this->once())
            ->method('post')
            ->with('debug.monolog.fluent', $context);

        $handler = new FluentHandler($loggerMock);
        $handler->write($this->record);
    }
}

Fix an issue where the unit test fails on PHP 5.3


<?php

namespace Tystr\RestOrm\Model;

use Tystr\RestOrm\Annotation\Id;

class BlogInvalidIdentifierMapping
{
    /**
     * @Id()
     */
    public $id;

    /**
     * @Id()
     */
    public $id2;
}

<?php

namespace Tystr\RestOrm\Model;

use Tystr\RestOrm\Annotation\Id;
use Tystr\RestOrm\Annotation\Resource;

/**
 * @Resource("blogs")
 */
class BlogInvalidIdentifierMapping
{
    /**
     * @Id()
     */
    public $id;

    /**
     * @Id()
     */
    public $id2;
}

Add @Resource annotation to test model

Add @Resource annotation to test model


<?php
class WorkCalendarTest extends PHPUnit_Framework_TestCase
{
    private $params = [];

    public function testWorkCalendar()
    {
        $this->assertTrue(true);
    }
}
?>

<?php
use fproject\calendar\WorkCalendar;
class WorkCalendarTest extends PHPUnit_Framework_TestCase
{
    private $params = [];

    public function testWorkCalendar()
    {
        $workCal = new WorkCalendar();
        $workCal->name = "My Calendar";
        $this->assertTrue($workCal->name === "My Calendar");
    }
}
?>

Add testcase for WorkCalendar contructor

Add testcase for WorkCalendar contructor


<?php

set_error_handler(
    function ($errno, $errstr, $errfile, $errline )
    {
        throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
    }
);

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

$driver = RemoteWebDriver::create('127.0.0.1:4444/wd/hub', DesiredCapabilities::phantomjs());
$driver->manage()->window()->setSize(new WebDriverDimension(1024, 1024));
$driver->manage()->timeouts()->implicitlyWait(16);

$driver->get('http://www.sbb.ch/geschaeftsreisen.html');
$driver->takeScreenshot(__DIR__ . '/s1.png');

$driver->findElement(WebDriverBy::id('btUser'))->sendKeys('stc-cpedersoli');
$driver->takeScreenshot(__DIR__ . '/s2.png');

<?php

set_error_handler(
    function ($errno, $errstr, $errfile, $errline )
    {
        throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
    }
);

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

$driver = RemoteWebDriver::create('127.0.0.1:4444/wd/hub', DesiredCapabilities::phantomjs());
$driver->manage()->window()->setSize(new WebDriverDimension(1024, 1024));
$driver->manage()->timeouts()->implicitlyWait(8);

$driver->get('http://www.sbb.ch/geschaeftsreisen.html');
$driver->findElement(WebDriverBy::id('btUser'))->sendKeys('stc-cpedersoli');

$driver->executeScript('console.log(1611);');

echo json_encode(
    array_map(
        function ($logEntry)
        {
            return json_decode($logEntry['message'], true);
        },

        $driver->manage()->getLog('har')
    )
);

Check out the HAR log

Check out the HAR log


<?php defined('C5_EXECUTE') or die('Access denied.');
$form = Loader::helper('form');
?>

				<?=USER_REGISTRATION_WITH_EMAIL_ADDRESS?t('Email Address'):t('Username')?>

				<?=$form->text('uName')?>

				<?=t('Password')?>

				<?=$form->password('uPassword')?>

	<?=$form->hidden('rcID', $rcID); ?>

		<?=$form->checkbox('uMaintainLogin',1)?> <?=t('Remain logged in to website.')?>

<a href="<?=View::url('/login', 'concrete', 'forgot_password')?>"><?=t('Forgot Password?')?>

	<button class='btn primary'><?=t('Sign In')</button>

<?php defined('C5_EXECUTE') or die('Access denied.');
$form = Loader::helper('form');
?>

				<?=USER_REGISTRATION_WITH_EMAIL_ADDRESS?t('Email Address'):t('Username')?>

				<?=$form->text('uName')?>

				<?=t('Password')?>

				<?=$form->password('uPassword')?>

	<?=$form->hidden('rcID', $rcID); ?>

		<?=$form->checkbox('uMaintainLogin',1)?> <?=t('Remain logged in to website.')?>

<a href="<?=View::url('/login', 'concrete', 'forgot_password')?>"><?=t('Forgot Password?')?>

	<button class='btn primary'><?=t('Sign In')?></button>

Fix typo in loging page causing fatal error

Fix typo in loging page causing fatal error

- Close `?>`


<?php declare(strict_types=1);

namespace GtmPlugin\DependencyInjection;

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

/**
 * Class Configuration
 * @package GtmPlugin\DependencyInjection
 */
final class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();

        $rootNode = $treeBuilder->root('gtm');

        $rootNode
            ->children()
                ->booleanNode('inject')->defaultTrue()->end()
                ->arrayNode('features')
                    ->children()
                        ->booleanNode('environment')->defaultTrue()->end()
                        ->booleanNode('route')->defaultTrue()->end()
                        ->booleanNode('context')->defaultTrue()->end()
                        ->booleanNode('events')->defaultTrue()->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

<?php declare(strict_types=1);

namespace GtmPlugin\DependencyInjection;

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

/**
 * Class Configuration
 * @package GtmPlugin\DependencyInjection
 */
final class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();

        $rootNode = $treeBuilder->root('gtm');

        $rootNode
            ->children()
                ->booleanNode('inject')->defaultTrue()->end()
                ->arrayNode('features')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->booleanNode('environment')->defaultTrue()->end()
                        ->booleanNode('route')->defaultTrue()->end()
                        ->booleanNode('context')->defaultTrue()->end()
                        ->booleanNode('events')->defaultTrue()->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

Add configuration defaults for features

Add configuration defaults for features


<?php
/**
 * This file is part of the LdapTools package.
 *
 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace LdapTools\Connection;

/**
 * Represents various ldap server control values.
 *
 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
 */
class LdapControls
{
    /**
     * Paged operation support that splits results into multiple result sets.
     */
    const PAGED_RESULTS = '1.2.840.113556.1.4.319';

    /**
     * Used to specify that tombstones and deleted objects should be visible to the operation.
     */
    const SHOW_DELETED = '1.2.840.113556.1.4.417';
}

<?php
/**
 * This file is part of the LdapTools package.
 *
 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace LdapTools\Connection;

/**
 * Represents various ldap server control values.
 *
 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
 */
class LdapControls
{
    /**
     * Paged operation support that splits results into multiple result sets.
     */
    const PAGED_RESULTS = '1.2.840.113556.1.4.319';

    /**
     * Used to specify that tombstones and deleted objects should be visible to the operation.
     */
    const SHOW_DELETED = '1.2.840.113556.1.4.417';

    /**
     * Used to specify that all children of a LDAP object should be removed during a delete operation.
     */
    const SUB_TREE_DELETE = '1.2.840.113556.1.4.805';
}

Add the sub tree delete control constant.


<?php
declare(strict_types=1);

namespace Vision\Session\Extension;

use Vision\Session\SessionInterface;

use SessionHandlerInterface;
use RuntimeException;

class NativeExtension implements ExtensionInterface
{
    private $started = false;

    public function __construct(SessionHandlerInterface $handler = null)
    {
        if (isset($handler)) {
            session_set_save_handler($handler, true);
        }
    }

    /**
     * @throws RuntimeException
     */
    public function start(SessionInterface $session): void
    {
        if ($this->started && $this->isActive()) {
            return;
        }

        if (!session_start()) {
            throw new RuntimeException('Session could not be started.');
        }

        $session->exchangeArray($_SESSION);

        $this->started = true;
    }

    public function save(SessionInterface $session)
    {
        $this->start($session);
        $_SESSION = $session->getArrayCopy();
    }

    public function isStarted(): bool
    {
        return $this->started;
    }

    public function isActive(): bool
    {
        return $this->getStatus() === PHP_SESSION_ACTIVE;
    }

    public function getStatus(): int
    {
        return session_status();
    }

    public function getId(): string
    {
        return session_id();
    }

    public function regenerateId(bool $deleteOldSession = true): bool
    {
        return session_regenerate_id($deleteOldSession);
    }
}

<?php
declare(strict_types=1);

namespace Vision\Session\Extension;

use Vision\Session\SessionInterface;

use SessionHandlerInterface;
use RuntimeException;

class NativeExtension implements ExtensionInterface
{
    private $started = false;

    public function __construct(SessionHandlerInterface $handler = null)
    {
        if (isset($handler)) {
            session_set_save_handler($handler, true);
        }
    }

    /**
     * @throws RuntimeException
     */
    public function start(SessionInterface $session): void
    {
        if ($this->started && $this->isActive()) {
            return;
        }

        if (!session_start()) {
            throw new RuntimeException('Session could not be started.');
        }

        $session->exchangeArray($_SESSION);

        $this->started = true;
    }

    public function save(SessionInterface $session)
    {
        $this->start($session);
        $_SESSION = $session->getArrayCopy();
        session_write_close();
    }

    public function isStarted(): bool
    {
        return $this->started;
    }

    public function isActive(): bool
    {
        return $this->getStatus() === PHP_SESSION_ACTIVE;
    }

    public function getStatus(): int
    {
        return session_status();
    }

    public function getId(): string
    {
        return session_id();
    }

    public function regenerateId(bool $deleteOldSession = true): bool
    {
        return session_regenerate_id($deleteOldSession);
    }
}

Call session_write_close() when saving session


<?php
namespace Codenetix\SocialMediaImporter\Adapters;

use Codenetix\SocialMediaImporter\Contracts\MediaAdapterInterface;
use Codenetix\SocialMediaImporter\Contracts\MediaFactoryMethodInterface;
use Codenetix\SocialMediaImporter\Support\TagsFromStringExtractor;

/**
 * @author Andrey Vorobiov<andrew.sprw@gmail.com>
 */
class DraugiemMediaAdapter implements MediaAdapterInterface
{
    private $data;

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

    /**
     * @param MediaFactoryMethodInterface $mediaFactoryMethod
     * @return \Codenetix\SocialMediaImporter\Contracts\MediaInterface
     */
    public function transform(MediaFactoryMethodInterface $mediaFactoryMethod){
        $media = $mediaFactoryMethod->make();
        $media->setId($this->data['id']);
        $media->setType($this->data['type'] == 'picture' ? 'image' : 'video');
        $media->setSourceType($this->data['type']);
        $media->setDescription(!empty($this->data['description']) ? $this->data['description'] : '');
        $media->setSourceURL($this->data['url']);
        $media->setThumbnailURL($this->data['thumbnail']);
        $media->setTags(TagsFromStringExtractor::extract($media->getDescription()));
        return $media;
    }
}

<?php
namespace Codenetix\SocialMediaImporter\Adapters;

use Codenetix\SocialMediaImporter\Contracts\MediaAdapterInterface;
use Codenetix\SocialMediaImporter\Contracts\MediaFactoryMethodInterface;
use Codenetix\SocialMediaImporter\Support\TagsFromStringExtractor;

/**
 * @author Andrey Vorobiov<andrew.sprw@gmail.com>
 */
class DraugiemMediaAdapter implements MediaAdapterInterface
{
    private $data;

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

    /**
     * @param MediaFactoryMethodInterface $mediaFactoryMethod
     * @return \Codenetix\SocialMediaImporter\Contracts\MediaInterface
     */
    public function transform(MediaFactoryMethodInterface $mediaFactoryMethod){
        $media = $mediaFactoryMethod->make();
        $media->setId($this->data['id']);
        $media->setType($this->data['type'] == 'picture' ? 'image' : 'video');
        $media->setSourceType($this->data['type']);
        $media->setDescription(!empty($this->data['description']) ? $this->data['description'] : '');
        if($this->data['type'] == 'youtube'){
            $media->setSourceURL($this->youtubeURLtoEmbed($this->data['url']));
        } else {
            $media->setSourceURL($this->data['url']);
        }
        $media->setThumbnailURL($this->data['thumbnail']);
        $media->setTags(TagsFromStringExtractor::extract($media->getDescription()));
        return $media;
    }

    private function youtubeURLtoEmbed($url){
        preg_match(
            '/[\\?\\&]v=([^\\?\\&]+)/',
            $url,
            $matches
        );
        return 'http://www.youtube.com/embed/'.$matches[1];
    }

}

Add youtube url to embed

Add youtube url to embed


<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.8.0';
}

<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.8.1';
}

Set release version to 0.8.1

Set release version to 0.8.1


<?php

namespace App\Form;

class Form extends \AzuraForms\Form
{
    public function __construct(array $options = [], ?array $defaults = null)
    {
        array_unshift($this->field_namespaces, '\\App\\Form\\Field');

        $this->field_name_conversions['playlisttime'] = 'PlaylistTime';

        parent::__construct($options, $defaults);
    }

    protected function addCsrfField(): void
    {
        $this->addField(self::CSRF_FIELD_NAME, Field\Csrf::class, [
            'csrf_key' => $this->name,
        ]);
    }
}

<?php

namespace App\Form;

class Form extends \AzuraForms\Form
{
    public function __construct(array $options = [], ?array $defaults = null)
    {
        array_unshift($this->field_namespaces, '\\App\\Form\\Field');

        $this->field_name_conversions['playlisttime'] = 'PlaylistTime';

        parent::__construct($options, $defaults);
    }

    protected function addCsrfField(): void
    {
        $this->addField(
            self::CSRF_FIELD_NAME,
            Field\Csrf::class,
            [
                'csrf_key' => $this->name,
            ]
        );
    }

    public function openForm(): string
    {
        $attrs = [
            'id' => $this->name,
            'method' => $this->method,
            'action' => $this->action,
            'class' => 'form ' . ($this->options['class'] ?? ''),
            'accept-charset' => 'UTF-8',
        ];

        foreach ($this->fields as $field) {
            if ($field instanceof Field\File) {
                $attrs['enctype'] = 'multipart/form-data';
                break;
            }
        }

        if (!empty($this->options['tabs'])) {
            $attrs['novalidate'] = 'novalidate';
        }

        $attrsAsHtml = [];
        foreach ($attrs as $key => $val) {
            $attrsAsHtml[] = $key . '="' . $val . '"';
        }

        return '<form ' . implode(' ', $attrsAsHtml) . '>';
    }
}

Disable HTML5 form validation on tabbed forms to prevent issues.


<?php

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

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

            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->string('buddy_name');
            $table->string('buddy_file_path');

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

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

<?php

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

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

            $table->boolean('is_spam')->default(false);

            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->string('buddy_name');
            $table->string('buddy_file_path');

            $table->string('status')->default('new');
            $table->unsignedInteger('status_update_by_user_id')->nullable();
            $table->dateTime('status_update_at')->nullable();

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

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

Add status and is_spam columns to registrations table


{{ trans('dashboard.event_reminder') }}

{{-- about Name --}}
{{ trans('dashboard.event_about') }} {{ $event['contact_complete_name'] }}

Fix reminders on the dashboard;

Fix reminders on the dashboard;


<?php

namespace Slim\Middleware;

/**
 * HTTP Basic Authentication
 *
 * Provides HTTP Basic Authentication on given routes
 *
 * @package    Slim
 * @author     Mika Tuupola <tuupola@appelsiini.net>
 */
class HttpBasicAuth extends \Slim\Middleware {

    public $options;

    public function __construct($options = null) {

        /* Default options. */
        $this->options = array(
            "users" => array(),
            "path" => "/",
            "realm" => "Protected"
        );

        if ($options) {
            $this->options = array_merge($this->options, (array)$options);
        }
    }

    public function call() {
        $request = $this->app->request;

        /* If path matches what is given on initialization. */
        if (false !== strpos($request->getPath(), $this->options["path"])) {
            $user = $request->headers("PHP_AUTH_USER");
            $pass = $request->headers("PHP_AUTH_PW");

            /* Check if user and passwords matches. */
            if (isset($this->options["users"][$user]) && $this->options["users"][$user] === $pass) {
                $this->next->call();
            } else {
                $this->app->response->status(401);
                $this->app->response->header("WWW-Authenticate", sprintf('Basic realm="%s"', $this->options["realm"]));;
                return;
            }
        } else {
            $this->next->call();
        }
    }
}

<?php

namespace Slim\Middleware;

/**
 * HTTP Basic Authentication
 *
 * Provides HTTP Basic Authentication on given routes
 *
 * @package    Slim
 * @author     Mika Tuupola <tuupola@appelsiini.net>
 */
class HttpBasicAuth extends \Slim\Middleware {

    public $options;

    public function __construct($options = null) {

        /* Default options. */
        $this->options = array(
            "users" => array(),
            "path" => "/",
            "realm" => "Protected"
        );

        if ($options) {
            $this->options = array_merge($this->options, (array)$options);
        }
    }

    public function call() {
        $request = $this->app->request;
        $environment = $this->app->environment;

        /* If path matches what is given on initialization. */
        if (false !== strpos($request->getPath(), $this->options["path"])) {

            $user = $environment["PHP_AUTH_USER"];
            $pass = $environment["PHP_AUTH_PW"];

            /* Check if user and passwords matches. */
            if (isset($this->options["users"][$user]) && $this->options["users"][$user] === $pass) {
                $this->next->call();
            } else {
                $this->app->response->status(401);
                $this->app->response->header("WWW-Authenticate", sprintf('Basic realm="%s"', $this->options["realm"]));;
                return;
            }
        } else {
            $this->next->call();
        }
    }
}

Use credentials from environment so we can do unit tests.


<?php

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

class CreateAnimalTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('animal', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string("name", 255);
            $table->integer("dob")->nullable();
            $table->enum("gender", ["male", "female"]);
            $table->integer("father")->unsigned()->nullable();
            $table->integer("mother")->unsigned()->nullable();
            $table->boolean("active")->default(false);
            $table->boolean("own")->default(false);
            $table->dateTime('created_at');
            $table->dateTime('updated_at');
        });

        Schema::table('animal', function (Blueprint $table) {
            $table->foreign("father")->references("id")->on("animal");
            $table->foreign("mother")->references("id")->on("animal");
            $table->unique(["name", "dob"]);
        });
    }

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

<?php

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

class CreateAnimalTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('animal', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string("name", 255);
            $table->integer("dob")->nullable();
            $table->boolean("female")->default(true);
            $table->integer("father")->unsigned()->nullable();
            $table->integer("mother")->unsigned()->nullable();
            $table->boolean("active")->default(false);
            $table->boolean("own")->default(false);
            $table->dateTime('created_at');
            $table->dateTime('updated_at');
        });

        Schema::table('animal', function (Blueprint $table) {
            $table->foreign("father")->references("id")->on("animal");
            $table->foreign("mother")->references("id")->on("animal");
            $table->unique(["name", "dob"]);
        });
    }

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

Change gender to represent boolean female


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

namespace WellCommerce\Bundle\LayoutBundle\Tests\Manager;

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

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

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

namespace WellCommerce\Bundle\LayoutBundle\Tests\Manager;

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

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

Return types in manager tests

Return types in manager tests


<?php

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

class CreateIdeasTable extends Migration {
    public function up() {
        Schema::create('ideas', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->text('body');
            $table->timestamps();
        });
    }

    public function down() {
        Schema::dropIfExists('ideas');
    }
}

<?php

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

class CreateIdeasTable extends Migration {
    public function up() {
        Schema::create('ideas', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->text('body');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    public function down() {
        Schema::table('ideas', function ($table) {
            $table->dropForeign('ideas_user_id_foreign');
        });

        Schema::dropIfExists('ideas');
    }
}

Add foreign key(s) to migration that creates ideas table


<?php

final class AlmanacBindingsSearchEngineAttachment
  extends AlmanacSearchEngineAttachment {

  private $isActive;

  public function setIsActive($is_active) {
    $this->isActive = $is_active;
    return $this;
  }

  public function getIsActive() {
    return $this->isActive;
  }

  public function getAttachmentName() {
    return pht('Almanac Bindings');
  }

  public function getAttachmentDescription() {
    return pht('Get Almanac bindings for the service.');
  }

  public function willLoadAttachmentData($query, $spec) {
    $query->needProperties(true);

    if ($this->getIsActive()) {
      $query->needBindings(true);
    } else {
      $query->needActiveBindings(true);
    }
  }

  public function getAttachmentForObject($object, $data, $spec) {
    $bindings = array();

    if ($this->getIsActive()) {
      $service_bindings = $object->getActiveBindings();
    } else {
      $service_bindings = $object->getBindings();
    }

    foreach ($service_bindings as $binding) {
      $bindings[] = $this->getAlmanacBindingDictionary($binding);
    }

    return array(
      'bindings' => $bindings,
    );
  }

}

<?php

final class AlmanacBindingsSearchEngineAttachment
  extends AlmanacSearchEngineAttachment {

  private $isActive;

  public function setIsActive($is_active) {
    $this->isActive = $is_active;
    return $this;
  }

  public function getIsActive() {
    return $this->isActive;
  }

  public function getAttachmentName() {
    return pht('Almanac Bindings');
  }

  public function getAttachmentDescription() {
    return pht('Get Almanac bindings for the service.');
  }

  public function willLoadAttachmentData($query, $spec) {
    $query->needProperties(true);

    if ($this->getIsActive()) {
      $query->needActiveBindings(true);
    } else {
      $query->needBindings(true);
    }
  }

  public function getAttachmentForObject($object, $data, $spec) {
    $bindings = array();

    if ($this->getIsActive()) {
      $service_bindings = $object->getActiveBindings();
    } else {
      $service_bindings = $object->getBindings();
    }

    foreach ($service_bindings as $binding) {
      $bindings[] = $this->getAlmanacBindingDictionary($binding);
    }

    return array(
      'bindings' => $bindings,
    );
  }

}

Correct issue with "bindings" conduit attachment

Summary: Ref T13641. These conditions are swapped, and "activeBindings" loads more data than necessary while "bindings" doesn't load enough.

Test Plan: Called method with each attachment, got good results instead of an exception.

Maniphest Tasks: T13641

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


<?php

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

class CreateRecurringsTable extends Migration {
    public function up() {
        Schema::create('recurrings', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('type');
            $table->string('day');
            $table->date('starts_on');
            $table->date('ends_on');
            $table->date('last_used_on');
            $table->integer('tag_id')->unsigned()->nullable();
            $table->string('description');
            $table->integer('amount');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    public function down() {
        Schema::dropIfExists('recurrings');
    }
}

<?php

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

class CreateRecurringsTable extends Migration {
    public function up() {
        Schema::create('recurrings', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('type');
            $table->string('day');
            $table->date('starts_on');
            $table->date('ends_on')->nullable();
            $table->date('last_used_on')->nullable();
            $table->integer('tag_id')->unsigned()->nullable();
            $table->string('description');
            $table->integer('amount');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    public function down() {
        Schema::dropIfExists('recurrings');
    }
}

Make ends_on and last_used_on columns in recurrings table nullable


<?php

namespace Belvedere\Basecamp\Sections;

use Belvedere\Basecamp\Models\Recording;

class Recordings extends AbstractSection
{
    /**
     * Index all recordings.
     *
     * @param  string  $type
     * @param  array   $parameters
     * @param  int     $page
     * @return \Illuminate\Support\Collection
     */
    public function index($type, array $parameters = array(), $page = null)
    {
        $url = 'projects/recordings.json';

        $recordings = $this->client->get($url, [
            'query' => array_merge([
                'type' => $type,
                'page' => $page,
            ], $parameters)
        ]);

        return $this->indexResponse($recordings, Recording::class);
    }

    /**
     * Trash a recording.
     *
     * @param  int  $id
     * @return string
     */
    public function destroy($id)
    {
        return $this->client->put(
            sprintf('buckets/%d/recordings/%d/status/trashed.json', $this->bucket, $id)
        );
    }

    /**
     * Archived a recording.
     *
     * @param int $id
     * @return string
     */
    public function archived(int $id)
    {
        return $this->client->put(
            sprintf('buckets/%d/recordings/%d/status/archived.json', $this->bucket, $id)
        );
    }
}

<?php

namespace Belvedere\Basecamp\Sections;

use Belvedere\Basecamp\Models\Recording;

class Recordings extends AbstractSection
{
    /**
     * Index all recordings.
     *
     * @param  string  $type
     * @param  array   $parameters
     * @param  int     $page
     * @return \Illuminate\Support\Collection
     */
    public function index($type, array $parameters = array(), $page = null)
    {
        $url = 'projects/recordings.json';

        $recordings = $this->client->get($url, [
            'query' => array_merge([
                'type' => $type,
                'page' => $page,
            ], $parameters)
        ]);

        return $this->indexResponse($recordings, Recording::class);
    }

    /**
     * Trash a recording.
     *
     * @param  int  $id
     * @return string
     */
    public function destroy($id)
    {
        return $this->client->put(
            sprintf('buckets/%d/recordings/%d/status/trashed.json', $this->bucket, $id)
        );
    }

    /**
     * Archive a recording.
     *
     * @param int $id
     * @return string
     */
    public function archive(int $id)
    {
        return $this->client->put(
            sprintf('buckets/%d/recordings/%d/status/archived.json', $this->bucket, $id)
        );
    }

    /**
     * Archive a recording.
     *
     * @param int $id
     * @return string
     */
    public function unarchive(int $id)
    {
        return $this->client->put(
            sprintf('buckets/%d/recordings/%d/status/active.json', $this->bucket, $id)
        );
    }
}

Change method name for archive and add unarchive method


<?php

namespace WP_CLI;

use \Composer\DependencyResolver\Rule;
use \Composer\EventDispatcher\Event;
use \Composer\EventDispatcher\EventSubscriberInterface;
use \Composer\Script\PackageEvent;
use \Composer\Script\ScriptEvents;
use \WP_CLI;

/**
 * A Composer Event subscriber so we can keep track of what's happening inside Composer
 */
class PackageManagerEventSubscriber implements EventSubscriberInterface {

	public static function getSubscribedEvents() {

		return array(
			ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install',
			ScriptEvents::POST_PACKAGE_INSTALL => 'post_install',
			);
	}

	public static function pre_install( PackageEvent $event ) {
		WP_CLI::log( ' - Installing package' );
	}

	public static function post_install( PackageEvent $event ) {

		$operation = $event->getOperation();
		$reason = $operation->getReason();
		if ( $reason instanceof Rule ) {

			switch ( $reason->getReason() ) {

				case Rule::RULE_PACKAGE_CONFLICT;
				case Rule::RULE_PACKAGE_SAME_NAME:
				case Rule::RULE_PACKAGE_REQUIRES:
					$composer_error = $reason->getPrettyString();
					break;

			}

			if ( ! empty( $composer_error ) ) {
				WP_CLI::log( sprintf( " - Error: %s", $composer_error ) );
			}
		}

	}

}

<?php

namespace WP_CLI;

use \Composer\DependencyResolver\Rule;
use \Composer\EventDispatcher\Event;
use \Composer\EventDispatcher\EventSubscriberInterface;
use \Composer\Script\PackageEvent;
use \Composer\Script\ScriptEvents;
use \WP_CLI;

/**
 * A Composer Event subscriber so we can keep track of what's happening inside Composer
 */
class PackageManagerEventSubscriber implements EventSubscriberInterface {

	public static function getSubscribedEvents() {

		return array(
			ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install',
			ScriptEvents::POST_PACKAGE_INSTALL => 'post_install',
			);
	}

	public static function pre_install( PackageEvent $event ) {
		WP_CLI::log( ' - Installing package' );
	}

	public static function post_install( PackageEvent $event ) {

		$operation = $event->getOperation();
		$reason = $operation->getReason();
		if ( $reason instanceof Rule ) {

			switch ( $reason->getReason() ) {

				case Rule::RULE_PACKAGE_CONFLICT;
				case Rule::RULE_PACKAGE_SAME_NAME:
				case Rule::RULE_PACKAGE_REQUIRES:
					$composer_error = $reason->getPrettyString( $event->getPool() );
					break;

			}

			if ( ! empty( $composer_error ) ) {
				WP_CLI::log( sprintf( " - Error: %s", $composer_error ) );
			}
		}

	}

}

Fix fatal error when a dependency needs to be installed

```
PHP Catchable fatal error:  Argument 1 passed to
Composer\DependencyResolver\Rule::getPrettyString() must be an instance
of Composer\DependencyResolver\Pool, none given, called in
/home/vagrant/.wp-cli/php/WP_CLI/PackageManagerEventSubscriber.php on
line 40 and defined in
/home/vagrant/.wp-cli/vendor/composer/composer/src/Composer/DependencyResolver/Rule.php
on line 161
```


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

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

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

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

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

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

Return number of set neurons

Return number of set neurons


<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class OrganizerRecap extends Mailable
{
    use Queueable, SerializesModels;

    public $participants;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($participants)
    {
        $this->participants = $participants;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $csv = $this->formatCsv(array_map(function ($participant) {
            return [
                $participant['name'],
                $participant['email']
            ];
        }, $this->participants));

        return $this->view('emails.organizer_recap')
                    ->text('emails.organizer_recap_plain')
                    ->attachData($csv, 'secretsanta.csv', [
                        'mime' => 'text/csv',
                    ]);
    }

    protected function formatCsv($data, $delimiter = ",", $enclosure = '"', $escape_char = "\\")
    {
        $f = fopen('php://memory', 'r+');
        foreach ($data as $fields) {
            if (fputcsv($f, $fields, $delimiter, $enclosure, $escape_char) === false) {
                return false;
            }
        }
        rewind($f);
        $csv_line = stream_get_contents($f);
        return rtrim($csv_line);
    }
}

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class OrganizerRecap extends Mailable
{
    use Queueable, SerializesModels;

    public $participants;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($participants)
    {
        $this->participants = $participants;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $csv = $this->formatCsv(array_map(function ($participant) {
            return [
                $participant['name'],
                $participant['email']
            ];
        }, $this->participants));

        return $this->subject("Récapitulatif Organisateur")
                    ->view('emails.organizer_recap')
                    ->text('emails.organizer_recap_plain')
                    ->attachData($csv, 'secretsanta.csv', [
                        'mime' => 'text/csv',
                    ]);
    }

    protected function formatCsv($data, $delimiter = ",", $enclosure = '"', $escape_char = "\\")
    {
        $f = fopen('php://memory', 'r+');
        foreach ($data as $fields) {
            if (fputcsv($f, $fields, $delimiter, $enclosure, $escape_char) === false) {
                return false;
            }
        }
        rewind($f);
        $csv_line = stream_get_contents($f);
        return rtrim($csv_line);
    }
}

Fix organizer recap email title

Fix organizer recap email title


<?php

namespace CF\WordPress;

class WordPressWrapper
{
    public function getOption($key, $default)
    {
        return get_option($key, $default);
    }

    public function updateOption($key, $value)
    {
        return update_option($key, $value);
    }

    public function deleteOption($key)
    {
        return delete_option($key);
    }

    public function getSiteURL()
    {
        if(function_exists('domain_mapping_siteurl')){
            return domain_mapping_siteurl('');
        } else {
           return get_site_url();
        }
    }
}

<?php

namespace CF\WordPress;

class WordPressWrapper
{
    public function getOption($key, $default)
    {
        return get_option($key, $default);
    }

    public function updateOption($key, $value)
    {
        return update_option($key, $value);
    }

    public function deleteOption($key)
    {
        return delete_option($key);
    }

    public function getSiteURL()
    {
		$site_url = get_site_url();

        if(function_exists('domain_mapping_siteurl')){
            $site_url = domain_mapping_siteurl($site_url);
        }

        return $site_url;
    }
}

Use subdomain URL if no domain mapping available

If no mapping available, "domain_mapping_siteurl()" returns the argument untouched (behaves like a filter).


<?php
namespace Payum\Bundle\PayumBundle\Form\Extension;

use Payum\Core\Bridge\Symfony\Form\Type\GatewayFactoriesChoiceType;
use Payum\Core\Registry\GatewayFactoryRegistryInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Exception;
use Symfony\Component\OptionsResolver\OptionsResolver;

class GatewayFactoriesChoiceTypeExtension extends AbstractTypeExtension
{
    /**
     * @var GatewayFactoryRegistryInterface
     */
    private $gatewayFactoryRegistry;

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

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $options = $resolver->getDefinedOptions();
        if (empty($options['choices'])) {
            $choices = [];
            foreach ($this->gatewayFactoryRegistry->getGatewayFactories() as $name => $factory) {
                $choices['form.choice.'.$name] = $name;
            }

            $resolver->setDefaults([
                'choices' => $choices,
                'choice_translation_domain' => 'PayumBundle',
                'translation_domain' => 'PayumBundle',
            ]);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getExtendedType()
    {
        return GatewayFactoriesChoiceType::class;
    }
}

<?php
namespace Payum\Bundle\PayumBundle\Form\Extension;

use Payum\Core\Bridge\Symfony\Form\Type\GatewayFactoriesChoiceType;
use Payum\Core\Registry\GatewayFactoryRegistryInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Exception;
use Symfony\Component\OptionsResolver\OptionsResolver;

class GatewayFactoriesChoiceTypeExtension extends AbstractTypeExtension
{
    /**
     * @var GatewayFactoryRegistryInterface
     */
    private $gatewayFactoryRegistry;

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

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $options = $resolver->getDefinedOptions();
        if (empty($options['choices'])) {
            $choices = [];
            foreach ($this->gatewayFactoryRegistry->getGatewayFactories() as $name => $factory) {
                $choices['form.choice.'.$name] = $name;
            }

            $resolver->setDefaults([
                'choices' => $choices,
                'choice_translation_domain' => 'PayumBundle',
                'translation_domain' => 'PayumBundle',
            ]);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getExtendedType()
    {
        return GatewayFactoriesChoiceType::class;
    }

    /**
     * {@inheritdoc}
     */
    public static function getExtendedTypes()
    {
        return [GatewayFactoriesChoiceType::class];
    }
}

Add new getExtendedTypes method in form extension for Symfony 4.2

When bumping the requirement to PHP 7.1 the iterable return type should be added


<?php
/**
 * Class Google\Site_Kit\Modules\Analytics\Plugin_Detector
 *
 * @package   Google\Site_Kit\Modules\Analytics
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Modules\Analytics;

/**
 * Detects the user's current active plugins that ShirshuClass supports
 *
 * Class Plugin_Detector
 */
class Plugin_Detector {

	/**
	 * A list of Shirshu_Class supported plugins
	 *
	 * @var array
	 */
	private $supported_plugins = array();

	/**
	 * Plugin_Detector constructor.
	 *
	 * @param array $supported_plugins list of supported plugins.
	 */
	public function __construct( $supported_plugins ) {
		$this->supported_plugins = $supported_plugins;
	}

	/**
	 * Determines the user's current active plugins that Shirshu_Class supports
	 *
	 * @return array
	 */
	public function get_active_plugins() {
		$active_plugins = array();
		foreach ( $this->supported_plugins as $key => $function_name ) {
			if ( defined( $function_name ) || function_exists( $function_name ) ) {
				array_push( $active_plugins, $key);
			}
		}
		return $active_plugins;
	}
}

<?php
/**
 * Class Google\Site_Kit\Modules\Analytics\Plugin_Detector
 *
 * @package   Google\Site_Kit\Modules\Analytics
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Modules\Analytics;

/**
 * Detects the user's current active plugins that ShirshuClass supports
 *
 * Class Plugin_Detector
 */
class Plugin_Detector {

	/**
	 * A list of Shirshu_Class supported plugins
	 *
	 * @var array
	 */
	private $supported_plugins = array();

	/**
	 * Plugin_Detector constructor.
	 *
	 * @param array $supported_plugins list of supported plugins.
	 */
	public function __construct( $supported_plugins ) {
		$this->supported_plugins = $supported_plugins;
	}

	/**
	 * Determines the user's current active plugins that Shirshu_Class supports
	 *
	 * @return array
	 */
	public function get_active_plugins() {
		$active_plugins = array();
		foreach ( $this->supported_plugins as $key => $function_name ) {
			if ( defined( $function_name ) || function_exists( $function_name ) ) {
				array_push( $active_plugins, $key );
			}
		}
		return $active_plugins;
	}
}

Fix the phpcs code style error.

Fix the phpcs code style error.


<?php
namespace DebugHttp\Network\Http;

use Cake\Core\Configure;
use DebugHttp\Panel\ClientCallPanel;
use DebugKit\DebugTimer;

/**
 * Class Client
 *
 * Client automatically registers all requests and responses with the panel
 *
 * @package DebugHttp\Network\Http
 */
class Client extends \Cake\Http\Client
{

    /**
     * Helper method for doing non-GET requests.
     *
     * @param string $method  HTTP method.
     * @param string $url     URL to request.
     * @param mixed  $data    The request body.
     * @param array  $options The options to use. Contains auth, proxy etc.
     *
     * @return \Cake\Network\Http\Response
     */
    protected function _doRequest($method, $url, $data, $options)
    {
        $request = $this->_createRequest($method, $url, $data, $options);

        $timerKey = 'debug_http.call.' . $url;
        if (Configure::read('debug')) {
            DebugTimer::start($timerKey, $method . ' ' . $url);
        }

        $response = $this->send($request, $options);

        if (Configure::read('debug')) {
            DebugTimer::stop($timerKey);
            ClientCallPanel::addCall($request, $response, DebugTimer::elapsedTime($timerKey));
        }

        return $response;
    }
}

<?php
namespace DebugHttp\Network\Http;

use Cake\Core\Configure;
use DebugHttp\Panel\ClientCallPanel;
use DebugKit\DebugTimer;

/**
 * Class Client
 *
 * Client automatically registers all requests and responses with the panel
 *
 * @package DebugHttp\Network\Http
 */
class Client extends \Cake\Http\Client
{

    /**
     * Helper method for doing non-GET requests.
     *
     * @param string $method  HTTP method.
     * @param string $url     URL to request.
     * @param mixed  $data    The request body.
     * @param array  $options The options to use. Contains auth, proxy etc.
     *
     * @return \Cake\Network\Http\Response
     */
    protected function _doRequest($method, $url, $data, $options)
    {
        $request = $this->_createRequest($method, $url, $data, $options);

        $time = microtime();
        $timerKey = 'debug_http.call.' . $url . '.' . $time;
        if (Configure::read('debug')) {
            DebugTimer::start($timerKey, $method . ' ' . $url);
        }

        $response = $this->send($request, $options);

        if (Configure::read('debug')) {
            DebugTimer::stop($timerKey);
            ClientCallPanel::addCall($request, $response, DebugTimer::elapsedTime($timerKey));
        }

        return $response;
    }
}

Add microtime to DebugTimer name to prevent duplicate times for equal calls


<?php

namespace Scarlett;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Scarlett\Event\ResponseEvent;
use Scarlett\Event\KernelEvents;

class Kernel
{
    private $dispatcher;
    private $matcher;
    private $resolver;

    public function __construct(EventDispatcher $dispatcher, UrlMatcherInterface $matcher, ControllerResolverInterface $resolver)
    {
        $this->dispatcher = $dispatcher;
        $this->matcher = $matcher;
        $this->resolver = $resolver;
    }

    public function handle(Request $request)
    {
        try{
            $request->attributes->add($this->matcher->match($request->getPathInfo()));

            $controller = $this->resolver->getController($request);
            $arguments = $this->resolver->getArguments($request, $controller);

            $response = call_user_func_array($controller, $arguments);
        }catch(ResourceNotFoundException $e) {
            $response = new Response('Not found', 404);
        }catch(\Exception $e){
            $response = new Response('[Scarlett Kernel Exception] '.$e->getMessage(), 500);
            $this->dispatcher->dispatch(KernelEvents::EXCEPTION, new ExceptionEvent($request, $e));
        }
        $this->dispatcher->dispatch(KernelEvents::RESPONSE, new ResponseEvent($request, $response));

        return $response;
    }

}

<?php

namespace Scarlett;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Scarlett\Event\ResponseEvent;
use Scarlett\Event\KernelEvents;

class Kernel
{
    private $dispatcher;
    private $matcher;
    private $resolver;

    public function __construct(EventDispatcherInterface $dispatcher, UrlMatcherInterface $matcher, ControllerResolverInterface $resolver)
    {
        $this->dispatcher = $dispatcher;
        $this->matcher = $matcher;
        $this->resolver = $resolver;
    }

    public function handle(Request $request)
    {
        try{
            $request->attributes->add($this->matcher->match($request->getPathInfo()));

            $controller = $this->resolver->getController($request);
            $arguments = $this->resolver->getArguments($request, $controller);

            $response = call_user_func_array($controller, $arguments);
        }catch(ResourceNotFoundException $e) {
            $response = new Response('Not found', 404);
        }catch(\Exception $e){
            $response = new Response('[Scarlett Kernel Exception] '.$e->getMessage(), 500);
            $this->dispatcher->dispatch(KernelEvents::EXCEPTION, new ExceptionEvent($request, $e));
        }
        $this->dispatcher->dispatch(KernelEvents::RESPONSE, new ResponseEvent($request, $response));

        return $response;
    }

}

Change EventDispatcher use to EventDispatcherInterface

This change makes code more testable and decoupled of the
EventDispatcher Component


<?php

namespace OpenDominion\Calculators\Dominion;

use OpenDominion\Models\Dominion;

class RangeCalculator
{
    /** @var LandCalculator */
    protected $landCalculator;

    /**
     * RangeCalculator constructor.
     *
     * @param LandCalculator $landCalculator
     */
    public function __construct(LandCalculator $landCalculator)
    {
        $this->landCalculator = $landCalculator;
    }

    public function isInRange(Dominion $self, Dominion $target): bool
    {
        // todo: if RG then $modifier = 0.6, else if EG then $modifier = 0.75, else $modifier = 0.4

        $selfLand = $this->landCalculator->getTotalLand($self);
        $targetLand = $this->landCalculator->getTotalLand($target);

        $modifier = 0.6;

        return (
            ($targetLand >= ($selfLand * $modifier)) &&
            ($targetLand <= ($selfLand / $modifier))
        );
    }
}

<?php

namespace OpenDominion\Calculators\Dominion;

use OpenDominion\Models\Dominion;

class RangeCalculator
{
    /** @var LandCalculator */
    protected $landCalculator;

    /**
     * RangeCalculator constructor.
     *
     * @param LandCalculator $landCalculator
     */
    public function __construct(LandCalculator $landCalculator)
    {
        $this->landCalculator = $landCalculator;
    }

    /**
     * Checks whether dominion $target is in range of dominion $self.
     *
     * @param Dominion $self
     * @param Dominion $target
     * @return bool
     */
    public function isInRange(Dominion $self, Dominion $target): bool
    {
        // todo: if RG then $modifier = 0.6, else if EG then $modifier = 0.75, else $modifier = 0.4

        $selfLand = $this->landCalculator->getTotalLand($self);
        $targetLand = $this->landCalculator->getTotalLand($target);

        $modifier = 0.6;

        return (
            ($targetLand >= ($selfLand * $modifier)) &&
            ($targetLand <= ($selfLand / $modifier))
        );
    }
}

Add phpdoc for isInRange() method

Add phpdoc for isInRange() method


<?php

namespace League\OAuth2\Server\Repositories;

use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface;
use League\OAuth2\Server\Entities\Interfaces\ScopeEntityInterface;

interface UserRepositoryInterface extends RepositoryInterface
{
    /**
     * Get a user entity.
     *
     * @param string                                                          $username
     * @param string                                                          $password
     * @param string                                                          $grantType    The grant type used
     * @param \League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface $clientEntity
     * @param ScopeEntityInterface[]                                          $scopes
     *
     * @return \League\OAuth2\Server\Entities\Interfaces\UserEntityInterface
     */
    public function getUserEntityByUserCredentials(
        $username,
        $password,
        $grantType,
        ClientEntityInterface $clientEntity,
        array &$scopes
    );
}

<?php

namespace League\OAuth2\Server\Repositories;

use League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface;

interface UserRepositoryInterface extends RepositoryInterface
{
    /**
     * Get a user entity.
     *
     * @param string                                                          $username
     * @param string                                                          $password
     * @param string                                                          $grantType    The grant type used
     * @param \League\OAuth2\Server\Entities\Interfaces\ClientEntityInterface $clientEntity
     *
     * @return \League\OAuth2\Server\Entities\Interfaces\UserEntityInterface
     */
    public function getUserEntityByUserCredentials(
        $username,
        $password,
        $grantType,
        ClientEntityInterface $clientEntity
    );
}

Remove injected array of scopes

Remove injected array of scopes


<?php
declare(strict_types=1);
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link          https://cakephp.org CakePHP(tm) Project
 * @since         3.5.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\TestSuite\Stub;

use Exception;

/**
 * Test Exception Renderer.
 *
 * Use this class if you want to re-throw exceptions that would otherwise be
 * caught by the ErrorHandlerMiddleware. This is useful while debugging or
 * writing integration test cases.
 *
 * @see \Cake\TestSuite\IntegrationTestCase::disableErrorHandlerMiddleware()
 * @internal
 */
class TestExceptionRenderer
{
    /**
     * Simply rethrow the given exception
     *
     * @param \Exception $exception Exception.
     * @return void
     * @throws \Exception $exception Rethrows the passed exception.
     */
    public function __construct(Exception $exception)
    {
        throw $exception;
    }
}

<?php
declare(strict_types=1);
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link          https://cakephp.org CakePHP(tm) Project
 * @since         3.5.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\TestSuite\Stub;

use Throwable;

/**
 * Test Exception Renderer.
 *
 * Use this class if you want to re-throw exceptions that would otherwise be
 * caught by the ErrorHandlerMiddleware. This is useful while debugging or
 * writing integration test cases.
 *
 * @see \Cake\TestSuite\IntegrationTestCase::disableErrorHandlerMiddleware()
 * @internal
 */
class TestExceptionRenderer
{
    /**
     * Simply rethrow the given exception
     *
     * @param \Throwable $exception Exception.
     * @return void
     * @throws \Throwable $exception Rethrows the passed exception.
     */
    public function __construct(Throwable $exception)
    {
        throw $exception;
    }
}

Allow throwable in stub renderer

Allow throwable in stub renderer

By only accepting Exception the Stub Exception renderer cannot handle
syntax errors, type errors or undefined method errors.


<?php

/**
 * @group aphront
 */
final class AphrontFileResponse extends AphrontResponse {

  private $content;
  private $mimeType;
  private $download;

  public function setDownload($download) {
    $download = preg_replace('/[^A-Za-z0-9_.-]/', '_', $download);
    if (!strlen($download)) {
      $download = 'untitled_document.txt';
    }
    $this->download = $download;
    return $this;
  }

  public function getDownload() {
    return $this->download;
  }

  public function setMimeType($mime_type) {
    $this->mimeType = $mime_type;
    return $this;
  }

  public function getMimeType() {
    return $this->mimeType;
  }

  public function setContent($content) {
    $this->content = $content;
    return $this;
  }

  public function buildResponseString() {
    return $this->content;
  }

  public function getHeaders() {
    $headers = array(
      array('Content-Type', $this->getMimeType()),
    );

    if (strlen($this->getDownload())) {
      $headers[] = array('X-Download-Options', 'noopen');

      $filename = $this->getDownload();
      $headers[] = array(
        'Content-Disposition',
        'attachment; filename='.$filename,
      );
    }

    $headers = array_merge(parent::getHeaders(), $headers);
    return $headers;
  }

}

<?php

/**
 * @group aphront
 */
final class AphrontFileResponse extends AphrontResponse {

  private $content;
  private $mimeType;
  private $download;

  public function setDownload($download) {
    $download = preg_replace('/[^A-Za-z0-9_.-]/', '_', $download);
    if (!strlen($download)) {
      $download = 'untitled_document.txt';
    }
    $this->download = $download;
    return $this;
  }

  public function getDownload() {
    return $this->download;
  }

  public function setMimeType($mime_type) {
    $this->mimeType = $mime_type;
    return $this;
  }

  public function getMimeType() {
    return $this->mimeType;
  }

  public function setContent($content) {
    $this->content = $content;
    return $this;
  }

  public function buildResponseString() {
    return $this->content;
  }

  public function getHeaders() {
    $headers = array(
      array('Content-Type', $this->getMimeType()),
      array('Content-Length', strlen($this->content)),
    );

    if (strlen($this->getDownload())) {
      $headers[] = array('X-Download-Options', 'noopen');

      $filename = $this->getDownload();
      $headers[] = array(
        'Content-Disposition',
        'attachment; filename='.$filename,
      );
    }

    $headers = array_merge(parent::getHeaders(), $headers);
    return $headers;
  }

}

Add Content-Length header to Aphront file responses.

Summary:
Provide a Content-Length header so that browsers can estimate time
remaining for file downloads.

Test Plan: Tested on our local phabricator install.

Reviewers: epriestley

Reviewed By: epriestley

CC: aran, Korvin

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


<?php
class f_MemcachedProvider
{
	private $memcachedInstance = null;

	public function __construct($config)
	{
		$this->memcachedInstance = new Memcached('memcachedConnection');

		if ($this->memcachedInstance->addServer($config["server"]["host"], $config["server"]["port"]) === false)
		{
			Framework::error("MemcachedProvider: could not obtain memcache instance");
		}
	}

	/**
	 * @return Boolean
	 */
	public function isAvailable()
	{
		return ($this->memcachedInstance !== null);
	}

	public function close()
	{
		if ($this->isAvailable())
		{
			$this->memcachedInstance = null;
		}
	}

	/**
	 * @return Memcache
	 */
	public function getConnection()
	{
		return $this->memcachedInstance;
	}
}

<?php
class f_MemcachedProvider
{
	private $memcachedInstance = null;

	public function __construct($config)
	{
		$this->memcachedInstance = new Memcached('memcachedConnection');

		// Check if memcached instance has no servers in it's pool yet (see http://www.php.net/manual/en/memcached.construct.php#93536)
		if (!count($this->memcachedInstance->getServerList()))
		{
			if ($this->memcachedInstance->addServer($config["server"]["host"], $config["server"]["port"]) === false)
			{
				Framework::error("MemcachedProvider: could not obtain memcache instance");
			}
		}
	}

	/**
	 * @return Boolean
	 */
	public function isAvailable()
	{
		return ($this->memcachedInstance !== null);
	}

	public function close()
	{
		if ($this->isAvailable())
		{
			$this->memcachedInstance = null;
		}
	}

	/**
	 * @return Memcache
	 */
	public function getConnection()
	{
		return $this->memcachedInstance;
	}
}

Check if memcache persistent connection not established before adding server to pool


<?php
/**
 * Created by PhpStorm.
 * User: etcinit
 * Date: 10/3/15
 * Time: 6:57 PM
 */

namespace Chromabits\Illuminated\Http\Factories;

use Chromabits\Illuminated\Http\ApiResponse;
use Chromabits\Illuminated\Http\Interfaces\ApiResponseFactoryInterface;
use Chromabits\Nucleus\Exceptions\LackOfCoffeeException;
use Chromabits\Nucleus\Foundation\BaseObject;
use Chromabits\Nucleus\Meditation\Interfaces\CheckResultInterface;

/**
 * Class ApiResponseFactory.
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Illuminated\Http\Factories
 */
class ApiResponseFactory extends BaseObject implements
    ApiResponseFactoryInterface
{
    /**
     * Create an API validation response from a CheckResultInterface.
     *
     * @param CheckResultInterface $result
     *
     * @return ApiResponse
     * @throws LackOfCoffeeException
     */
    public function fromCheckable(CheckResultInterface $result)
    {
        if ($result->passed()) {
            throw new LackOfCoffeeException(
                'You are trying to send a validation error response,'
                . ' but your check actually passed!'
            );
        }

        return new static([
            'missing' => $result->getMissing(),
            'validation' => $result->getFailed(),
        ], ApiResponse::STATUS_INVALID, [
            'One or more fields are invalid. Please check your input.',
        ]);
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: etcinit
 * Date: 10/3/15
 * Time: 6:57 PM
 */

namespace Chromabits\Illuminated\Http\Factories;

use Chromabits\Illuminated\Http\ApiResponse;
use Chromabits\Illuminated\Http\Interfaces\ApiResponseFactoryInterface;
use Chromabits\Nucleus\Exceptions\LackOfCoffeeException;
use Chromabits\Nucleus\Foundation\BaseObject;
use Chromabits\Nucleus\Meditation\Interfaces\CheckResultInterface;

/**
 * Class ApiResponseFactory.
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Illuminated\Http\Factories
 */
class ApiResponseFactory extends BaseObject implements
    ApiResponseFactoryInterface
{
    /**
     * Create an API validation response from a CheckResultInterface.
     *
     * @param CheckResultInterface $result
     *
     * @return ApiResponse
     * @throws LackOfCoffeeException
     */
    public function fromCheckable(CheckResultInterface $result)
    {
        if ($result->passed()) {
            throw new LackOfCoffeeException(
                'You are trying to send a validation error response,'
                . ' but your check actually passed!'
            );
        }

        return new ApiResponse([
            'missing' => $result->getMissing(),
            'validation' => $result->getFailed(),
        ], ApiResponse::STATUS_INVALID, [
            'One or more fields are invalid. Please check your input.',
        ]);
    }
}

Remove static call to constructor.

Remove static call to constructor.


<?php

use Sylius\Bundle\CoreBundle\Application\Kernel;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class AppKernel extends Kernel
{
    /**
     * {@inheritdoc}
     */
    public function registerBundles()
    {
        $bundles = [
            new Sylius\Bundle\AdminBundle\SyliusAdminBundle(),
            new Sylius\Bundle\ApiBundle\SyliusApiBundle(),
            new Sylius\Bundle\ShopBundle\SyliusShopBundle(),
            new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(),
            new FOS\OAuthServerBundle\FOSOAuthServerBundle(),
            new Snc\RedisBundle\SncRedisBundle(),
            new AppBundle\AppBundle(),
        ];

        return array_merge(parent::registerBundles(), $bundles);
    }
}

<?php

use Sylius\Bundle\CoreBundle\Application\Kernel;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class AppKernel extends Kernel
{
    /**
     * {@inheritdoc}
     */
    public function registerBundles()
    {
        $bundles = [
            new Sylius\Bundle\AdminBundle\SyliusAdminBundle(),
            new Sylius\Bundle\ApiBundle\SyliusApiBundle(),
            new Sylius\Bundle\ShopBundle\SyliusShopBundle(),
            new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(),
            new FOS\OAuthServerBundle\FOSOAuthServerBundle(),
            new AppBundle\AppBundle(),
        ];

        if ('prod' === $this->getEnvironment()) {
            $bundles[] = new Snc\RedisBundle\SncRedisBundle();
        }

        return array_merge(parent::registerBundles(), $bundles);
    }
}

Include Redis only in prod

Include Redis only in prod


<?php

namespace Omnipay\PaymentExpress\Message;

/**
 * PaymentExpress PxPost Create Credit Card Request
 */
class PxPayCreateCardRequest extends PxPayAuthorizeRequest
{
    public function getData()
    {
        $this->setAmount('1.00');
        $this->setCurrency('NZD');

        $data = parent::getData();
        $data->EnableAddBillCard = 1;

        return $data;
    }
}

<?php

namespace Omnipay\PaymentExpress\Message;

/**
 * PaymentExpress PxPost Create Credit Card Request
 */
class PxPayCreateCardRequest extends PxPayAuthorizeRequest
{
    public function getData()
    {
        $amount = $this->getAmount() ? $this->getAmount() : '1.00';
        $this->setAmount($amount);

        $this->setCurrency('NZD');

        $data = parent::getData();
        $data->EnableAddBillCard = 1;

        return $data;
    }
}

Allow amount to be set by the calling function as it is valid to pass a greater amount as part of the initial payment express transaction


<?php

namespace Lily\Test\Usage;

use Symfony\Component\DomCrawler\Crawler;

use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;

use Lily\Util\Request;
use Lily\Util\Response;

class DescribeTestingTest extends \PHPUnit_Framework_TestCase
{
    private function applicationToTest()
    {
        $html = file_get_contents(dirname(__FILE__).'/example.html');
        return
            new MiddlewareApplication(
                array(
                    new RoutedApplication(
                        array(
                            array('POST', '/form', $html)))));
    }

    private function applicationResponse($request)
    {
        $application = $this->applicationToTest();
        return $application($request);
    }

    private function crawler($html)
    {
        return new Crawler($html);
    }

    private function filterNotEmpty($crawler, $filter)
    {
        return $crawler->filter($filter)->count() > 0;
    }

    private function responseBodyHasClass($response, $class)
    {
        return $this->filterNotEmpty($this->crawler($response['body']), $class);
    }

    public function testFormErrorShouldBeShown()
    {
        $response = $this->applicationResponse(Request::post('/form'));
        $this->assertTrue($this->responseBodyHasClass($response, '.error'));
    }

    public function testFormShouldSuccessfullySubmit()
    {
        $response = $this->applicationResponse(Request::post('/form'));
        $this->assertTrue($this->responseBodyHasClass($response, 'h1.success'));
    }
}

<?php

namespace Lily\Test\Usage;

use Symfony\Component\DomCrawler\Crawler;

use Lily\Application\MiddlewareApplication;
use Lily\Application\RoutedApplication;

use Lily\Util\Request;
use Lily\Util\Response;

class DescribeTestingTest extends \PHPUnit_Framework_TestCase
{
    private function applicationToTest()
    {
        $html = file_get_contents(dirname(__FILE__).'/example.html');
        return
            new MiddlewareApplication(
                array(
                    new RoutedApplication(
                        array(
                            array('POST', '/form', $html)))));
    }

    private function applicationResponse($request)
    {
        $application = $this->applicationToTest();
        return $application($request);
    }

    private function filterNotEmpty($html, $filter)
    {
        $crawler = new Crawler($html);
        return $crawler->filter($filter)->count() > 0;
    }

    private function responseBodyHasClass($response, $class)
    {
        return $this->filterNotEmpty($response['body'], $class);
    }

    public function testFormErrorShouldBeShown()
    {
        $response = $this->applicationResponse(Request::post('/form'));
        $this->assertTrue($this->responseBodyHasClass($response, '.error'));
    }

    public function testFormShouldSuccessfullySubmit()
    {
        $response = $this->applicationResponse(Request::post('/form'));
        $this->assertTrue($this->responseBodyHasClass($response, 'h1.success'));
    }
}

Remove some complexity caused by refactorings


<?php

/**
 * This file is part of the Liquid package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @package Liquid
 */

namespace Liquid\Tag;

use Liquid\TestCase;

class TagUnlessTest extends TestCase
{
	public function testTrueEqlTrue() {
		$text = " {% unless true == true %} true {% else %} false {% endunless %} ";
		$expected = "  false  ";
		$this->assertTemplateResult($expected, $text);
	}

	public function testTrueNotEqlTrue() {
		$text = " {% unless true != true %} true {% else %} false {% endunless %} ";
		$expected = "  true  ";
		$this->assertTemplateResult($expected, $text);
	}
}

<?php

/**
 * This file is part of the Liquid package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @package Liquid
 */

namespace Liquid\Tag;

use Liquid\TestCase;

class TagUnlessTest extends TestCase
{
	public function testTrueEqlTrue() {
		$text = " {% unless true == true %} true {% else %} false {% endunless %} ";
		$expected = "  false  ";
		$this->assertTemplateResult($expected, $text);
	}

	public function testTrueNotEqlTrue() {
		$text = " {% unless true != true %} true {% else %} false {% endunless %} ";
		$expected = "  true  ";
		$this->assertTemplateResult($expected, $text);
	}

	public function testWithVariable() {
		$text = " {% unless variable %} true {% else %} false {% endunless %} ";
		$expected = "  false  ";
		$this->assertTemplateResult($expected, $text, array('variable' => true));
	}
}

Test TagUnless with a variable

Test TagUnless with a variable


<?php

namespace Kutny\AutowiringBundle\Compiler;

use ReflectionMethod;
use Symfony\Component\DependencyInjection\Definition;

class ClassConstructorFiller
{

    private $parameterProcessor;

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

    public function autowireParams(ReflectionMethod $constructor, Definition $definition, array $classes)
    {
        $explicitlyDefinedArguments = $definition->getArguments();
        $allArguments = array();

        foreach ($constructor->getParameters() as $index => $parameter) {
            if (array_key_exists($index, $explicitlyDefinedArguments)) {
                $allArguments[] = $explicitlyDefinedArguments[$index];
            } else {
                $allArguments[] = $this->parameterProcessor->getParameterValue($parameter, $classes);
            }
        }

        $definition->setArguments($allArguments);
    }
}

<?php

namespace Kutny\AutowiringBundle\Compiler;

use ReflectionMethod;
use Symfony\Component\DependencyInjection\Definition;

class ClassConstructorFiller
{

    private $parameterProcessor;

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

    public function autowireParams(ReflectionMethod $constructor, Definition $definition, array $classes)
    {
        $explicitlyDefinedArguments = $definition->getArguments();
        $allArguments = array();

        foreach ($constructor->getParameters() as $index => $parameter) {
            if (array_key_exists($index, $explicitlyDefinedArguments)) {
                $allArguments[] = $explicitlyDefinedArguments[$index];
            } else if ($parameter->isDefaultValueAvailable()) {
                $allArguments[] = $parameter->getDefaultValue();
            } else {
                $allArguments[] = $this->parameterProcessor->getParameterValue($parameter, $classes);
            }
        }

        $definition->setArguments($allArguments);
    }
}

Support for default values in constructor added


<?php
/**
 * Apply patches to support newer PHP versions.
 */

$patches = [
    'phpunit_mock_objects.patch' => 'phpunit/phpunit-mock-objects',
    'phpunit_php7.patch' => 'phpunit/phpunit',
    'phpunit_php8.patch' => 'phpunit/phpunit',
];

foreach ($patches as $patch => $package) {
    chdir(__DIR__.'/../vendor/'.$package);
    passthru(sprintf('patch -p1 -f < ../../../tests/%s', $patch));
}

<?php
/**
 * Apply patches to support newer PHP versions.
 */

$patches = array(
    'phpunit_mock_objects.patch' => 'phpunit/phpunit-mock-objects',
    'phpunit_php7.patch' => 'phpunit/phpunit',
    'phpunit_php8.patch' => 'phpunit/phpunit',
);

foreach ($patches as $patch => $package) {
    chdir(__DIR__.'/../vendor/'.$package);
    passthru(sprintf('patch -p1 -f < ../../../tests/%s', $patch));
}

Switch to old array style syntax to support PHP 5.3