<?php
declare(strict_types = 1);

namespace Apha\CommandHandling;

use Apha\Message\Command;

class SimpleCommandBus extends CommandBus
{
    /**
     * @var array
     */
    private $commandHandlerMap;

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

    /**
     * @param string $commandClass
     * @param CommandHandler $handler
     * @throws CommandHandlerAlreadyExistsException
     */
    public function addHandler(string $commandClass, CommandHandler $handler)
    {
        if (array_key_exists($commandClass, $this->commandHandlerMap)) {
            throw new CommandHandlerAlreadyExistsException($commandClass);
        }

        $this->commandHandlerMap[$commandClass] = $handler;
    }

    /**
     * @param Command $command
     * @throws NoCommandHandlerException
     */
    public function send(Command $command)
    {
        $commandClassName = get_class($command);

        if (!array_key_exists($commandClassName, $this->commandHandlerMap)) {
            throw new NoCommandHandlerException($command);
        }

        /* @var $handler CommandHandler */
        $handler = $this->commandHandlerMap[$commandClassName];
        $handler->handle($command);
    }
}

<?php
declare(strict_types = 1);

namespace Apha\CommandHandling;

use Apha\Message\Command;

class SimpleCommandBus extends CommandBus
{
    /**
     * @var array
     */
    private $commandHandlerMap = [];

    /**
     * @param array $commandHandlerMap
     */
    public function __construct(array $commandHandlerMap)
    {
        foreach ($commandHandlerMap as $commandClass => $handler) {
            $this->addHandler($commandClass, $handler);
        }
    }

    /**
     * @param string $commandClass
     * @param CommandHandler $handler
     * @throws CommandHandlerAlreadyExistsException
     */
    public function addHandler(string $commandClass, CommandHandler $handler)
    {
        if (array_key_exists($commandClass, $this->commandHandlerMap)) {
            throw new CommandHandlerAlreadyExistsException($commandClass);
        }

        $this->commandHandlerMap[$commandClass] = $handler;
    }

    /**
     * @param Command $command
     * @throws NoCommandHandlerException
     */
    public function send(Command $command)
    {
        $commandClassName = get_class($command);

        if (!array_key_exists($commandClassName, $this->commandHandlerMap)) {
            throw new NoCommandHandlerException($command);
        }

        /* @var $handler CommandHandler */
        $handler = $this->commandHandlerMap[$commandClassName];
        $handler->handle($command);
    }
}

Make sure all handlers are valid CommandHandlers.


<?php

declare(strict_types=1);

/**
 * This file is part of Laravel Zero.
 *
 * (c) Nuno Maduro <enunomaduro@gmail.com>
 *
 *  For the full copyright and license information, please view the LICENSE
 *  file that was distributed with this source code.
 */

namespace LaravelZero\Framework\Bootstrap;

use Dotenv\Dotenv;
use LaravelZero\Framework\Application;
use LaravelZero\Framework\Contracts\BoostrapperContract;
use LaravelZero\Framework\Providers\Build\Build;

/**
 * @internal
 */
final class BuildLoadEnvironmentVariables implements BoostrapperContract
{
    /**
     * @var \LaravelZero\Framework\Providers\Build\Build
     */
    private $build;

    /**
     * BuildLoadEnvironmentVariables constructor.
     *
     * @param \LaravelZero\Framework\Providers\Build\Build $build
     */
    public function __construct(Build $build)
    {
        $this->build = $build;
    }

    /**
     * {@inheritdoc}
     */
    public function bootstrap(Application $app): void
    {
        /*
         * Override environment variables with the environment file along side the Phar file.
         */
        if ($this->build->shouldUseEnvironmentFile()) {
            Dotenv::create($this->build->getDirectoryPath(), $this->build->environmentFile())->overload();
        }
    }
}

<?php

declare(strict_types=1);

/**
 * This file is part of Laravel Zero.
 *
 * (c) Nuno Maduro <enunomaduro@gmail.com>
 *
 *  For the full copyright and license information, please view the LICENSE
 *  file that was distributed with this source code.
 */

namespace LaravelZero\Framework\Bootstrap;

use Dotenv\Dotenv;
use LaravelZero\Framework\Application;
use LaravelZero\Framework\Contracts\BoostrapperContract;
use LaravelZero\Framework\Providers\Build\Build;

/**
 * @internal
 */
final class BuildLoadEnvironmentVariables implements BoostrapperContract
{
    /**
     * @var \LaravelZero\Framework\Providers\Build\Build
     */
    private $build;

    /**
     * BuildLoadEnvironmentVariables constructor.
     *
     * @param \LaravelZero\Framework\Providers\Build\Build $build
     */
    public function __construct(Build $build)
    {
        $this->build = $build;
    }

    /**
     * {@inheritdoc}
     */
    public function bootstrap(Application $app): void
    {
        /*
         * Override environment variables with the environment file along side the Phar file.
         */
        if ($this->build->shouldUseEnvironmentFile()) {
            Dotenv::createMutable($this->build->getDirectoryPath(), $this->build->environmentFile())->load();
        }
    }
}

Update DotEnv registration to version 4

Update DotEnv registration to version 4


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

if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
	header("location: index.php");
	exit;
}

/**
 * @param $installer
 */
function upgrade_20170127_remove_templates_c_tiki($installer)
{
	$dirname = 'templates_c';
	if (is_dir($dirname)) {
		$dir_handle = opendir($dirname);
	}
	if (!$dir_handle) {
		return false;
	}
	while($file = readdir($dir_handle)) {
		if ($file != "." && $file != "..") {
			if (!is_dir($dirname."/".$file))
				unlink($dirname."/".$file);
			else
				delete_directory($dirname.'/'.$file);
		}
	}
	closedir($dir_handle);
	rmdir($dirname);
}

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

if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
	header("location: index.php");
	exit;
}

/**
 * @param $installer
 * @return void|bool
 */
function upgrade_20170127_remove_templates_c_tiki($installer)
{
	$dir_handle = false;
	$dirname = 'templates_c';
	if (is_dir($dirname)) {
		$dir_handle = opendir($dirname);
	}
	if (! $dir_handle) {
		return false;
	}
	while ($file = readdir($dir_handle)) {
		if ($file != "." && $file != "..") {
			if (! is_dir($dirname . "/" . $file)) {
				unlink($dirname . "/" . $file);
			} else {
				delete_directory($dirname . '/' . $file);
			}
		}
	}
	closedir($dir_handle);
	rmdir($dirname);
}

[REF] Fix notice with $dir_handle not being defined, improve code formatting

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


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

if ($argc < 4)
	die ("Required parameters not received. Run script in the following format: php setPartnerBroadcastingUrls.php {partnerId} {parimary broadcast URL} {HTTP playback URL} [{secondary broadcast URL}] [{HTTPS playback URL}]");

$partnerId = $argv[1];
$primaryBroadcatUrl =  $argv[2];
$httpPlaybackUrl = $argv[3];

$secondaryBroadcastUrl = null;
if (isset($argv[4]))
	$secondaryBroadcastUrl = $argv[4];

$httpsPlaybackUrl = null;
if (isset($argv[5]))
	$httpsPlaybackUrl = $argv[5];

$partner = PartnerPeer::retrieveByPK($partnerId);
if (!$partner)
{
	die ("Partner with id {$partnerId} not found.");
}

$partner->setBroadcastUrlManager('kPartnerBroadcastUrlManager');
$partner->setPrimaryBroadcastUrl($primaryBroadcatUrl);
$partner->setSecondaryBroadcastUrl($secondaryBroadcastUrl);

$liveStreamConfigurations = array ('http' => $httpPlaybackUrl);
$liveStreamConfigurations = array ('https' => $httpsPlaybackUrl);
$partner->setLiveStreamPlaybackUrlConfigurations($liveStreamConfigurations);
$partner->save();

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

if ($argc < 4)
	die ("Required parameters not received. Run script in the following format: php setPartnerBroadcastingUrls.php {partnerId} {parimary broadcast URL} {HTTP playback URL} [{secondary broadcast URL}] [{HTTPS playback URL}]");

$partnerId = $argv[1];
$primaryBroadcatUrl =  $argv[2];
$httpPlaybackUrl = $argv[3];

$secondaryBroadcastUrl = null;
if (isset($argv[4]) && $argv[4] != 0)
	$secondaryBroadcastUrl = $argv[4];

$httpsPlaybackUrl = null;
if (isset($argv[5]))
	$httpsPlaybackUrl = $argv[5];

$partner = PartnerPeer::retrieveByPK($partnerId);
if (!$partner)
{
	die ("Partner with id {$partnerId} not found.");
}

$partner->setBroadcastUrlManager('kPartnerBroadcastUrlManager');
$partner->setPrimaryBroadcastUrl($primaryBroadcatUrl);
$partner->setSecondaryBroadcastUrl($secondaryBroadcastUrl);

$liveStreamConfigurations = array ('http' => $httpPlaybackUrl);
if($httpsPlaybackUrl)
	$liveStreamConfigurations = array ('https' => $httpsPlaybackUrl);

$partner->setLiveStreamPlaybackUrlConfigurations($liveStreamConfigurations);
$partner->save();

Add arguments validations: 1. Enable excluding secondaryBroadcstingUrl. 2. Validate https playback url was provided before setting its value.


<?php

$rules = [
    '@Symfony' => true,
    'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced'],
    'phpdoc_to_comment' => false,
    'phpdoc_align' => false,
    'php_unit_method_casing' => false,
];

$finder = PhpCsFixer\Finder::create()
    ->in(__DIR__)
;

$config = new PhpCsFixer\Config();
return $config
    ->setFinder($finder)
    ->setRiskyAllowed(true)
    ->setRules($rules)
    ->setUsingCache(true)
;

<?php

$rules = [
    '@Symfony' => true,
    'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced'],
    'phpdoc_to_comment' => false,
    'phpdoc_align' => false,
    'php_unit_method_casing' => false,
    'phpdoc_separation' => ['groups' => [['test', 'dataProvider']]],
];

$finder = PhpCsFixer\Finder::create()
    ->in(__DIR__)
;

$config = new PhpCsFixer\Config();
return $config
    ->setFinder($finder)
    ->setRiskyAllowed(true)
    ->setRules($rules)
    ->setUsingCache(true)
;

Add php-cs-fixer config for test annotations


@extends('layout')

@section('body')

Reports

                @for ($y = 2017; $y <= date('Y'); $y ++)
                    @for ($m = 1; $m <= 12; $m ++)
                        @if (App\Budget::where('user_id', Auth::user()->id)->whereMonth('date', $m)->whereYear('date', $y)->count())

                                    {{ $m }}, {{ $y }}

                        @endif
                    @endfor
                @endfor

@endsection

@extends('layout')

@section('body')

Reports

                @for ($y = 2017; $y <= date('Y'); $y ++)
                    @for ($m = 1; $m <= 12; $m ++)
                        @if (App\Budget::where('user_id', Auth::user()->id)->whereMonth('date', $m)->whereYear('date', $y)->count())

                                    @lang('months.' . $m), {{ $y }}

                        @endif
                    @endfor
                @endfor

@endsection

Use localization to label months in reports's index view


<?php
namespace Sandstorm\UserManagement\Security;

use TYPO3\Flow\Mvc\ActionRequest;
use TYPO3\Flow\Mvc\RequestInterface;
use TYPO3\Flow\Security\RequestPatternInterface;

/**
 * A request pattern that can detect and match "frontend" and "backend" mode
 */
class NeosRequestPattern implements RequestPatternInterface
{
    const AREA_BACKEND = 'backend';
    const AREA_FRONTEND = 'frontend';

    /**
     * @var array
     */
    protected $options;

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

    /**
     * Matches a \TYPO3\Flow\Mvc\RequestInterface against its set pattern rules
     *
     * @param RequestInterface $request The request that should be matched
     * @return boolean TRUE if the pattern matched, FALSE otherwise
     */
    public function matchRequest(RequestInterface $request)
    {
        $shouldMatchBackend = ($this->options['area'] === self::AREA_FRONTEND) ? false : true;

        if (!$request instanceof ActionRequest) {
            return false;
        }
        $requestPath = $request->getHttpRequest()->getUri()->getPath();
        $requestPathMatchesBackend = substr($requestPath, 0, 5) === '/neos' || strpos($requestPath, '@') !== false;

        return $shouldMatchBackend === $requestPathMatchesBackend;
    }
}

<?php
namespace Sandstorm\UserManagement\Security;

use TYPO3\Flow\Mvc\ActionRequest;
use TYPO3\Flow\Mvc\RequestInterface;
use TYPO3\Flow\Security\RequestPatternInterface;

/**
 * A request pattern that can detect and match "frontend" and "backend" mode
 */
class NeosRequestPattern implements RequestPatternInterface
{
    const AREA_BACKEND = 'backend';
    const AREA_FRONTEND = 'frontend';

    /**
     * @var array
     */
    protected $options;

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

    /**
     * Matches a \TYPO3\Flow\Mvc\RequestInterface against its set pattern rules
     *
     * @param RequestInterface $request The request that should be matched
     * @return boolean TRUE if the pattern matched, FALSE otherwise
     */
    public function matchRequest(RequestInterface $request)
    {
        $shouldMatchBackend = ($this->options['area'] === self::AREA_FRONTEND) ? false : true;

        if (!$request instanceof ActionRequest) {
            return false;
        }
        $requestPath = $request->getHttpRequest()->getUri()->getPath();
        $requestPathMatchesBackend = substr($requestPath, 0, 5) === '/neos' || substr($requestPath, 0, 6) === '/setup' || strpos($requestPath, '@') !== false;

        return $shouldMatchBackend === $requestPathMatchesBackend;
    }
}

BUGFIX: Fix bug in request pattern that caused broken setup


<?php declare(strict_types=1);

namespace Cjsaylor\Domain;

use Cjsaylor\Domain\Collection\CollectionInterface;
use Cjsaylor\Domain\Entity\EntityInterface;
use Cjsaylor\Domain\Behavior\Accessable;
use Cjsaylor\Domain\Behavior\Iteratable;
use Cjsaylor\Domain\Behavior\Countable;
use Cjsaylor\Domain\Collection\CollectionTrait;
use Cjsaylor\Domain\Collection\Collectable;
use Cjsaylor\Domain\Entity\EntityTrait;

abstract class CollectionEntity implements CollectionInterface, EntityInterface, Collectable
{
    use Accessable, Iteratable, Countable;
    use CollectionTrait {
        CollectionTrait::toArray as collectionToArray;
    }
    use EntityTrait {
        EntityTrait::toArray as entityToArray;
    }

    /**
     * Array of Entities.
     *
     * @var \ArrayObject
     */
    protected $entries;

    /**
     * Constructor.
     *
     * @param array $initialEntityData
     */
    public function __construct(array $initialEntityData = [])
    {
        $this->entries = new \ArrayObject();
        $this->initialize($initialEntityData);
    }

    /**
     * Array representation of this collection entity.
     * @return array
     */
    public function toArray() : array
    {
        $output = $this->entityToArray();
        $output['entries'] = $this->collectionToArray();

        return $output;
    }
}

<?php declare(strict_types=1);

namespace Cjsaylor\Domain;

use Cjsaylor\Domain\Collection\CollectionInterface;
use Cjsaylor\Domain\Entity\EntityInterface;
use Cjsaylor\Domain\Behavior\Accessable;
use Cjsaylor\Domain\Behavior\Iteratable;
use Cjsaylor\Domain\Behavior\Countable;
use Cjsaylor\Domain\Collection\CollectionTrait;
use Cjsaylor\Domain\Collection\Collectable;
use Cjsaylor\Domain\Entity\EntityTrait;

abstract class CollectionEntity implements CollectionInterface, EntityInterface, Collectable
{
    use Accessable, Iteratable, Countable;
    use CollectionTrait {
        CollectionTrait::toArray as collectionToArray;
    }
    use EntityTrait {
        EntityTrait::toArray as entityToArray;
    }

    /**
     * Array of Entities.
     *
     * @var \ArrayObject
     */
    protected $entries;

    /**
     * Constructor.
     *
     * @param array $initialEntityData
     * @param Collectable[] ...$entries Optional entries to intialize the collection
     */
    public function __construct(array $initialEntityData = [], Collectable ...$entries)
    {
        $this->entries = new \ArrayObject($entries);
        $this->initialize($initialEntityData);
    }

    /**
     * Array representation of this collection entity.
     * @return array
     */
    public function toArray() : array
    {
        $output = $this->entityToArray();
        $output['entries'] = $this->collectionToArray();

        return $output;
    }
}

Allow collection entities to be intialized with a set.


<?php

namespace Badawy\Embedly;

use Illuminate\Support\ServiceProvider;

class EmbedlyServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/config/Embedly.php' => config_path('embedly.php'),
        ]);
    }

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

        $this->app['Embedly'] = $this->app->share(
            function($app)
            {
                return new Embedly();
            }
        );
    }
}

<?php

namespace Badawy\Embedly;

use Illuminate\Support\ServiceProvider;

class EmbedlyServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/config/Embedly.php' => config_path('embedly.php'),
        ]);
    }

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

        $this->app->singleton('Embedly', function(){
            return new Embedly();
        });
    }
}

Switch from share to singleton

Switch from share to singleton

The share method has been deprecated.


<?php

namespace PHPMD;

class Fingerprint
{
    const OVERRIDE_RULES = [
      "Controversial/CamelCaseVariableName",
      "Controversial/CamelCasePropertyName",
      "CyclomaticComplexity",
      "Design/LongClass",
      "Design/LongMethod",
      "Design/LongParameterList",
      "Design/NpathComplexity",
      "Design/NumberOfChildren",
      "Design/TooManyFields",
      "Design/TooManyMethods",
      "Design/TooManyPublicMethods",
      "Design/WeightedMethodCount",
      "ExcessivePublicCount",
      "Naming/ShortMethodName",
    ];
    private $name;
    private $path;
    private $rule;

    public function __construct($path, $rule, $name)
    {
        $this->path = $path;
        $this->rule = $rule;
        $this->name = $name;
    }

    public function compute()
    {
        $fingerprint = null;

        if (in_array($this->rule, self::OVERRIDE_RULES)) {
            $fingerprint = md5($this->path . $this->rule . $this->name);
        }

        return $fingerprint;
    }
}

<?php

namespace PHPMD;

class Fingerprint
{
    const OVERRIDE_RULES = [
      "Controversial/CamelCaseVariableName",
      "Controversial/CamelCasePropertyName",
      "CyclomaticComplexity",
      "Design/CouplingBetweenObjects",
      "Design/LongClass",
      "Design/LongMethod",
      "Design/LongParameterList",
      "Design/NpathComplexity",
      "Design/NumberOfChildren",
      "Design/TooManyFields",
      "Design/TooManyMethods",
      "Design/TooManyPublicMethods",
      "Design/WeightedMethodCount",
      "ExcessivePublicCount",
      "Naming/ShortMethodName",
    ];
    private $name;
    private $path;
    private $rule;

    public function __construct($path, $rule, $name)
    {
        $this->path = $path;
        $this->rule = $rule;
        $this->name = $name;
    }

    public function compute()
    {
        $fingerprint = null;

        if (in_array($this->rule, self::OVERRIDE_RULES)) {
            $fingerprint = md5($this->path . $this->rule . $this->name);
        }

        return $fingerprint;
    }
}

Use internal fingerprint for Design/CouplingBetweenObjects issues

This is a similar fix to d419bbb2228d49bf23c8ed23c25295bf0f8b416b.  This
type of issue should use a more flexible fingerprint (path, rule, method
name) instead of the source-based default fingerprint.


<?php
/**
 * Header bar template part.
 *
 * @package AMP
 */

?>

		<a href="<?php echo esc_url( $this->get( 'home_url' ) ); ?>">
			<?php $site_icon_url = $this->get( 'site_icon_url' ); ?>
			<?php if ( $site_icon_url ) : ?>
				<amp-img src="<?php echo esc_url( $site_icon_url ); ?>" width="32" height="32" class="amp-wp-site-icon"></amp-img>
			<?php endif; ?>

				<?php echo esc_html( wptexturize( $this->get( 'blog_name' ) ) ); ?>

Remove pound symbol from header id

Remove pound symbol from header id

Removed the # symbol from <header> id. It was causing 404 errors and
prevented the "Back to top" link in the footer from working.


<?php

require_once __DIR__.'/../lib/base.php';

if(!class_exists('PHPUnit_Framework_TestCase')){
	require_once('PHPUnit/Autoload.php');
}

//SimpleTest compatibility
abstract class UnitTestCase extends PHPUnit_Framework_TestCase{
	function assertEqual($expected, $actual, $string=''){
		$this->assertEquals($expected, $actual, $string);
	}

	function assertNotEqual($expected, $actual, $string=''){
		$this->assertNotEquals($expected, $actual, $string);
	}

	static function assertTrue($actual, $string=''){
		parent::assertTrue((bool)$actual, $string);
	}

	static function assertFalse($actual, $string=''){
		parent::assertFalse((bool)$actual, $string);
	}
}

OC_Hook::clear();
OC_Log::$enabled = false;

<?php

global $RUNTIME_NOAPPS;
$RUNTIME_NOAPPS = true;
require_once __DIR__.'/../lib/base.php';

if(!class_exists('PHPUnit_Framework_TestCase')){
	require_once('PHPUnit/Autoload.php');
}

//SimpleTest compatibility
abstract class UnitTestCase extends PHPUnit_Framework_TestCase{
	function assertEqual($expected, $actual, $string=''){
		$this->assertEquals($expected, $actual, $string);
	}

	function assertNotEqual($expected, $actual, $string=''){
		$this->assertNotEquals($expected, $actual, $string);
	}

	static function assertTrue($actual, $string=''){
		parent::assertTrue((bool)$actual, $string);
	}

	static function assertFalse($actual, $string=''){
		parent::assertFalse((bool)$actual, $string);
	}
}

OC_Hook::clear();
OC_Log::$enabled = false;

Disable loading apps before starting tests


<?php
use Cake\Core\Plugin;

$findRoot = function ($root) {
	do {
		$lastRoot = $root;
		$root = dirname($root);
		if (is_dir($root . '/vendor/cakephp/cakephp')) {
			return $root;
		}
	} while ($root !== $lastRoot);
	throw new \Exception('Cannot find the root of the application, unable to run tests');
};

$root = $findRoot(__FILE__);
unset($findRoot);
chdir($root);
if (file_exists($root . '/config/bootstrap.php')) {
	//require $root . '/config/bootstrap.php';
	//return;
}
require $root . '/vendor/cakephp/cakephp/tests/bootstrap.php';
$loader = require $root . '/vendor/autoload.php';

$loader->setPsr4('Cake\\', './vendor/cakephp/cakephp/src');
$loader->setPsr4('Cake\Test\\', './vendor/cakephp/cakephp/tests');
$loader->setPsr4('Burzum\Imagine\\', './vendor/burzum/cakephp-imagine-plugin/src');

Plugin::load('Burzum/FileStorage', [
	'path' => dirname(__FILE__, 2) . DS,
	//'autoload' => true,
	//'bootstrap' => true
]);

Plugin::load('Burzum/Imagine', [
	'path' => dirname(__FILE__, 2) . DS,
	'autoload' => true,
	'bootstrap' => true
]);

<?php
use Cake\Core\Plugin;

$findRoot = function ($root) {
	do {
		$lastRoot = $root;
		$root = dirname($root);
		if (is_dir($root . '/vendor/cakephp/cakephp')) {
			return $root;
		}
	} while ($root !== $lastRoot);
	throw new \Exception('Cannot find the root of the application, unable to run tests');
};

$root = $findRoot(__FILE__);
unset($findRoot);
chdir($root);
//if (file_exists($root . '/config/bootstrap.php')) {
//	require $root . '/config/bootstrap.php';
//	return;
//}
require $root . '/vendor/cakephp/cakephp/tests/bootstrap.php';
$loader = require $root . '/vendor/autoload.php';

$loader->setPsr4('Cake\\', './vendor/cakephp/cakephp/src');
$loader->setPsr4('Cake\Test\\', './vendor/cakephp/cakephp/tests');
$loader->setPsr4('Burzum\Imagine\\', './vendor/burzum/cakephp-imagine-plugin/src');

Plugin::load('Burzum/FileStorage', [
	'path' => dirname(__FILE__, 2) . DS,
	//'autoload' => true,
	//'bootstrap' => true
]);

Plugin::load('Burzum/Imagine', [
	'path' => dirname(__FILE__, 2) . DS,
	'autoload' => true,
	'bootstrap' => true
]);

Comment out full if clause, not just body


<?php

// This file needs to parse without error in PHP < 5.3

if ( 'cli' !== PHP_SAPI ) {
	echo "Only CLI access.\n";
	die( -1 );
}

if ( version_compare( PHP_VERSION, '5.3.0', '<' ) ) {
	printf( "Error: EE requires PHP %s or newer. You are running version %s.\n", '5.3.0', PHP_VERSION );
	die( -1 );
}

define( 'EE_ROOT', dirname( __DIR__ ) );

include_once EE_ROOT . '/php/init-ee.php';

<?php

// This file needs to parse without error in PHP < 7.0

if ( 'cli' !== PHP_SAPI ) {
	echo "Only CLI access.\n";
	die( -1 );
}

if ( version_compare( PHP_VERSION, '7.0', '<' ) ) {
	printf( "Error: EE requires PHP %s or newer. You are running version %s.\n", '7.0', PHP_VERSION );
	die( -1 );
}

define( 'EE_ROOT', dirname( __DIR__ ) );

include_once EE_ROOT . '/php/init-ee.php';

Update php version check at start

Update php version check at start

Signed-off-by: Riddhesh Sanghvi <f8c90b0b72a59c76b108f89842786e39e7dc3e58@gmail.com>


<?php

namespace spec\Peterjmit\BlogBundle\Controller;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class BlogControllerSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Peterjmit\BlogBundle\Controller\BlogController');
    }

    function it_should_respond_to_index_action()
    {
        $response = $this->indexAction();

        $response->shouldHaveType('Symfony\Component\HttpFoundation\Response');
    }
}

<?php

namespace spec\Peterjmit\BlogBundle\Controller;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

use Symfony\Component\DependencyInjection\ContainerInterface;

class BlogControllerSpec extends ObjectBehavior
{
    function let(ContainerInterface $container)
    {
        $this->setContainer($container);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Peterjmit\BlogBundle\Controller\BlogController');
    }

    function it_should_respond_to_index_action()
    {
        $response = $this->indexAction();

        $response->shouldHaveType('Symfony\Component\HttpFoundation\Response');
    }
}

Fix controller not having access to container


<?php

namespace Studio\Parts;

use League\Flysystem\Filesystem;

abstract class AbstractPart implements PartInterface
{

    /**
     * @var PartInputInterface
     */
    protected $input;

    abstract public function setupPackage($composer, Filesystem $target);

    public function setInput(PartInputInterface $input)
    {
        $this->input = $input;

        return $this;
    }

    protected function copyTo($file, Filesystem $target, $targetName = null)
    {
        $targetName = $targetName ?: basename($file);

        $target->write($targetName, file_get_contents($file));
    }

}

<?php

namespace Studio\Parts;

use Closure;
use League\Flysystem\Filesystem;

abstract class AbstractPart implements PartInterface
{

    /**
     * @var PartInputInterface
     */
    protected $input;

    abstract public function setupPackage($composer, Filesystem $target);

    public function setInput(PartInputInterface $input)
    {
        $this->input = $input;

        return $this;
    }

    protected function copyTo($file, Filesystem $target, $targetName = null, Closure $handler = null)
    {
        $targetName = $targetName ?: basename($file);

        $content = file_get_contents($file);

        if ($handler) {
            $content = $handler($content);
        }

        $target->write($targetName, $content);
    }

}

Allow content handler closures when copying files.


<?php

namespace sequences;

include_once 'BottomlineWrapper.php';

/**
 * returns a wrapper instance, allows the value to be passed through multiple bottomline functions
 *
 * __::chain([0, 1, 2, 3, null])
 *   ->compact()
 *   ->prepend(4)
 *   ->value();
 * >> [4, 1, 2, 3]
 *
 * @param mixed $initialValue
 *
 * @return mixed
 *
 */
function chain($initialValue)
{
    return new \BottomlineWrapper($initialValue);
}

<?php

namespace sequences;

include_once 'BottomlineWrapper.php';

/**
 * Returns a wrapper instance, allows the value to be passed through multiple
 * bottomline functions.
 *
 * **Usage**
 *
 * ```php
 * __::chain([0, 1, 2, 3, null])
 *     ->compact()
 *     ->prepend(4)
 *     ->value()
 * ;
 * ```
 *
 * **Result**
 *
 * ```
 * [4, 1, 2, 3]
 * ```
 *
 * @param mixed $initialValue
 *
 * @return \__|\BottomlineWrapper|mixed
 */
function chain($initialValue)
{
    return new \BottomlineWrapper($initialValue);
}

Rewrite docs for sequences namespace

Rewrite docs for sequences namespace


<?php

namespace Oro\Bundle\EmailBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

use Oro\Bundle\EmailBundle\Cache\EmailCacheManager;
use Oro\Bundle\EmailBundle\Exception\LoadEmailBodyException;

class EmailBodySyncCommand extends ContainerAwareCommand
{
    /**
     * {@internaldoc}
     */
    protected function configure()
    {
        $this
            ->setName('oro:email:body-sync')
            ->setDescription('Synchronization email body')
            ->addOption(
                'id',
                null,
                InputOption::VALUE_REQUIRED,
                'The identifier of email to be synchronized.'
            );
    }

    /**
     * {@internaldoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var EmailCacheManager $emailCacheManager */
        $emailCacheManager = $this->getContainer()->get('oro_email.email.cache.manager');

        $emailId = $input->getOption('id');
        $email = $this->getContainer()->get("doctrine")->getRepository('OroEmailBundle:Email')->find($emailId);
        if ($email) {
            try {
                $emailCacheManager->ensureEmailBodyCached($email);
            } catch (LoadEmailBodyException $e) {
                // log
            }
        } else {
            // s
        }
    }
}

<?php

namespace Oro\Bundle\EmailBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

use Oro\Bundle\EmailBundle\Cache\EmailCacheManager;
use Oro\Bundle\EmailBundle\Exception\LoadEmailBodyException;
use Oro\Component\Log\OutputLogger;

class EmailBodySyncCommand extends ContainerAwareCommand
{
    /**
     * {@internaldoc}
     */
    protected function configure()
    {
        $this
            ->setName('oro:email:body-sync')
            ->setDescription('Synchronization email body')
            ->addOption(
                'id',
                null,
                InputOption::VALUE_REQUIRED,
                'The identifier of email to be synchronized.'
            );
    }

    /**
     * {@internaldoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $logger = new OutputLogger($output);

        /** @var EmailCacheManager $emailCacheManager */
        $emailCacheManager = $this->getContainer()->get('oro_email.email.cache.manager');

        $emailId = $input->getOption('id');
        $email = $this->getContainer()->get("doctrine")->getRepository('OroEmailBundle:Email')->find($emailId);
        if ($email) {
            try {
                $emailCacheManager->ensureEmailBodyCached($email);
                $output->writeln(sprintf('<info>Email body synced for email - %s</info>', $email->getId()));
            } catch (LoadEmailBodyException $e) {
                $warn = sprintf('Email body cannot be loaded for email - %s', $email->getId());
                $output->writeln('<info>' . $warn . '</info>');
                $logger->warning($warn);
            }
        }
    }
}

Modify sync email body. Sync at once.

CRM-2894: Modify sync email body. Sync at once.


<?php
namespace Muffin\Footprint\Test\TestCase\Event\Listener;

use Cake\Event\Event;
use Cake\ORM\Entity;
use Cake\TestSuite\TestCase;
use Muffin\Footprint\Event\FootprintListener;

class FootprintListenerTest extends TestCase
{
    public function setUp()
    {
        $this->listener = new FootprintListener();
    }

    public function testImplementedEvents()
    {
        $result = $this->listener->implementedEvents();
        $expected = [
            'Model.beforeSave' => ['priority' => -100, 'callable' => 'handleEvent'],
            'Model.beforeFind' => ['priority' => -100, 'callable' => 'handleEvent'],
            'Model.beforeValidate' => ['priority' => -100, 'callable' => 'handleEvent'],
        ];
        $this->assertEquals($expected, $result);
    }

    public function testHandleEvent()
    {
        $entity = new Entity(['id' => 1]);
        $this->listener->setUser($entity);

        $options = new \ArrayObject();
        $this->listener->handleEvent(
            new Event('Model.save'),
            new Entity(['title' => 'article']),
            $options
        );

        $this->assertSame($entity, $options['_footprint']);
    }
}

<?php
namespace Muffin\Footprint\Test\TestCase\Event\Listener;

use Cake\Event\Event;
use Cake\ORM\Entity;
use Cake\TestSuite\TestCase;
use Muffin\Footprint\Event\FootprintListener;

class FootprintListenerTest extends TestCase
{
    public function setUp()
    {
        $this->listener = new FootprintListener();
    }

    public function testImplementedEvents()
    {
        $result = $this->listener->implementedEvents();
        $expected = [
            'Model.beforeSave' => ['priority' => -100, 'callable' => 'handleEvent'],
            'Model.beforeFind' => ['priority' => -100, 'callable' => 'handleEvent'],
            'Model.beforeValidate' => ['priority' => -100, 'callable' => 'handleEvent'],
            'Model.beforeDelete' => ['priority' => -100, 'callable' => 'handleEvent'],
        ];
        $this->assertEquals($expected, $result);
    }

    public function testHandleEvent()
    {
        $entity = new Entity(['id' => 1]);
        $this->listener->setUser($entity);

        $options = new \ArrayObject();
        $this->listener->handleEvent(
            new Event('Model.save'),
            new Entity(['title' => 'article']),
            $options
        );

        $this->assertSame($entity, $options['_footprint']);
    }
}

Add new implemented event to test

Add new implemented event to test


<?php

namespace LastFmApi\Exception;
/**
 * NotAuthenticatedException
 *
 * @author Marcos Peña
 */
class NotAuthenticatedException extends LastFmApiExeption
{
}

<?php

namespace LastFmApi\Exception;
/**
 * NotAuthenticatedException
 *
 * @author Marcos Peña
 */
class NotAuthenticatedException extends LastFmApiException
{
}

Fix missing « c » char on LastFmApiException.php


<?php

namespace fennecweb\ajax\details;

use \PDO as PDO;

/**
 * Web Service.
 * Returns trait information to a list of organism ids
 */
class TraitsOfOrganisms extends \fennecweb\WebService
{
    private $db;
    /**
     * @param $querydata['organism_ids' => [13,7,12,5]]
     * @returns Array $result
     * <code>
     * array(trait_entry_id => cvterm);
     * </code>
     */
    public function execute($querydata)
    {
        $this->db = $this->openDbConnection($querydata);
        $organism_ids = $querydata['organism_ids'];
        var_dump($organism_ids);
        $result = array();
        return $result;
    }
}

<?php

namespace fennecweb\ajax\details;

use \PDO as PDO;

/**
 * Web Service.
 * Returns trait information to a list of organism ids
 */
class TraitsOfOrganisms extends \fennecweb\WebService
{
    private $db;
    /**
     * @param $querydata['organism_ids' => [13,7,12,5]]
     * @returns Array $result
     * <code>
     * array(trait_entry_id => cvterm);
     * </code>
     */
    public function execute($querydata)
    {
        $this->db = $this->openDbConnection($querydata);
        $organism_ids = $querydata['organism_ids'];
        $placeholders = implode(',', array_fill(0, count($organism_ids), '?'));
        var_dump($placeholders);
        $query_get_traits_to_organisms = <<<EOF
SELECT *
    FROM trait_entry WHERE organism_id IN ($placeholders)
EOF;
        $stm_get_traits_to_organisms = $this->db->prepare($query_get_traits_to_organisms);
        $stm_get_traits_to_organisms->execute($organism_ids);

        $result = array();
        return $result;
    }
}

Add sql stm for selecting trait_entry_ids to a list of organism_ids


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

namespace Zend\Mvc\Service;

use Zend\Form\FormElementManager;
use Zend\ServiceManager\ServiceLocatorInterface;

class FormElementManagerFactory extends AbstractPluginManagerFactory
{
    const PLUGIN_MANAGER_CLASS = 'Zend\Form\FormElementManager';

    /**
     * Create and return the MVC controller plugin manager
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return FormElementManager
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $plugins = parent::createService($serviceLocator);
        return $plugins;
    }
}

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

namespace Zend\Mvc\Service;

use Zend\Form\Form;
use Zend\Form\FormElementManager;
use Zend\ServiceManager\ServiceLocatorInterface;

class FormElementManagerFactory extends AbstractPluginManagerFactory
{
    const PLUGIN_MANAGER_CLASS = 'Zend\Form\FormElementManager';

    /**
     * Create and return the MVC controller plugin manager
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return FormElementManager
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $plugins = parent::createService($serviceLocator);
        if ($serviceLocator->has('Di')) {
            $di = $serviceLocator->get('Di');
            $im = $di->instanceManager();
            if (!$im->getTypePreferences('Zend\Form\FormInterface')) {
                $form = new Form;
                $im->setTypePreference('Zend\Form\FormInterface', array($form));
            }
            $plugins->addPeeringServiceManager($serviceLocator);
            $plugins->setRetrieveFromPeeringManagerFirst(true);
        }
        return $plugins;
    }
}

Fix conflict AbstractPluginManager::valdatePlugin with DiAbstractFactory


@extends('layouts/master')

@section('content')

Come chat on Freenode at #capisso

@stop

Set the IRC webchat widget's width to 100%


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Payment extends Model
{
    use SoftDeletes;

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['method_presentation'];

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

    /**
     * Get all of the owning payable models
     */
    public function payable()
    {
        return $this->morphTo();
    }

    /**
     * Get the User associated with the Payment model.
     */
    public function user()
    {
        return $this->belongsTo('App\User', 'recorded_by');
    }

    /**
     * Get the presentation-ready format of a Payment Method
     *
     * @return String
     */
    public function getMethodPresentationAttribute()
    {
        $valueMap = array(
            'cash' => 'Cash',
            'squarecash' => 'Square Cash',
            'check' => 'Check',
            'swipe' => 'Swiped Card'
        );

        $method = $this->method;

        if (array_key_exists($method, $valueMap)) {
            return $valueMap[$this->method];
        } else {
            return null;
        }
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Payment extends Model
{
    use SoftDeletes;

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['method_presentation'];

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

    /**
     * Get all of the owning payable models
     */
    public function payable()
    {
        return $this->morphTo();
    }

    /**
     * Get the User associated with the Payment model.
     */
    public function user()
    {
        return $this->belongsTo('App\User', 'recorded_by');
    }

    /**
     * Get the presentation-ready format of a Payment Method
     *
     * @return String
     */
    public function getMethodPresentationAttribute()
    {
        $valueMap = array(
            'cash' => 'Cash',
            'squarecash' => 'Square Cash',
            'check' => 'Check',
            'swipe' => 'Swiped Card',
            'square' => 'Square'
        );

        $method = $this->method;

        if (array_key_exists($method, $valueMap)) {
            return $valueMap[$this->method];
        } else {
            return null;
        }
    }
}

Add Square to presentation map

Add Square to presentation map


    <a href="<?php echo home_url(); ?>">
      <img class="logo-img" src="<?php echo get_template_directory_uri(); ?>/img/logo.svg" alt="Pedagog Malmö">

      <?php pedagog_nav(); ?>

      <?php get_template_part('searchform'); ?>

Add home link in sticky header

Add home link in sticky header


<?php
namespace Setup;

class Menus
{
    /**
     * Initialization
     * This method should be run from functions.php
     */
    public static function init()
    {
        add_action( 'init', array(__CLASS__, 'register') );
    }

    /**
     * Registers menus within our theme
     */
    public static function register()
    {
        register_nav_menus( array(
            'primary' => __( 'Primary Menu', 'components-theme' ),
            'utility' => __( 'Utility Menu', 'components-theme' ),
            'footer-menu' => __( 'Footer Menu', 'components-theme' ),
            'footer-legal' => __( 'Footer Legal', 'components-theme' )
        ) );
    }
}

<?php
namespace Setup;

class Menus
{
    /**
     * Initialization
     * This method should be run from functions.php
     */
    public static function init()
    {
        add_action( 'init', array(__CLASS__, 'register') );
    }

    /**
     * Registers menus within our theme
     */
    public static function register()
    {
        register_nav_menus( array(
            'primary' => __( 'Primary Menu', 'components-theme' ),
            'utility' => __( 'Utility Menu', 'components-theme' ),
            'footer-menu' => __( 'Footer Menu', 'components-theme' ),
            'footer-legal' => __( 'Footer Legal', 'components-theme' ),
        ) );
    }
}

Add trailing comma to last item in Menu array


<?php
# $Id$
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#

if (! Gmetad($ganglia_ip, $ganglia_port) )
   {
      print "
There was an error collecting ganglia data ".
         "($ganglia_ip:$ganglia_port): $error
\n";
      exit;
   }

# If we have no child data sources, assume something is wrong.
if (!count($grid))
   {
      print "
Ganglia cannot find a data source. Is gmond running?
";
      exit;
   }

# If we only have one cluster source, suppress MetaCluster output.
if (count($grid) == 2 and $context=="meta")
   {
      # Lets look for one cluster (the other is our grid).
      foreach($grid as $source)
         if ($source[CLUSTER])
            {
               $standalone = 1;
               $context = "cluster";
               # Need to refresh data with new context.
               Gmetad($ganglia_ip, $ganglia_port);
               $clustername = $source[NAME];
            }
   }

?>

<?php
# $Id$
# Retrieves and parses the XML output from gmond. Results stored
# in global variables: $clusters, $hosts, $hosts_down, $metrics.
# Assumes you have already called get_context.php.
#

if (! Gmetad($ganglia_ip, $ganglia_port) )
   {
      print "
There was an error collecting ganglia data ".
         "($ganglia_ip:$ganglia_port): $error
\n";
      exit;
   }

# If we have no child data sources, assume something is wrong.
if (!count($grid) and !count($cluster))
   {
      print "
Ganglia cannot find a data source. Is gmond running?
";
      exit;
   }

# If we only have one cluster source, suppress MetaCluster output.
if (count($grid) == 2 and $context=="meta")
   {
      # Lets look for one cluster (the other is our grid).
      foreach($grid as $source)
         if ($source[CLUSTER])
            {
               $standalone = 1;
               $context = "cluster";
               # Need to refresh data with new context.
               Gmetad($ganglia_ip, $ganglia_port);
               $clustername = $source[NAME];
            }
   }

?>

Fix for scalable option bug, pointed out by Jason Smith.


<?php

require_once('../config.php');

function unauthorized() {
    header('WWW-Authenticate: Basic realm="' . APP_NAME . '"');
    header('HTTP/1.0 401 Unauthorized');
    die ('Unauthorized');
}

list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
  explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
    unauthorized();
}

$user = trim(strtolower($_SERVER['PHP_AUTH_USER']));
$password = $_SERVER['PHP_AUTH_PW'];

$users_filepath = STORAGE_PATH . 'users.json';
$users = json_decode(file_get_contents($users_filepath), true);
$valid_users = array_keys($users);

$user_exists = (in_array($user, $valid_users));

if (!$user_exists && strlen($user) > 0 && strlen($password) >= 6) {
    $users[$user] = password_hash($password, PASSWORD_BCRYPT);
    file_put_contents($users_filepath, json_encode($users), LOCK_EX);
}

$validated = $user_exists && password_verify($password, $users[$user]);

if (!$validated) {
    unauthorized();
}

define('STORAGE_FILEPATH', STORAGE_PATH . "users/$user.csv");

Put two lines into one line

Put two lines into one line


<?php

namespace FS\Components\Event\Listener;

use FS\Components\AbstractComponent;
use FS\Context\ApplicationListenerInterface;
use FS\Components\Event\NativeHookInterface;
use FS\Context\ConfigurableApplicationContextInterface as Context;
use FS\Context\ApplicationEventInterface as Event;
use FS\Components\Event\ApplicationEvent;

class GetSectionsShipping extends AbstractComponent implements ApplicationListenerInterface, NativeHookInterface
{
    public function getSupportedEvent()
    {
        return ApplicationEvent::GET_SECTIONS_SHIPPING;
    }

    public function onApplicationEvent(Event $event, Context $context)
    {
        //Since on woocommerce3.0.x, settings are for each shipping zone, the global settings for FlagShip method will not be displayed.
        $sections = $event->getInput('sections');
        unset($sections[$context->setting('FLAGSHIP_SHIPPING_PLUGIN_ID')]);

        return $sections;
    }

    public function publishNativeHook(Context $context)
    {
        \add_filter('woocommerce_get_sections_shipping', function ($sections) use ($context) {
            $event = new ApplicationEvent(ApplicationEvent::GET_SECTIONS_SHIPPING);
            $event->setInputs(array(
                'sections' => $sections,
            ));

            return $context->publishEvent($event);
        }, 10, 1);
    }

    public function getNativeHookType()
    {
        return self::TYPE_FILTER;
    }
}

<?php

namespace FS\Components\Event\Listener;

use FS\Injection\I;
use FS\Components\AbstractComponent;
use FS\Context\ApplicationListenerInterface;
use FS\Components\Event\NativeHookInterface;
use FS\Context\ConfigurableApplicationContextInterface as Context;
use FS\Context\ApplicationEventInterface as Event;
use FS\Components\Event\ApplicationEvent;

class GetSectionsShipping extends AbstractComponent implements ApplicationListenerInterface, NativeHookInterface
{
    public function getSupportedEvent()
    {
        return ApplicationEvent::GET_SECTIONS_SHIPPING;
    }

    public function onApplicationEvent(Event $event, Context $context)
    {
        $sections = $event->getInput('sections');
        unset($sections['flagship_shipping_method']);

        return $sections;
    }

    public function publishNativeHook(Context $context)
    {
        \add_filter('woocommerce_get_sections_shipping', function ($sections) use ($context) {
            $event = new ApplicationEvent(ApplicationEvent::GET_SECTIONS_SHIPPING);
            $event->setInputs(array(
                'sections' => $sections,
            ));

            return $context->publishEvent($event);
        }, 10, 1);
    }

    public function getNativeHookType()
    {
        return self::TYPE_FILTER;
    }
}

Revert "For removing the FlagShip section in the shipping settings tab, avoid hardcoding the FlagShip shipping method id."

This reverts commit 1ca4ad0917decb824fc7ea3dc7cb1d27b5612738.


<?php namespace Picqer\Financials\Exact\Query;

class Resultset
{
    protected $connection;

    protected $url;

    protected $class;

    protected $params;

    public function __construct($connection, $url, $class, $params)
    {
        $this->connection = $connection;
        $this->url = $url;
        $this->class = $class;
        $this->params = $params;
    }

    public function next()
    {
        $result = $this->connection->get($this->url, $params);
        $this->url = $this->connection->nextUrl;
        return $this->collectionFromResult($result, $this->class);
    }

    public function hasMore()
    {
        return $this->url !== null;
    }

    protected function collectionFromResult($result)
    {
        // If we have one result which is not an assoc array, make it the first element of an array for the
        // collectionFromResult function so we always return a collection from filter
        if ((bool) count(array_filter(array_keys($result), 'is_string'))) {
            $result = [ $result ];
        }

        $class = $this->class;
        $collection = [];

        foreach ($result as $r) {
            $collection[] = new $class($this->connection, $r);
        }

        return $collection;
    }
}

<?php namespace Picqer\Financials\Exact\Query;

class Resultset
{
    protected $connection;

    protected $url;

    protected $class;

    protected $params;

    public function __construct($connection, $url, $class, $params)
    {
        $this->connection = $connection;
        $this->url = $url;
        $this->class = $class;
        $this->params = $params;
    }

    public function next()
    {
        $result = $this->connection->get($this->url, $this->params);
        $this->url = $this->connection->nextUrl;
        return $this->collectionFromResult($result, $this->class);
    }

    public function hasMore()
    {
        return $this->url !== null;
    }

    protected function collectionFromResult($result)
    {
        // If we have one result which is not an assoc array, make it the first element of an array for the
        // collectionFromResult function so we always return a collection from filter
        if ((bool) count(array_filter(array_keys($result), 'is_string'))) {
            $result = [ $result ];
        }

        $class = $this->class;
        $collection = [];

        foreach ($result as $r) {
            $collection[] = new $class($this->connection, $r);
        }

        return $collection;
    }
}

Fix unused variable for $params

Fix unused variable for $params


<?php

namespace Pinq\Tests\Integration\Parsing;

use Pinq\Expressions as O;

class PowerOperatorsTest extends ParserTest
{
    protected function setUp()
    {
        if (!version_compare(PHP_VERSION, '5.6.0-alpha3', '>=')) {
            $this->markTestSkipped('Requires >=PHP 5.6');
        }
    }

    /**
     * @dataProvider parsers
     */
    public function testBinaryOperator()
    {
        $this->assertParsedAs(
                [PowerOperators::TYPE, 'binaryOperator'],
                [
                        O\Expression::binaryOperation(
                                O\Expression::value(4),
                                O\Operators\Binary::POWER,
                                O\Expression::value(5)
                        )
                ]
        );
    }
}

<?php

namespace Pinq\Tests\Integration\Parsing;

use Pinq\Expressions as O;

class PowerOperatorsTest extends ParserTest
{
    protected function setUp()
    {
        if (!version_compare(PHP_VERSION, '5.6.0-alpha3', '>=')) {
            $this->markTestSkipped('Requires >=PHP 5.6');
        }
    }

    /**
     * @dataProvider parsers
     */
    public function testBinaryOperator()
    {
        $this->assertParsedAs(
                [PowerOperators::TYPE, 'binaryOperator'],
                [
                        O\Expression::binaryOperation(
                                O\Expression::value(4),
                                O\Operators\Binary::POWER,
                                O\Expression::value(5)
                        )
                ]
        );
    }

    /**
     * @dataProvider parsers
     */
    public function testAssignmentOperator()
    {
        $this->assertParsedAs(
                [PowerOperators::TYPE, 'assignmentOperator'],
                [
                        O\Expression::assign(
                                O\Expression::variable(O\Expression::value('i')),
                                O\Operators\Assignment::POWER,
                                O\Expression::value(5)
                        )
                ]
        );
    }
}

Add missing ** assignment operator parsing test


<?php

class ValidationTest extends PHPUnit_Framework_TestCase
{

    public function testIsbn10()
    {
        $this->assertTrue(Isbn\Validation::isbn10('8881837188'));
        $this->assertFalse(Isbn\Validation::isbn10('8881837187'));
    }

    public function testIsbn13()
    {
        $this->assertTrue(Isbn\Validation::isbn13('9788889527191'));
        $this->assertFalse(Isbn\Validation::isbn13('9788889527190'));
    }

    public function testIsbn()
    {
        $this->assertTrue(Isbn\Validation::isbn('8881837188'));
        $this->assertFalse(Isbn\Validation::isbn('8881837187'));
        $this->assertTrue(Isbn\Validation::isbn('9788889527191'));
        $this->assertFalse(Isbn\Validation::isbn('9788889527190'));
    }

}

<?php

class ValidationTest extends PHPUnit_Framework_TestCase
{

    public function testIsbn10()
    {
        $this->assertTrue(Isbn\Validation::isbn10('8881837188'));
        $this->assertFalse(Isbn\Validation::isbn10('8881837187'));
    }

    public function testIsbn13()
    {
        $this->assertTrue(Isbn\Validation::isbn13('9788889527191'));
        $this->assertFalse(Isbn\Validation::isbn13('9788889527190'));
    }

    public function testIsbn()
    {
        $this->assertTrue(Isbn\Validation::isbn('8881837188'));
        $this->assertFalse(Isbn\Validation::isbn('8881837187'));
        $this->assertTrue(Isbn\Validation::isbn('9788889527191'));
        $this->assertFalse(Isbn\Validation::isbn('9788889527190'));
        $this->assertFalse(Isbn\Validation::isbn('97888895271910'));
    }

}

Move to 100% of Testing Code Coverage for Isbn::Validation


<?php

declare(strict_types=1);

namespace ProxyManagerTest\Exception;

use PHPUnit\Framework\TestCase;
use ProxyManager\Exception\FileNotWritableException;
use Webimpress\SafeWriter\Exception\ExceptionInterface as FileWriterException;

/**
 * Tests for {@see \ProxyManager\Exception\FileNotWritableException}
 *
 * @covers \ProxyManager\Exception\FileNotWritableException
 * @group Coverage
 */
final class FileNotWritableExceptionTest extends TestCase
{
    public function testFromPrevious() : void
    {
        $previous = $this->getMockBuilder(FileWriterException::class)
            ->enableOriginalConstructor()
            ->setConstructorArgs(['Previous exception message'])
            ->getMock();

        $exception = FileNotWritableException::fromPrevious($previous);

        self::assertSame('Previous exception message', $exception->getMessage());
        self::assertSame($previous, $exception->getPrevious());
    }
}

<?php

declare(strict_types=1);

namespace ProxyManagerTest\Exception;

use PHPUnit\Framework\TestCase;
use ProxyManager\Exception\FileNotWritableException;
use Webimpress\SafeWriter\Exception\ExceptionInterface as FileWriterException;

/**
 * Tests for {@see \ProxyManager\Exception\FileNotWritableException}
 *
 * @covers \ProxyManager\Exception\FileNotWritableException
 * @group Coverage
 */
final class FileNotWritableExceptionTest extends TestCase
{
    public function testFromPrevious() : void
    {
        $previousExceptionMock = $this->getMockBuilder(FileWriterException::class);
        $previousExceptionMock->enableOriginalConstructor();
        $previousExceptionMock->setConstructorArgs(['Previous exception message']);
        $previousException = $previousExceptionMock->getMock();

        $exception = FileNotWritableException::fromPrevious($previousException);

        self::assertSame('Previous exception message', $exception->getMessage());
        self::assertSame($previousException, $exception->getPrevious());
    }
}

Drop usageof fluent interface on mocking

Psalm is not failing now !


<?php namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Session;
use Redirect;
use App\Business;
use Flash;

class BusinessController extends Controller
{
    public function getHome()
    {
        $business = Business::find(Session::get('selected.business')->id);
        if (empty($business)) {
            Flash::warning(trans('user.business.msg.please_select_a_business'));
            return Redirect::route('user.businesses.list');
        }
        return view('user.businesses.show', compact('business'));
    }

    public function getList()
    {
        $businesses = Business::all();
        return view('user.businesses.index', compact('businesses'));
    }

    public function getSelect(Business $business)
    {
        Session::set('selected.business', $business);
        return Redirect::route('user.businesses.home');
    }

    public function getSuscriptions()
    {
        $contacts = \Auth::user()->contacts;
        return view('user.businesses.suscriptions', compact('contacts'));
    }
}

<?php namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Session;
use Redirect;
use App\Business;
use Flash;

class BusinessController extends Controller
{
    public function getHome()
    {
        if (!Session::get('selected.business')) {
            return Redirect::route('user.businesses.list');
        }
        $business = Business::find(Session::get('selected.business')->id);
        if (empty($business)) {
            Flash::warning(trans('user.business.msg.please_select_a_business'));
            return Redirect::route('user.businesses.list');
        }
        return view('user.businesses.show', compact('business'));
    }

    public function getList()
    {
        $businesses = Business::all();
        return view('user.businesses.index', compact('businesses'));
    }

    public function getSelect(Business $business)
    {
        Session::set('selected.business', $business);
        return Redirect::route('user.businesses.home');
    }

    public function getSuscriptions()
    {
        $contacts = \Auth::user()->contacts;
        return view('user.businesses.suscriptions', compact('contacts'));
    }
}

Add empty session value check

Bugfix: Add empty session value check


<?php

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

namespace Sylius\Behat\Context\Transform;

use Behat\Behat\Context\Context;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 */
final class LexicalContext implements Context
{
    /**
     * @Transform /^"(?:€|£|￥|\$)((?:\d+\.)?\d+)"$/
     */
    public function getPriceFromString($price)
    {
        $this->validatePriceString($price);

        return (int) round(($price * 100), 2);
    }

    /**
     * @Transform /^"((?:\d+\.)?\d+)%"$/
     */
    public function getPercentageFromString($percentage)
    {
        return ((int) $percentage) / 100;
    }

    /**
     * @param string $price
     *
     * @throws \InvalidArgumentException
     */
    private function validatePriceString($price)
    {
        if (strlen(substr(strrchr($price, "."), 1)) > 2) {
            throw new \InvalidArgumentException('Price string should not have more than 2 decimal digits.');
        }
    }
}

<?php

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

namespace Sylius\Behat\Context\Transform;

use Behat\Behat\Context\Context;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 */
final class LexicalContext implements Context
{
    /**
     * @Transform /^"(\-)?(?:€|£|￥|\$)((?:\d+\.)?\d+)"$/
     */
    public function getPriceFromString($sign, $price)
    {
        $this->validatePriceString($price);

        if ('-' === $sign) {
            $price = $price * -1;
        }

        return (int) round(($price * 100), 2);
    }

    /**
     * @Transform /^"((?:\d+\.)?\d+)%"$/
     */
    public function getPercentageFromString($percentage)
    {
        return ((int) $percentage) / 100;
    }

    /**
     * @param string $price
     *
     * @throws \InvalidArgumentException
     */
    private function validatePriceString($price)
    {
        if (strlen(substr(strrchr($price, "."), 1)) > 2) {
            throw new \InvalidArgumentException('Price string should not have more than 2 decimal digits.');
        }
    }
}

[Behat] Allow lexical context to accept negative values


<?php
namespace Czim\FileHandling\Variant\Strategies;

use Czim\FileHandling\Support\Image\OrientationFixer;
use Imagine\Gd\Imagine;

class ImageAutoOrientStrategy extends AbstractImageStrategy
{

    /**
     * Performs manipulation of the file.
     *
     * @return bool|null
     */
    protected function perform()
    {
        $fixer = $this->getOrientationFixer();

        return (bool) $fixer->fixFile($this->file, new Imagine);
    }

    /**
     * @return OrientationFixer
     */
    protected function getOrientationFixer()
    {
        return new OrientationFixer;
    }

}

<?php
namespace Czim\FileHandling\Variant\Strategies;

use Czim\FileHandling\Support\Image\OrientationFixer;
use Imagine\Gd\Imagine;

class ImageAutoOrientStrategy extends AbstractImageStrategy
{

    /**
     * Performs manipulation of the file.
     *
     * @return bool|null
     */
    protected function perform()
    {
        $fixer = $this->getOrientationFixer();

        if ($this->isQuietModeDisabled()) {
            $fixer->disableQuietMode();
        }

        return (bool) $fixer->fixFile($this->file, new Imagine);
    }

    /**
     * @return OrientationFixer
     */
    protected function getOrientationFixer()
    {
        return new OrientationFixer;
    }

    /**
     * Returns whether we should throw exceptions on exif problems.
     *
     * @return bool
     */
    protected function isQuietModeDisabled()
    {
        if ( ! array_key_exists('quiet', $this->options)) {
            return false;
        }

        return ! $this->options['quiet'];
    }

}

Allow disable ‘quiet’ option for auto orient strategy


<?php
namespace ShinyGeoip\Responder;

use ShinyGeoip\Core\Responder;

class ApiRequestResponder extends Responder
{
    /**
     * Echos short version of record as json or jsonp string.
     */
    public function short()
    {
        $callback = $this->app->request->get('callback', '');
        $record = $this->get('record');
        $record = json_encode($record);
        if (!empty($callback)) {
            $this->setContentTypeHeader('javascript');
            $record = $callback . '(' . $record . ');';
        } else {
            $this->setContentTypeHeader('json');
        }
        $this->setContent($record);
    }

    /**
     * Echos the full record as json or jsonp string.
     */
    public function full()
    {
        $callback = $this->app->request->get('callback', '');
        $record = $this->get('record')->jsonSerialize();
        $record = json_encode($record);
        if (!empty($callback)) {
            $this->setContentTypeHeader('javascript');
            $record = $callback . '(' . $record . ');';
        } else {
            $this->setContentTypeHeader('json');
        }
        $this->setContent($record);
    }

    /**
     * Echos a json encoded not found error message.
     */
    public function notFound()
    {
        $this->setContentTypeHeader('json');
        $this->setContent(json_encode(['type' => 'error', 'msg' => 'No record found.']));
    }
}

<?php
namespace ShinyGeoip\Responder;

use ShinyGeoip\Core\Responder;

class ApiRequestResponder extends Responder
{
    /**
     * Echos short version of record as json or jsonp string.
     */
    public function short()
    {
        $callback = $this->app->request->get('callback', '');
        $record = $this->get('record');
        $record = json_encode($record);
        if (!empty($callback)) {
            $this->setContentTypeHeader('javascript');
            $record = $callback . '(' . $record . ');';
        } else {
            $this->setContentTypeHeader('json');
        }
        $this->setContent($record);
    }

    /**
     * Echos the full record as json or jsonp string.
     */
    public function full()
    {
        $callback = $this->app->request->get('callback', '');
        $record = $this->get('record')->jsonSerialize();
        $record = json_encode($record);
        if (!empty($callback)) {
            $this->setContentTypeHeader('javascript');
            $record = $callback . '(' . $record . ');';
        } else {
            $this->setContentTypeHeader('json');
        }
        $this->setContent($record);
    }

    /**
     * Echos a json encoded not found error message.
     */
    public function notFound()
    {
        $callback = $this->app->request->get('callback', '');
        $response = json_encode(['type' => 'error', 'msg' => 'No record found.']);
        if (!empty($callback)) {
            $this->setContentTypeHeader('javascript');
            $response = $callback . '(' . $response . ');';
        } else {
            $this->setContentTypeHeader('json');
        }
        $this->setContentTypeHeader('json');
        $this->setContent($response);
    }
}

Make not found message JSONP compatible

Make not found message JSONP compatible

In case an IP is not found and a callback function is provided
in the request the response message should be JSONP encoded.

Resolves issue #1


<?php

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

class CreateUsersTable extends Migration {
    public function up() {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('currency_id')->unsigned();
            $table->string('avatar')->nullable();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->string('language');
            $table->timestamps();
        });
    }

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

<?php

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

class CreateUsersTable extends Migration {
    public function up() {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('currency_id')->unsigned();
            $table->string('avatar')->nullable();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->string('language');
            $table->string('theme')->default('light');
            $table->timestamps();
        });
    }

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

Add theme column to users table

Add theme column to users table


<?php

/**
 * Register application routes.
 */
use App\Http\Controller;
use Corviz\Routing\Route;

Route::get('/', [
    'controller' => Controller\Home::class,
    'action'     => 'index',
    'alias'      => 'home.index',
    'middleware' => 'auth'
]);

<?php

/**
 * Register application routes.
 */
use App\Http\Controller;
use Corviz\Routing\Route;

Route::get('/', [
    'controller' => Controller\Home::class,
    'action'     => 'index',
    'alias'      => 'home.index',
]);

Index route should not use authentication


<?php

namespace App\Http\Controllers\Article;
use App\Article;
use App\Http\Requests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;

class ArticlesController extends BaseController
{
    /**
     Article
     */
    protected $article;
    public function __construct(Article $article){
      $this->article = $article;
    }
    public function getIndex(){
      $articles = $this->article->all();
      return view('articles.index')->with(compact('articles'));
    }

    public function getShow($id){
      $article = $this->article->find($id);
      return view('articles.show')->with(compact('article'));
    }

    public function getTagIndex($tag_id){
      $articles = $this->article->all();
      return view('articles.index')->with(compact('articles'));
    }

}

<?php

namespace App\Http\Controllers\Article;
use App\Article;
use App\Http\Requests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;

class ArticlesController extends BaseController
{
    /**
     Article
     */
    protected $article;
    public function __construct(Article $article){
      $this->article = $article;
    }
    public function getIndex(){
      $articles = $this->article->all();
      return response()->json($articles);
    }

    public function getShow($id){
      $article = $this->article->find($id);
      return response()->json($article);
    }

    public function getTagIndex($tag_id){
      $articles = $this->article->all();
      return response()->json($articles);
    }

}

Change Main Response to Json

Change Main Response to Json


<?php

/*
 * This file is part of the Active Collab Controller project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\Controller\ActionResultEncoder\ValueEncoder;

use ActiveCollab\Controller\ActionResultEncoder\ActionResultEncoderInterface;
use Psr\Http\Message\ResponseInterface;

class ScalarEncoder extends ValueEncoder
{
    public function shouldEncode($value): bool
    {
        return is_scalar($value);
    }

    /**
     * @param  ResponseInterface            $response
     * @param  ActionResultEncoderInterface $encoder
     * @param  string                       $value
     * @return ResponseInterface
     */
    public function encode(ResponseInterface $response, ActionResultEncoderInterface $encoder, $value): ResponseInterface
    {
        return $response->withBody($this->createBodyFromText($value));
    }
}

Add new line at the end of class

Add new line at the end of class


<?php
$uniqueId = $_REQUEST['id'];
// Lookup variable `$uniqueId` in a database to find messageSid
$messageSid = 'SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

// TODO: Implement

<?php
// Required if your envrionment does not handle autoloading
require __DIR__ . '/vendor/autoload.php';

// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;

$uniqueId = $_REQUEST['id'];
// Lookup variable `$uniqueId` in a database to find messageSid
$messageSid = 'SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

// Your Account SID and Auth Token from twilio.com/console
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken = 'your_auth_token';

$client = new Client($accountSid, $authToken);
$client->request(
    'POST',
    "https://api.twilio.com/2010-04-01/Accounts/{$accountSid}/Messages/{$messageSid}/Feedback",
    null,
    array('Outcome' => 'confirmed')
);

echo 'Thank you!';

Update snippet for send delivery confirmation feedback in PHP


<?php

namespace Tests;

use Cake\Chronos\Chronos;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    /**
     * Setup tests.
     */
    public function setUp()
    {
        parent::setUp();

        $this->setKnownUuidFactory();
    }

    /**
     * Tear down tests.
     */
    protected function tearDown()
    {
        parent::tearDown();

        Chronos::setTestNow();
    }

    /**
     * Handles the known UUID handling in certain unit tests. Use the "KnownUuid" trait
     * in order to enable this ability.
     */
    public function setKnownUuidFactory()
    {
        // do nothing
    }
}

<?php

namespace Tests;

use Cake\Chronos\Chronos;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    /**
     * Setup tests.
     */
    public function setUp()
    {
        parent::setUp();

        Hash::setRounds(4);
        $this->setKnownUuidFactory();
    }

    /**
     * Tear down tests.
     */
    protected function tearDown()
    {
        parent::tearDown();

        Chronos::setTestNow();
    }

    /**
     * Handles the known UUID handling in certain unit tests. Use the "KnownUuid" trait
     * in order to enable this ability.
     */
    public function setKnownUuidFactory()
    {
        // do nothing
    }
}

Set the hashing rounds low to speed up tests


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

/**
 * @internal This class is not covered by the backward compatibility promise for phpunit/php-code-coverage
 */
final class CachingUncoveredFileAnalyser extends Cache implements UncoveredFileAnalyser
{
    /**
     * @var UncoveredFileAnalyser
     */
    private $uncoveredFileAnalyser;

    public function __construct(string $directory, UncoveredFileAnalyser $uncoveredFileAnalyser)
    {
        parent::__construct($directory);

        $this->uncoveredFileAnalyser = $uncoveredFileAnalyser;
    }

    public function executableLinesIn(string $filename): array
    {
        $cacheKey = 'v2' . __METHOD__;

        if ($this->has($filename, $cacheKey)) {
            return $this->read($filename, $cacheKey);
        }

        $data = $this->uncoveredFileAnalyser->executableLinesIn($filename);

        $this->write($filename, $cacheKey, $data);

        return $data;
    }
}

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

/**
 * @internal This class is not covered by the backward compatibility promise for phpunit/php-code-coverage
 */
final class CachingUncoveredFileAnalyser extends Cache implements UncoveredFileAnalyser
{
    private const CACHE_FORMAT_VERSION = 2;

    /**
     * @var UncoveredFileAnalyser
     */
    private $uncoveredFileAnalyser;

    public function __construct(string $directory, UncoveredFileAnalyser $uncoveredFileAnalyser)
    {
        parent::__construct($directory);

        $this->uncoveredFileAnalyser = $uncoveredFileAnalyser;
    }

    public function executableLinesIn(string $filename): array
    {
        $cacheKey = __CLASS__ . self::CACHE_FORMAT_VERSION;

        if ($this->has($filename, $cacheKey)) {
            return $this->read($filename, $cacheKey);
        }

        $data = $this->uncoveredFileAnalyser->executableLinesIn($filename);

        $this->write($filename, $cacheKey, $data);

        return $data;
    }
}

Use a constant to declare the cache format version


<?php namespace Octommerce\Octommerce\Console;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Octommerce\Octommerce\Models\Cart;
use Octommerce\Octommerce\Models\Settings;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class DeleteCart extends Command
{
    /**
     * @var string The console command name.
     */
    protected $name = 'octommerce:delete-cart';

    /**
     * @var string The console command description.
     */
    protected $description = 'Delete unused cart in a few days';

    /**
     * Execute the console command.
     * @return void
     */
    public function fire()
    {
        // Default value is 30 days
        $inDays = Settings::get('delete_cart_in_days') ?: 30;
        $maxDate = Carbon::now()->subDays($inDays);

        Cart::with('products')
            ->whereDate('updated_at', '<', $maxDate)
            ->get()
            ->each(function($cart) {
                $cart->products()->delete();
                $cart->delete();
            });
    }

    /**
     * Get the console command arguments.
     * @return array
     */
    protected function getArguments()
    {
        return [];
    }

    /**
     * Get the console command options.
     * @return array
     */
    protected function getOptions()
    {
        return [];
    }
}

<?php namespace Octommerce\Octommerce\Console;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Octommerce\Octommerce\Models\Cart;
use Octommerce\Octommerce\Models\Settings;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class DeleteCart extends Command
{
    /**
     * @var string The console command name.
     */
    protected $name = 'octommerce:delete-cart';

    /**
     * @var string The console command description.
     */
    protected $description = 'Delete unused cart in a few days';

    /**
     * Execute the console command.
     * @return void
     */
    public function fire()
    {
        // Default value is 30 days
        $inDays = Settings::get('delete_cart_in_days') ?: 30;
        $maxDate = Carbon::now()->subDays($inDays);

        Cart::with('products')
            ->whereDate('updated_at', '<', $maxDate)
            ->get()
            ->each(function($cart) {
                $cart->products()->detach();
                $cart->delete();
            });
    }

    /**
     * Get the console command arguments.
     * @return array
     */
    protected function getArguments()
    {
        return [];
    }

    /**
     * Get the console command options.
     * @return array
     */
    protected function getOptions()
    {
        return [];
    }
}

Fix detach product(s) instead delete it

Fix detach product(s) instead delete it


poster()->first()->avatarUrl() }}" alt="" class="post-avatar">

{{ $post->poster()->first()->name }}

Admin

Remove admin badge from displaying on every post


<?php

namespace Test\AppBundle\API\Details;

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

class OrganismsWithTraitTest extends WebserviceTestCase
{
    public function testExecute()
    {
        $default_db = $this->default_db;
        $service = $this->webservice->factory('details', 'organismsWithTrait');
        //Test for the correct number of elements in the returned array
        $results = $service->execute(new ParameterBag(array(
            'dbversion' => $default_db,
            'trait_type_id' => 1)),
            null
        );
        $this->assertEquals(OrganismsWithTrait::DEFAULT_LIMIT, count($results));
        $results = $service->execute(
            new ParameterBag(array(
                'dbversion' => $default_db,
                'trait_type_id' => 1, 'limit' => 10
            )),
            null
        );
        $this->assertEquals(10, count($results));
        $this->assertTrue(array_key_exists('fennec_id',$results[0]));
        $this->assertTrue(array_key_exists('scientific_name',$results[0]));
    }
}

<?php

namespace Test\AppBundle\API\Details;

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

class OrganismsWithTraitTest extends WebserviceTestCase
{
    public function testExecute()
    {
        $default_db = $this->default_db;
        $service = $this->webservice->factory('details', 'organismsWithTrait');
        //Test for the correct number of elements in the returned array
        $results = $service->execute(new ParameterBag(array(
            'dbversion' => $default_db,
            'trait_type_id' => 1)),
            null
        );
        $this->assertEquals(OrganismsWithTrait::DEFAULT_LIMIT, count($results));

        $results = $service->execute(
            new ParameterBag(array(
                'dbversion' => $default_db,
                'trait_type_id' => 3, 'limit' => 30000
            )),
            null
        );
        $this->assertEquals(23185, count($results));

        $results = $service->execute(
            new ParameterBag(array(
                'dbversion' => $default_db,
                'trait_type_id' => 1, 'limit' => 10
            )),
            null
        );
        $this->assertEquals(10, count($results));
        $this->assertTrue(array_key_exists('fennec_id',$results[0]));
        $this->assertTrue(array_key_exists('scientific_name',$results[0]));
    }
}

Add test case for new version of IUCN

Add test case for new version of IUCN


<?
if (is_object($configuration)) {
	$path = $configuration->getRootPath();
	$relativePath = $configuration->getWebRootRelativePath();
}
?>
<? $form = Loader::helper('form'); ?>

    <?=t('Root Path')?>

        <?=$form->text('fslType[path]', $path)?>

    <?=t('Relative Path')?>
    <?=$form->text('fslType[relativePath]', $relativePath)?>

<?php
defined('C5_EXECUTE') or die('Access Denied');
if (is_object($configuration)) {
	$path = $configuration->getRootPath();
	$relativePath = $configuration->getWebRootRelativePath();
}
?>
<? $form = Loader::helper('form'); ?>

    <?=t('Root Path')?>

        <?=$form->text('fslType[path]', $path)?>

    <?=t('Relative Path')?>
    <?=$form->text('fslType[relativePath]', $relativePath)?>

Add a c5_execute or die

Add a c5_execute or die


<?php

namespace Concrete\Core\Tree\Menu\Item;

class EditPermissionsItem extends AbstractNodeItem
{

    public function getDialogTitle()
    {
        return t('Edit Permissions');
    }

    public function getAction()
    {
        return 'edit-node';
    }

    public function getActionURL()
    {
        return \URL::to('/ccm/system/dialogs/tree/node/permissions?treeNodeID=' . $this->node->getTreeNodeID());
    }

    public function getItemName()
    {
        return t('Edit Permissions');
    }
}

<?php

namespace Concrete\Core\Tree\Menu\Item;

use HtmlObject\Element;
use HtmlObject\Link;

class EditPermissionsItem extends AbstractNodeItem
{

    public function getDialogTitle()
    {
        return t('Edit Permissions');
    }

    public function getAction()
    {
        return 'edit-node';
    }

    public function getActionURL()
    {
        return \URL::to('/ccm/system/dialogs/tree/node/permissions?treeNodeID=' . $this->node->getTreeNodeID());
    }

    public function getItemName()
    {
        return t('Edit Permissions');
    }

    public function getItemElement()
    {
        $element = new Element('li');
        $link = new Link('#', $this->getItemName());
        $link->setAttribute('data-tree-action', $this->getAction());
        $link->setAttribute('dialog-title', $this->getDialogTitle());
        $link->setAttribute('data-tree-action-url', $this->getActionURL());
        $link->setAttribute('dialog-width', '520');
        $link->setAttribute('dialog-height', '450');
        $element->appendChild($link);
        return $element;
    }
}

Fix height/width of edit permissions dialog


<?php

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

namespace Sonata\BlockBundle\Tests\Block;

use Sonata\BlockBundle\Block\Loader\ServiceLoader;

class ServiceLoaderTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @expectedException \RuntimeException
     */
    public function testBlockNotFoundException()
    {
        $loader = new ServiceLoader(array());
        $loader->load('foo');
    }

    public function testLoader()
    {

        $loader = new ServiceLoader(array('foo.bar' => array('option1' => 42)));

        $definition = array(
            'type' => 'foo.bar',
            'settings' => array('option2' => 23)
        );

        $this->assertTrue($loader->support($definition));

        $this->assertInstanceOf('Sonata\BlockBundle\Model\BlockInterface', $loader->load($definition));
    }
}

<?php

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

namespace Sonata\BlockBundle\Tests\Block;

use Sonata\BlockBundle\Block\Loader\ServiceLoader;

class ServiceLoaderTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @expectedException RuntimeException
     */
    public function testBlockNotFoundException()
    {
        $loader = new ServiceLoader(array());
        $loader->load('foo');
    }

    public function testLoader()
    {

        $loader = new ServiceLoader(array('foo.bar' => array('option1' => 42)));

        $definition = array(
            'type' => 'foo.bar',
            'settings' => array('option2' => 23)
        );

        $this->assertTrue($loader->support($definition));

        $this->assertInstanceOf('Sonata\BlockBundle\Model\BlockInterface', $loader->load($definition));
    }
}

Test issue with expected exception

Test issue with expected exception


<?php

declare(strict_types=1);

namespace Roave\Signature;

use Roave\Signature\Encoder\EncoderInterface;
use Roave\Signature\Hasher\HasherInterface;

final class FileContentChecker implements CheckerInterface
{
    /**
     * @var EncoderInterface
     */
    private $encoder;

    /**
     * @var HasherInterface
     */
    private $hasher;

    /**
     * {@inheritDoc}
     */
    public function __construct(EncoderInterface $encoder, HasherInterface $hasher)
    {
        $this->encoder = $encoder;
        $this->hasher  = $hasher;
    }

    /**
     * {@inheritDoc}
     */
    public function check(string $phpCode)
    {
        if (! preg_match('{Roave/Signature:\s+([a-zA-Z0-9\/=]+)}', $phpCode, $matches)) {
            return false;
        }

        // @todo extract this logic for get rid of signature
        $codeWithoutSignature = array_reduce(
            explode(PHP_EOL, $phpCode),
            function (string $carry = null, string $currentLine = null): string {

                // if current line is the signature line, we just ignore it
                if (preg_match('{Roave/Signature: (\w)}', $currentLine)) {
                    return $carry;
                }

                if (null === $carry) {
                    return $currentLine;
                }

                if (null !== $currentLine) {
                    return $carry . PHP_EOL . $currentLine;
                }

                return $carry;
            }
        );

        return $this->encoder->verify($codeWithoutSignature, $matches[1]);
    }
}

<?php

declare(strict_types=1);

namespace Roave\Signature;

use Roave\Signature\Encoder\EncoderInterface;
use Roave\Signature\Hasher\HasherInterface;

final class FileContentChecker implements CheckerInterface
{
    /**
     * @var EncoderInterface
     */
    private $encoder;

    /**
     * @var HasherInterface
     */
    private $hasher;

    /**
     * {@inheritDoc}
     */
    public function __construct(EncoderInterface $encoder, HasherInterface $hasher)
    {
        $this->encoder = $encoder;
        $this->hasher  = $hasher;
    }

    /**
     * {@inheritDoc}
     */
    public function check(string $phpCode)
    {
        if (! preg_match('{Roave/Signature:\s+([a-zA-Z0-9\/=]+)}', $phpCode, $matches)) {
            return false;
        }

        return $this->encoder->verify($this->stripCodeSignature($phpCode), $matches[1]);
    }

    /**
     * @param string $phpCode
     *
     * @return string
     */
    private function stripCodeSignature(string $phpCode)
    {
        return preg_replace('{[\/\*\s]+Roave/Signature:\s+([a-zA-Z0-9\/\*\/ =]+)}', '', $phpCode);
    }
}

Use preg_replace to strip commented signature line


<?php

namespace Jsor\HalClient;

use Psr\Http\Message\UriInterface;

interface HalClientInterface
{
    /**
     * @return UriInterface
     */
    public function getRootUrl();

    /**
     * @param string
     * @return string[]
     */
    public function getHeader($name);

    /**
     * @param string
     * @param string|string[]
     * @return HalClientInterface
     */
    public function withHeader($name, $value);

    /**
     * @param array
     * @return HalResource
     */
    public function root(array $options = []);

    /**
     * @param string|UriInterface
     * @param array
     * @return HalResource
     */
    public function get($uri, array $options = []);

    /**
     * @param string|UriInterface
     * @param array
     * @return HalResource
     */
    public function post($uri, array $options = []);

    /**
     * @param string|UriInterface
     * @param array
     * @return HalResource
     */
    public function put($uri, array $options = []);

    /**
     * @param string|UriInterface
     * @param array
     * @return HalResource
     */
    public function delete($uri, array $options = []);

    /**
     * @param string
     * @param string|UriInterface
     * @param array
     * @return HalResource
     */
    public function request($method, $uri, array $options = []);
}

<?php

namespace Jsor\HalClient;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;

interface HalClientInterface
{
    /**
     * @return UriInterface
     */
    public function getRootUrl();

    /**
     * @param string
     * @return string[]
     */
    public function getHeader($name);

    /**
     * @param string
     * @param string|string[]
     * @return HalClientInterface
     */
    public function withHeader($name, $value);

    /**
     * @param array
     * @return HalResource|ResponseInterface
     */
    public function root(array $options = []);

    /**
     * @param string|UriInterface
     * @param array
     * @return HalResource|ResponseInterface
     */
    public function get($uri, array $options = []);

    /**
     * @param string|UriInterface
     * @param array
     * @return HalResource|ResponseInterface
     */
    public function post($uri, array $options = []);

    /**
     * @param string|UriInterface
     * @param array
     * @return HalResource|ResponseInterface
     */
    public function put($uri, array $options = []);

    /**
     * @param string|UriInterface
     * @param array
     * @return HalResource|ResponseInterface
     */
    public function delete($uri, array $options = []);

    /**
     * @param string
     * @param string|UriInterface
     * @param array
     * @return HalResource|ResponseInterface
     */
    public function request($method, $uri, array $options = []);
}

Add ResponseInterface return type to request methods


<?php

namespace React\Socket;

use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
use React\Stream\WritableStreamInterface;
use React\Stream\Buffer;
use React\Stream\Stream;
use React\Stream\Util;

class Connection extends Stream implements ConnectionInterface
{
    public function handleData($stream)
    {
        $data = stream_socket_recvfrom($stream, $this->bufferSize);
        if ('' === $data || false === $data) {
            $this->end();
        } else {
            $this->emit('data', array($data, $this));
        }
    }

    public function handleClose()
    {
        if (is_resource($this->stream)) {
            stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR);
            fclose($this->stream);
        }
    }

    public function getRemoteAddress()
    {
        return $this->parseAddress(stream_socket_get_name($this->stream, true));
    }

    private function parseAddress($address)
    {
        return trim(substr($address, 0, strrpos($address, ':')), '[]');
    }
}

<?php

namespace React\Socket;

use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
use React\Stream\WritableStreamInterface;
use React\Stream\Buffer;
use React\Stream\Stream;
use React\Stream\Util;

class Connection extends Stream implements ConnectionInterface
{
    public function handleData($stream)
    {
        $data = fread($stream, $this->bufferSize);
        if ('' === $data || false === $data) {
            $this->end();
        } else {
            $this->emit('data', array($data, $this));
        }
    }

    public function handleClose()
    {
        if (is_resource($this->stream)) {
            stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR);
            fclose($this->stream);
        }
    }

    public function getRemoteAddress()
    {
        return $this->parseAddress(stream_socket_get_name($this->stream, true));
    }

    private function parseAddress($address)
    {
        return trim(substr($address, 0, strrpos($address, ':')), '[]');
    }
}

Use fread() instead of socket_recv_from()


<?php

namespace spec\Elfiggo\Brobdingnagian\Detector;

use Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use ReflectionClass;

class ClassSizeSpec extends ObjectBehavior
{
    const LESS_THAN_300 = 299;
    const GREATER_THAN_300 = 301;

    function let(ReflectionClass $sus)
    {
        $this->beConstructedWith($sus);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Elfiggo\Brobdingnagian\Detector\ClassSize');
    }

    function it_does_not_complain_if_the_class_size_is_not_too_large(ReflectionClass $sus)
    {
        $sus->getEndLine()->willReturn(self::LESS_THAN_300);
        $this->check();
    }

    function it_complains_if_class_size_is_too_large(ReflectionClass $sus)
    {
        $sus->getEndLine()->willReturn(self::GREATER_THAN_300);
        $this->shouldThrow(ClassSizeTooLarge::class)->duringCheck();
    }
}

<?php

namespace spec\Elfiggo\Brobdingnagian\Detector;

use Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use ReflectionClass;

class ClassSizeSpec extends ObjectBehavior
{
    const LESS_THAN_300 = 299;
    const GREATER_THAN_300 = 301;

    function let(ReflectionClass $sus)
    {
        $this->beConstructedWith($sus);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Elfiggo\Brobdingnagian\Detector\ClassSize');
    }

    function it_does_not_complain_if_the_class_size_is_not_too_large(ReflectionClass $sus)
    {
        $sus->getEndLine()->willReturn(self::LESS_THAN_300);
        $this->check();
    }

    function it_complains_if_class_size_is_too_large(ReflectionClass $sus)
    {
        $sus->getEndLine()->willReturn(self::GREATER_THAN_300);
        $sus->getName()->willReturn("Elfiggo/Brobdingnagian/Detector/ClassSize");
        $this->shouldThrow(ClassSizeTooLarge::class)->duringCheck();
    }
}

Update spec for 5.6 to handle additional Refleciton call