<?php
namespace Aedart\Scaffold\Cache;

use Aedart\Scaffold\Containers\IoC;
use Illuminate\Contracts\Cache\Repository;

/**
 * Cache Helper
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Cache
 */
class CacheHelper
{
    /**
     * @var Repository
     */
    static protected $cache;

    /**
     * Register the cache directory
     *
     * @param string $directory
     */
    static public function setCacheDirectory($directory)
    {
        $ioc = IoC::getInstance();

        $config = $ioc->make('config');
        $config->set('cacheDir', $directory);

        $ioc->container()['config'] = $config;
    }

    /**
     * Returns a cache repository instance
     *
     * @return Repository
     */
    static public function make()
    {
        if(!isset(self::$cache)){
            $ioc = IoC::getInstance();
            $repository = $ioc->make(Repository::class);
            self::$cache = $repository;
        }

        return self::$cache;
    }

    /**
     * Destroy the cache instance inside this helper
     */
    static public function destroy()
    {
        unset(self::$cache);
    }
}

<?php
namespace Aedart\Scaffold\Cache;

use Aedart\Scaffold\Containers\IoC;
use Aedart\Scaffold\Contracts\Builders\IndexBuilder;
use Illuminate\Contracts\Cache\Repository;

/**
 * Cache Helper
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Cache
 */
class CacheHelper
{
    /**
     * Default cache directory
     */
    const DEFAULT_CACHE_DIRECTORY = IndexBuilder::DEFAULT_SCAFFOLD_INDEX_DIRECTORY . '/cache';

    /**
     * @var Repository
     */
    static protected $cache;

    /**
     * Register the cache directory
     *
     * @param string $directory
     */
    static public function setCacheDirectory($directory)
    {
        $ioc = IoC::getInstance();

        $config = $ioc->make('config');
        $config->set('cacheDir', $directory);

        $ioc->container()['config'] = $config;
    }

    /**
     * Returns a cache repository instance
     *
     * @return Repository
     */
    static public function make()
    {
        if(!isset(self::$cache)){
            $ioc = IoC::getInstance();
            $repository = $ioc->make(Repository::class);
            self::$cache = $repository;
        }

        return self::$cache;
    }

    /**
     * Destroy the cache instance inside this helper
     */
    static public function destroy()
    {
        unset(self::$cache);
    }
}

Add const with a default cache directory


<?php

namespace Zend\Romans\Filter;

use Romans\Filter\Exception as FilterException;
use Romans\Filter\IntToRoman as BaseIntToRoman;
use Zend\Filter\FilterInterface;

/**
 * Integer to Roman Number Filter
 */
class IntToRoman implements FilterInterface
{
    /**
     * {@inheritdoc}
     */
    public function filter($value)
    {
        $result = null;

        try {
            $result = (new BaseIntToRoman())->filter($value);
        } catch (FilterException $e) {
            // default value: null
        }

        return $result;
    }
}

<?php

namespace Zend\Romans\Filter;

use Romans\Filter\Exception as FilterException;
use Romans\Filter\IntToRoman as IntToRomanFilter;
use Zend\Filter\FilterInterface;

/**
 * Integer to Roman Number Filter
 */
class IntToRoman implements FilterInterface
{
    /**
     * Base Integer to Roman Number Filter
     * @type IntToRomanFilter
     */
    private $intToRomanFilter;

    /**
     * Default Constructor
     *
     * @param IntToRomanFilter $intToRomanFilter IntToRomanFilter Object
     */
    public function __construct(IntToRomanFilter $intToRomanFilter = null)
    {
        if (! isset($intToRomanFilter)) {
            $intToRomanFilter = new IntToRomanFilter();
        }

        $this->setIntToRomanFilter($intToRomanFilter);
    }

    /**
     * Set Integer to Roman Number Filter
     *
     * @param  IntToRomanFilter $intToRomanFilter IntToRomanFilter Object
     * @return self             Fluent Interface
     */
    public function setIntToRomanFilter(IntToRomanFilter $intToRomanFilter) : self
    {
        $this->intToRomanFilter = $intToRomanFilter;
        return $this;
    }

    /**
     * Get Integer to Roman Number Filter
     *
     * @return IntToRomanFilter IntToRomanFilter Object
     */
    public function getIntToRomanFilter() : IntToRomanFilter
    {
        return $this->intToRomanFilter;
    }

    /**
     * {@inheritdoc}
     */
    public function filter($value)
    {
        $result = null;

        try {
            $result = $this->getIntToRomanFilter()->filter($value);
        } catch (FilterException $e) {
            // default value: null
        }

        return $result;
    }
}

Remove direct dependency into constructor


<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2017-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Service / SearchImage
 */

namespace PH7\Framework\Service\SearchImage;

defined('PH7') or exit('Restricted access');

class Url
{
    /**
     * @param string $sUrl
     *
     * @throws InvalidUrlException
     */
    public function __construct($sUrl)
    {
        if (
            filter_var($sUrl, FILTER_VALIDATE_URL) === false ||
            strlen($sUrl) >= $this->getMaxImageLength()
        ) {
            throw new InvalidUrlException(sprintf('%s is an invalid URL', $sUrl));
        }

        $this->sUrl = $sUrl;
    }

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

    /**
     * Images length are longer. It multiples the regular URL length by 2.
     *
     * @return int
     */
    private function getMaxImageLength()
    {
        return PH7_MAX_URL_LENGTH * 2;
    }
}

<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2017-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Service / SearchImage
 */

namespace PH7\Framework\Service\SearchImage;

defined('PH7') or exit('Restricted access');

class Url
{
    /**
     * @param string $sUrl
     *
     * @throws InvalidUrlException
     */
    public function __construct($sUrl)
    {
        if (!$this->isValid($sUrl)) {
            throw new InvalidUrlException(sprintf('%s is an invalid URL', $sUrl));
        }

        $this->sUrl = $sUrl;
    }

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

    /**
     * @param $sUrl
     *
     * @return bool
     */
    private function isValid($sUrl)
    {
        return filter_var($sUrl, FILTER_VALIDATE_URL) !== false && strlen($sUrl) <= $this->getMaxImageLength();
    }

    /**
     * Images length are longer. It multiples the regular URL length by 2.
     *
     * @return int
     */
    private function getMaxImageLength()
    {
        return PH7_MAX_URL_LENGTH * 2;
    }
}

Refactor boolean conditions imto method

Refactor boolean conditions imto method


<?hh //strict
type TRouterWeb = Router<classname<Page>>;
type TRouterAPI = Router<(function():array<string, string>)>;
type User = shape(
  'id' => int
);

<?hh //strict
type TRouterWeb = Router<classname<Page>>;
type TRouterAPI = Router<(function():array<string, mixed>)>;
type User = shape(
  'id' => int
);

Allow nested arrays in API response

:+1: Allow nested arrays in API response


<?PHP  //$Id$
// This file defines the current version of the
// backup/restore code that is being used.  This can be
// compared against the values stored in the
// database (backup_version) to determine whether upgrades should
// be performed (see db/backup_*.php)

$backup_version = 2004031200;   // The current version is a date (YYYYMMDDXX)

$backup_release = "1.2";  // User-friendly version number

<?PHP  //$Id$
// This file defines the current version of the
// backup/restore code that is being used.  This can be
// compared against the values stored in the
// database (backup_version) to determine whether upgrades should
// be performed (see db/backup_*.php)

$backup_version = 2004031400;   // The current version is a date (YYYYMMDDXX)

$backup_release = "1.2";  // User-friendly version number

Upgrade to new release day

Upgrade to new release day


<?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>

Package :: <?php echo $context->name; ?>

<?php echo $context->summary; ?>

            <?php
            echo nl2br(trim($context->description));
            ?>

        <?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?>

Releases

            <?php
             foreach ($context as $version => $release): ?>

                <a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name . '-' . $version; ?>"><?php echo $version; ?>
                <?php echo $release['stability']; ?>
                <abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?>
                <a class="download" href="<?php echo $context->getDownloadURL('.tgz'); ?>">Download

            <?php endforeach; ?>

<?php
// Set the title for the main template
$parent->context->page_title = $context->name.' | pear2.php.net';
?>

Package :: <?php echo $context->name; ?>

<?php echo $context->summary; ?>

            <?php
            $description = preg_replace("|<\?php(.*)\?\>|Use", "highlight_string('<?php\\1?>', true)", trim($context->getRaw('description')));
            echo nl2br($description);
            ?>

        <?php echo $savant->render($context->name . '-' . $context->version['release'], 'InstallInstructions.tpl.php'); ?>

Releases

            <?php
             foreach ($context as $version => $release): ?>

                <a href="<?php echo pear2\SimpleChannelFrontend\Main::getURL() . $context->name . '-' . $version; ?>"><?php echo $version; ?>
                <?php echo $release['stability']; ?>
                <abbr class="releasedate" title="<?php echo $context->date.' '.$context->time; ?>"><?php echo $context->date; ?>
                <a class="download" href="<?php echo $context->getDownloadURL('.tgz'); ?>">Download

            <?php endforeach; ?>

Add PHP code highlighting within package descriptions, patch from Amir.


<?php namespace Flarum\Api\Actions\Discussions;

use Event;

use Flarum\Core\Discussions\Commands\StartDiscussionCommand;
use Flarum\Core\Users\User;
use Flarum\Api\Actions\Base;
use Flarum\Api\Serializers\DiscussionSerializer;

class Create extends Base
{
    /**
     * Start a new discussion.
     *
     * @return Response
     */
    protected function run()
    {
        // By default, the only required attributes of a discussion are the
        // title and the content. We'll extract these from the request data
        // and pass them through to the StartDiscussionCommand.
        $title = $this->input('discussions.title');
        $content = $this->input('discussions.content');
        $command = new StartDiscussionCommand($title, $content, User::current());

        Event::fire('Flarum.Api.Actions.Discussions.Create.WillExecuteCommand', [$command, $this->document]);

        $discussion = $this->commandBus->execute($command);

        $serializer = new DiscussionSerializer(['posts']);
        $this->document->setPrimaryElement($serializer->resource($discussion));

        return $this->respondWithDocument();
    }
}

<?php namespace Flarum\Api\Actions\Discussions;

use Event;

use Flarum\Core\Discussions\Commands\StartDiscussionCommand;
use Flarum\Core\Discussions\Commands\ReadDiscussionCommand;
use Flarum\Core\Users\User;
use Flarum\Api\Actions\Base;
use Flarum\Api\Serializers\DiscussionSerializer;

class Create extends Base
{
    /**
     * Start a new discussion.
     *
     * @return Response
     */
    protected function run()
    {
        // By default, the only required attributes of a discussion are the
        // title and the content. We'll extract these from the request data
        // and pass them through to the StartDiscussionCommand.
        $title = $this->input('discussions.title');
        $content = $this->input('discussions.content');
        $user = User::current();
        $command = new StartDiscussionCommand($title, $content, $user);

        Event::fire('Flarum.Api.Actions.Discussions.Create.WillExecuteCommand', [$command, $this->document]);

        $discussion = $this->commandBus->execute($command);

        // After creating the discussion, we assume that the user has seen all
        // of the posts in the discussion; thus, we will mark the discussion
        // as read if they are logged in.
        if ($user->exists) {
            $command = new ReadDiscussionCommand($discussion->id, $user, 1);
            $this->commandBus->execute($command);
        }

        $serializer = new DiscussionSerializer(['posts']);
        $this->document->setPrimaryElement($serializer->resource($discussion));

        return $this->respondWithDocument();
    }
}

Mark a discussion as read when it is created


<?php
/**
 * Created by PhpStorm.
 * User: talv
 * Date: 10/07/16
 * Time: 16:04.
 */
namespace TalvBansal\MediaManager\Providers;

use Illuminate\Support\ServiceProvider;

/**
 * Class MediaBrowserServiceProvider.
 */
class MediaManagerServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Load the view files
        $this->loadViewsFrom(MEDIA_MANAGER_BASE_PATH.'/resources/views', 'media-manager');
        // Load language files
        $this->loadTranslationsFrom(MEDIA_MANAGER_BASE_PATH.'/resources/lang', 'media-manager');

        if ($this->app->runningInConsole()) {
            $this->defineResources();
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // Define package base path
        if (!defined('MEDIA_MANAGER_BASE_PATH')) {
            define('MEDIA_MANAGER_BASE_PATH', realpath(__DIR__.'/../../'));
        }
    }

    /**
     * Publish views to host application
     * This is only when the application is run in the console.
     */
    private function defineResources()
    {
        $this->publishes([
            MEDIA_MANAGER_BASE_PATH.'/public' => resource_path('/assets/talvbansal/media-manager'),
        ], 'media-manager');
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: talv
 * Date: 10/07/16
 * Time: 16:04.
 */
namespace TalvBansal\MediaManager\Providers;

use Illuminate\Support\ServiceProvider;

/**
 * Class MediaBrowserServiceProvider.
 */
class MediaManagerServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Load language files
        $this->loadTranslationsFrom(MEDIA_MANAGER_BASE_PATH.'/resources/lang', 'media-manager');

        if ($this->app->runningInConsole()) {
            $this->defineResources();
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        // Define package base path
        if (!defined('MEDIA_MANAGER_BASE_PATH')) {
            define('MEDIA_MANAGER_BASE_PATH', realpath(__DIR__.'/../../'));
        }
    }

    /**
     * Publish assets to host application
     * This is only when the application is run in the console.
     */
    private function defineResources()
    {
        $this->publishes([
            MEDIA_MANAGER_BASE_PATH.'/public' => resource_path('/assets/talvbansal/media-manager'),
        ], 'media-manager');
    }
}

Clean up redundant code from service provider


<?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.
 */

declare(strict_types=1);

namespace Sylius\Bundle\ApiBundle\Swagger;

use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

/** @experimental */
final class ProductVariantDocumentationNormalizer implements NormalizerInterface
{
    /** @var NormalizerInterface */
    private $decoratedNormalizer;

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

    public function supportsNormalization($data, $format = null)
    {
        return $this->decoratedNormalizer->supportsNormalization($data, $format);
    }

    public function normalize($object, $format = null, array $context = [])
    {
        $docs = $this->decoratedNormalizer->normalize($object, $format, $context);

        $docs['components']['schemas']['ProductVariant.jsonld-shop.product_variant.read']['properties']['price'] = [
            'type' => 'int',
            'readOnly' => true,
            'default' => 0,
        ];

        $docs['components']['schemas']['ProductVariant.jsonld-shop.product_variant.read']['properties']['inStock'] = [
            'type' => 'boolean',
            'readOnly' => true,
        ];

        return $docs;
    }
}

<?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.
 */

declare(strict_types=1);

namespace Sylius\Bundle\ApiBundle\Swagger;

use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

/** @experimental */
final class ProductVariantDocumentationNormalizer implements NormalizerInterface
{
    /** @var NormalizerInterface */
    private $decoratedNormalizer;

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

    public function supportsNormalization($data, $format = null)
    {
        return $this->decoratedNormalizer->supportsNormalization($data, $format);
    }

    public function normalize($object, $format = null, array $context = [])
    {
        $docs = $this->decoratedNormalizer->normalize($object, $format, $context);

        $docs['components']['schemas']['ProductVariant.jsonld-shop.product_variant.read']['properties']['price'] = [
            'type' => 'int',
            'readOnly' => true,
            'default' => 0,
        ];

        $docs['components']['schemas']['ProductVariant.jsonld-shop.product_variant.read']['properties']['inStock'] = [
            'type' => 'boolean',
            'readOnly' => true,
        ];

        $docs['components']['schemas']['ProductVariant.jsonld-shop.product_variant.read']['properties']['originalPrice'] = [
            'type' => 'int',
            'readOnly' => true,
            'default' => 0,
        ];

        return $docs;
    }
}

Update swagger docs with product variants originalPrice


<?hh

class SettingsController extends BaseController {
  public static function getPath(): string {
    return '/settings';
  }

  public static function getConfig(): ControllerConfig {
    return
      (new ControllerConfig())->setUserRoles(Vector {UserRole::Superuser});
  }

  public static function get(): :xhp {
    $settings = Map {
      'applications_open' => Settings::get('applications_open'),
    };

    return
      <x:js-scope>
        <nucleus:settings settings={$settings} />
      </x:js-scope>;
  }

  public static function post(): void {
    if (isset($_POST['applications_disabled'])) {
      Settings::set('applications_open', false);
    } else {
      Settings::set('applications_open', true);
    }

    Route::redirect('/settings');
  }
}

<?hh

class SettingsController extends BaseController {
  public static function getPath(): string {
    return '/settings';
  }

  public static function getConfig(): ControllerConfig {
    return (new ControllerConfig())->addCheck(
      Auth::requireRoles(Vector {UserRole::Superuser}),
    );
  }

  public static function get(): :xhp {
    $settings = Map {
      'applications_open' => Settings::get('applications_open'),
    };

    return
      <x:js-scope>
        <nucleus:settings settings={$settings} />
      </x:js-scope>;
  }

  public static function post(): void {
    if (isset($_POST['applications_disabled'])) {
      Settings::set('applications_open', false);
    } else {
      Settings::set('applications_open', true);
    }

    Route::redirect(self::getPath());
  }
}

Move Settings to addCheck config syntax

Move Settings to addCheck config syntax


<?php

require_once '../Mustache.php';
require_once 'PHPUnit/Framework.php';

class MustachePragmaUnescapedTest extends PHPUnit_Framework_TestCase {

	public function testPragmaUnescaped() {
		$m = new Mustache(null, array('title' => 'Bear > Shark'));

		$this->assertEquals('Bear > Shark', $m->render('{{%UNESCAPED}}{{title}}'));
		$this->assertEquals('Bear > Shark', $m->render('{{%UNESCAPED}}{{{title}}}'));
	}

}

<?php

require_once '../Mustache.php';
require_once 'PHPUnit/Framework.php';

class MustachePragmaUnescapedTest extends PHPUnit_Framework_TestCase {

	public function testPragmaUnescaped() {
		$m = new Mustache(null, array('title' => 'Bear > Shark'));

		$this->assertEquals('Bear > Shark', $m->render('{{%UNESCAPED}}{{title}}'));
		$this->assertEquals('Bear > Shark', $m->render('{{title}}'));
		$this->assertEquals('Bear > Shark', $m->render('{{%UNESCAPED}}{{{title}}}'));
		$this->assertEquals('Bear > Shark', $m->render('{{{title}}}'));
	}

}

Test consecutive renders with pragma unescaped


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class SecurityController extends AbstractController
{
    public function checkAction()
    {
        return new Response('OK');
    }

    public function profileAction()
    {
        return new Response('Welcome '.$this->getUser()->getUsername().'!');
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class SecurityController extends AbstractController
{
    public function checkAction()
    {
        return new Response('OK');
    }

    public function profileAction()
    {
        return new Response('Welcome '.$this->getUser()->getUserIdentifier().'!');
    }
}

Fix call to deprecated getUsername() in tests


<?php
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/

/*
Relies on PHPUnit to test the functionality in ./Get_BasePathmapping.php.
Related custom constants are defined in ./phpunit.xml.
Example PHPUnit run command from this file's parent directory:
./vendor/bin/phpunit --testsuite apigateway-getbasepathmapping
*/
use PHPUnit\Framework\TestCase;
use Aws\MockHandler;
use Aws\Result;
use Aws\ApiGateway\ApiGatewayClient;

class GetBasePathMappingTest extends TestCase
{
    public function testGetsTheBasePathMapping()
    {
        require('./Get_BasePathmapping.php');

        $mock = new MockHandler();
        $mock->append(new Result(array(true)));

        $apiGatewayClient = new ApiGatewayClient([
            'profile' => AWS_ACCOUNT_PROFILE_NAME,
            'region' => AWS_REGION_ID,
            'version' => API_GATEWAY_API_VERSION,
            'handler' => $mock
        ]);

        $this->assertEquals(getBasePathMapping(
            $apiGatewayClient,
            API_GATEWAY_BASE_PATH,
            API_GATEWAY_DOMAIN_NAME
        ), 'The base path mapping\'s effective URI is: : ' .
            'https://apigateway.us-east-1.amazonaws.com/domainnames/example.com/basepathmappings/%28none%29');
    }
}

<?php
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/

/*
Relies on PHPUnit to test the functionality in ./Get_BasePathmapping.php.
Related custom constants are defined in ./phpunit.xml.
Example PHPUnit run command from this file's parent directory:
./vendor/bin/phpunit --testsuite apigateway-getbasepathmapping
*/
use PHPUnit\Framework\TestCase;
use Aws\MockHandler;
use Aws\Result;
use Aws\ApiGateway\ApiGatewayClient;

class GetBasePathMappingTest extends TestCase
{
    public function testGetsTheBasePathMapping()
    {
        require('./Get_BasePathmapping.php');

        $mock = new MockHandler();
        $mock->append(new Result(array(true)));

        $apiGatewayClient = new ApiGatewayClient([
            'profile' => AWS_ACCOUNT_PROFILE_NAME,
            'region' => AWS_REGION_ID,
            'version' => API_GATEWAY_API_VERSION,
            'handler' => $mock
        ]);

        $this->assertEquals(getBasePathMapping(
            $apiGatewayClient,
            API_GATEWAY_BASE_PATH,
            API_GATEWAY_DOMAIN_NAME
        ), 'The base path mapping\'s effective URI is: ' .
            'https://apigateway.us-east-1.amazonaws.com/domainnames/example.com/basepathmappings/%28none%29');
    }
}

Fix a typo in the comparison string which caused the test to always fail.


<?php

namespace Tests;

use App\User;

abstract class IntegrationTestCase extends TestCase
{
    public function setUp()
    {
        parent::setUp(); // TODO: Change the autogenerated stub

        $this->seed(\DatabaseSeeder::class);
    }

    protected function signIn($user = null)
    {
        $user = $user ?: factory(User::class)->create();
        $this->actingAs($user);
        return $this;
    }

    protected function giveUserRole($user, $role)
    {
        return $user->giveRole($role);
    }
}

<?php

namespace Tests;

use App\User;

abstract class IntegrationTestCase extends TestCase
{
    public function setUp()
    {
        parent::setUp(); // TODO: Change the autogenerated stub

        $this->seed(\DatabaseSeeder::class);
    }

    /**
     * Sign In user
     *
     * @param null $user
     * @return $this
     */
    protected function signIn($user = null)
    {
        $user = $user ?: factory(User::class)->create();
        $this->actingAs($user);
        return $this;
    }

    /**
     * Give user a role
     *
     * @param $user
     * @param $role
     * @return mixed
     */
    protected function giveUserRole($user, $role)
    {
        return $user->giveRole($role);
    }

    /**
     * Sign in a user with Admin role
     *
     * @param array $overrides
     * @return mixed
     */
    protected function signInAdmin(array $overrides = [])
    {
        return $this->signInAs('admin', $overrides);
    }

    /**
     * Sign in a user with Author role
     *
     * @param array $overrides
     * @return mixed
     */
    protected function signInAuthor(array $overrides = [])
    {
        return $this->signInAs('author', $overrides);
    }

    /**
     * Signm in a user with Guest
     *
     * @param array $overrides
     * @return mixed
     */
    protected function signInGuest(array $overrides = [])
    {
        return $this->signInAs('guest', $overrides);
    }

    /**
     * Sign in a user with a given role
     *
     * @param $role
     * @param $overrides
     * @return mixed
     */
    protected function signInAs($role, $overrides)
    {
        $user = factory(User::class)->create($overrides);
        $this->signIn($user);
        return $this->giveUserRole($user, $role);
    }
}

Add test case helper methods to sign in user with role


<?php

/*
 * This file is part of the Integrated package.
 *
 * (c) e-Active B.V. <integrated@e-active.nl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Integrated\Bundle\ContentBundle\Document\Content;

use Integrated\Common\Form\Mapping\Annotations as Type;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * Document type Image
 *
 * @author Johnny Borg <johnny@e-active.nl>
 *
 * @ODM\Document
 * @Type\Document("Image")
 */
class Image extends File
{

}

<?php

/*
 * This file is part of the Integrated package.
 *
 * (c) e-Active B.V. <integrated@e-active.nl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Integrated\Bundle\ContentBundle\Document\Content;

use Integrated\Common\Content\Document\Storage\Embedded\StorageInterface;
use Integrated\Common\Form\Mapping\Annotations as Type;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * Document type Image
 *
 * @author Johnny Borg <johnny@e-active.nl>
 *
 * @ODM\Document
 * @Type\Document("Image")
 */
class Image extends File
{
    /**
     * @var StorageInterface
     * @Type\Field(type="integrated_image")
     * @ODM\EmbedOne(targetDocument="Integrated\Bundle\ContentBundle\Document\Content\Embedded\Storage")
     */
    protected $file;
}

Use the image type to display a thumbnail in an Integrated form.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Shop extends Model
{
    public function products()
    {
        return $this->hasMany('App\Product');
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Shop extends Model
{
    public function products()
    {
        return $this->hasMany('App\Product');
    }
    public function cities()
    {
        return $this->hasMany('App\City');
    }
    public function districts()
    {
        return $this->hasMany('App\District');
    }
    public function countries()
    {
        return $this->hasMany('App\Country');
    }
    public function types()
    {
        return $this->hasMany('App\Type');
    }
    public function shopimages()
    {
        return $this->hasMany('App\ShopImgae');
    }
    public function users()
    {
        return $this->hasMany('App\User');
    }
    public function shopassignment()
    {
        return $this->belongsTo('App\ShopAssignment');
    }
}

Create relationship for shop table

feat(shop): Create relationship for shop table

Create relationship for shop table

see #141


<?php namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {

	/**
	 * The Artisan commands provided by your application.
	 *
	 * @var array
	 */
	protected $commands = [
        'App\Console\Commands\ConvertToSpeech',
		'App\Console\Commands\Inspire',
		'App\Console\Commands\UploadLocalFile',
	];

	/**
	 * Define the application's command schedule.
	 *
	 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
	 * @return void
	 */
	protected function schedule(Schedule $schedule)
	{
		$schedule->command('inspire')
				 ->hourly();
	}

}

<?php namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {

	/**
	 * The Artisan commands provided by your application.
	 *
	 * @var array
	 */
	protected $commands = [
        'App\Console\Commands\ConvertToSpeech',
		'App\Console\Commands\Inspire',
		'App\Console\Commands\UploadLocalFile',
	];

	/**
	 * Define the application's command schedule.
	 *
	 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
	 * @return void
	 */
	protected function schedule(Schedule $schedule)
	{
		$schedule->command('articles:convert')->hourly();
        $schedule->command('articles:upload')->cron('10 * * * * *');
	}

}

Convert articles on a regular basis

Convert articles on a regular basis

- Convert articles on the hour
- Move audio files to external storage to save diskspace.


<?php

namespace ACDH\FCSSRU\mysqlonsru;

use ACDH\FCSSRU\mysqlonsru\GlossaryOnSRU,
    ACDH\FCSSRU\SRUWithFCSParameters,
    ACDH\FCSSRU\HttpResponseSender;

require_once __DIR__ . '/../../vendor/autoload.php';
// this is not autoload enabled yet. There are to many magic global constants that need to be set when loading.
if (!isset($runner)) {
    $resetRunner = true;
    $runner = true;
}
require_once __DIR__ . '/GlossaryOnSRU.php';
if (isset($resetRunner)) {
    unset($runner);
    unset($resetRunner);
}

class FilteredGlossaryOnSRU extends GlossaryOnSRU {

    protected function addFilter() {
        $this->options["xpath-filters"] = array(
            "entry-xr-bibl-tunisCourse-" => array('as' => 'signed int', '<' => '2'),
        );
    }

    public function scan() {
        $this->addFilter();
        return parent::scan();
    }

    public function search() {
        $this->addFilter();
        return parent::search();
    }
}

if (!isset($runner)) {
    $worker = new FilteredGlossaryOnSRU(new SRUWithFCSParameters('lax'));
    $response = $worker->run();
    HttpResponseSender::sendResponse($response);
}

<?php

namespace ACDH\FCSSRU\mysqlonsru;

use ACDH\FCSSRU\mysqlonsru\GlossaryOnSRU,
    ACDH\FCSSRU\SRUWithFCSParameters,
    ACDH\FCSSRU\HttpResponseSender;

require_once __DIR__ . '/../../vendor/autoload.php';
// this is not autoload enabled yet. There are to many magic global constants that need to be set when loading.
if (!isset($runner)) {
    $resetRunner = true;
    $runner = true;
}
require_once __DIR__ . '/GlossaryOnSRU.php';
if (isset($resetRunner)) {
    unset($runner);
    unset($resetRunner);
}

class FilteredGlossaryOnSRU extends GlossaryOnSRU {
    public function __construct(SRUWithFCSParameters $params = null) {
        parent::__construct($params);
        $this->params->context[0] = rtrim($this->params->context[0], 'F');
    }

    protected function addFilter() {
        $this->options["xpath-filters"] = array(
            "entry-xr-bibl-tunisCourse-" => array('as' => 'signed int', '<' => '2'),
        );
    }

    public function scan() {
        $this->addFilter();
        return parent::scan();
    }

    public function search() {
        $this->addFilter();
        return parent::search();
    }
}

if (!isset($runner)) {
    $worker = new FilteredGlossaryOnSRU(new SRUWithFCSParameters('lax'));
    $response = $worker->run();
    HttpResponseSender::sendResponse($response);
}

Remove an F from the context if it was appended to distinguish it from the unfiltered resource.


<?php

namespace AppVentus\MangopayBundle\Helper;

use Doctrine\ORM\EntityManager;
use MangoPay\MangoPayApi;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * This class is an interface between raw MongoPay api object and symfony2.
 * It is declared as a service with application wide "clientId", "clientPassword" and "baseUrl" parameters
 * This service provides some shortcuts to interact with the api
 *
 * ref: appventus_mangopay.mango_api
 *
 **/
class MangopayHelper extends MangoPayApi
{
    protected $clientId;
    protected $clientPassword;
    protected $baseUrl;
    protected $dispatcher;
    protected $entityManager;
    protected $debug;

    public function __construct($clientId, $clientPassword, $baseUrl, EventDispatcherInterface $dispatcher, EntityManager $entityManager, $debug = false)
    {
        parent::__construct();
        $this->Config->ClientId = $clientId;
        $this->Config->ClientPassword = $clientPassword;
        $this->Config->TemporaryFolder = sys_get_temp_dir().'/'.$clientId;
        $this->Config->BaseUrl = $baseUrl;
        $this->Config->DebugMode = $debug;
        $this->dispatcher = $dispatcher;
        $this->entityManager = $entityManager;
    }

}

<?php

namespace AppVentus\MangopayBundle\Helper;

use Doctrine\ORM\EntityManager;
use MangoPay\MangoPayApi;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * This class is an interface between raw MongoPay api object and symfony2.
 * It is declared as a service with application wide "clientId", "clientPassword" and "baseUrl" parameters
 * This service provides some shortcuts to interact with the api
 *
 * ref: appventus_mangopay.mango_api
 *
 **/
class MangopayHelper extends MangoPayApi
{
    protected $clientId;
    protected $clientPassword;
    protected $baseUrl;
    protected $dispatcher;
    protected $entityManager;
    protected $debug;

    public function __construct($clientId, $clientPassword, $baseUrl, EventDispatcherInterface $dispatcher, EntityManager $entityManager, $debug = false)
    {
        parent::__construct();
        $this->Config->ClientId = $clientId;
        $this->Config->ClientPassword = $clientPassword;
        $this->Config->TemporaryFolder = sys_get_temp_dir().'/'.$clientId;
        $this->Config->BaseUrl = $baseUrl;
        $this->Config->DebugMode = $debug;
        $this->dispatcher = $dispatcher;
        $this->entityManager = $entityManager;

        if (!is_dir($this->Config->TemporaryFolder)) {
            mkdir($this->Config->TemporaryFolder);
        }
    }
}

Create temporary folder if not exist

Create temporary folder if not exist


@extends('layouts.default')

@section('content')

Create sprint for {{ $project->title }}

@stop

@extends('layouts.default')

@section('content')

Create sprint for {{ $project->title }}

	{{ Form::open(['method' => 'POST', 'route' => ['store_sprint_path', $project->id]]) }}

			{{ Form::label('title', 'Title:') }}
			{{ Form::text('title', '', ['class' => 'form-control']) }}

			{{ Form::label('sprint_start', 'Sprint start:') }}
			{{ Form::text('sprint_start', '', ['class' => 'form-control']) }}

			{{ Form::label('sprint_end', 'Sprint end:') }}
			{{ Form::text('sprint_end', '', ['class' => 'form-control']) }}

		{{ Form::submit('Create new sprint', ['class' => 'btn btn-primary']) }}
	{{ Form::close() }}
@stop

Add form for sprint creation.

Add form for sprint creation.


<?php

define('NET_SSH2_LOGGING', \phpseclib\Net\SSH2::LOG_COMPLEX);

use DigipolisGent\Robo\Laravel\RoboFileBase;

class RoboFile extends RoboFileBase
{

}

<?php

define('NET_SSH2_LOGGING', \phpseclib\Net\SSH2::LOG_COMPLEX);

use DigipolisGent\Robo\Laravel\RoboFileBase;

class RoboFile extends RoboFileBase
{
    /**
     * TODO: remove this method once the gulp task is fixed.
     */
    protected function buildTask($archivename = null)
    {
        $archive = is_null($archivename) ? $this->time . '.tar.gz' : $archivename;
        $collection = $this->collectionBuilder();
        $collection
            ->taskPackageProject($archive)
                ->ignoreFileNames([
                    '.env.example',
                    '.gitattributes',
                    '.gitignore',
                    'README',
                    'README.txt',
                    'README.md',
                    'LICENSE',
                    'LICENSE.txt',
                    'LICENSE.md',
                ]);
        return $collection;
    }
}

Fix for no gulp task defined.

Fix for no gulp task defined.


<?php
namespace nochso\Omni\Test;

use nochso\Omni\Folder;
use nochso\Omni\Path;

class FolderTest extends \PHPUnit_Framework_TestCase
{
    private static $tmp;

    public static function setUpBeforeClass()
    {
        self::$tmp = Path::combine(sys_get_temp_dir(), 'phpunit-nochso-omni');
    }

    protected function setUp()
    {
        $this->cleanUp();
    }

    protected function tearDown()
    {
        $this->cleanUp();
    }

    public function testEnsure()
    {
        $this->assertFalse(is_dir(self::$tmp));
        Folder::ensure(self::$tmp);
        $this->assertTrue(is_dir(self::$tmp));
        Folder::ensure(self::$tmp);
        $this->assertTrue(is_dir(self::$tmp));
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testEnsureThrows()
    {
        Folder::ensure('');
    }

    protected function cleanUp()
    {
        if (is_dir(self::$tmp)) {
            rmdir(self::$tmp);
        }
    }
}

<?php
namespace nochso\Omni\Test;

use nochso\Omni\Folder;
use nochso\Omni\Path;

class FolderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var string Path to be used by all tests in this class
     */
    private static $base;

    public static function setUpBeforeClass()
    {
        self::$base = Path::combine(__DIR__, 'temp', 'Folder');
    }

    public static function tearDownAfterClass()
    {
        Folder::delete(self::$base);
    }

    public function testEnsure()
    {
        $path = Path::combine(self::$base, 'ensure');
        $this->assertFalse(is_dir($path));
        Folder::ensure($path);
        $this->assertTrue(is_dir($path));
        Folder::ensure($path);
        $this->assertTrue(is_dir($path));
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testEnsureThrows()
    {
        Folder::ensure('');
    }

    public function testDeleteContents()
    {
        $base = Path::combine(self::$base, 'deleteContents');
        Folder::ensure($base);

        $filepath = Path::combine($base, 'foo.txt');
        touch($filepath);
        $subfolder = Path::combine($base, 'sub-folder');
        Folder::ensure($subfolder);
        Folder::deleteContents($base);

        $this->assertFalse(is_file($filepath));
        $this->assertFalse(is_dir($subfolder));
        $this->assertTrue(is_dir($base));
    }

    public function testDeleteContents_WhenFolderMissing_MustThrow()
    {
        $base = Path::combine(self::$base, 'deleteContents_missing');
        $this->assertFalse(is_dir($base), 'Unable to set up test');

        $this->expectException('RuntimeException');
        Folder::deleteContents($base);
    }

    public function testDelete()
    {
        $base = Path::combine(self::$base, 'delete');
        Folder::ensure($base);
        Folder::delete($base);
        $this->assertFalse(is_dir($base));
    }
}

test: Add tests for Folder::delete and deleteContents


Update file cache path to /storage/framework/cache/


<?php

final class forkOnGithub
{
    private $githubRepo;

    public function __construct(\Bookdown\Bookdown\Config\IndexConfig $config)
    {
        $default = 'https://github.com/prooph/proophessor';
        if($config->isRemote()) {
            $this->githubRepo = $this->extractGithubRepo($config, $default);
        } else {
            $this->githubRepo = $default;
        }
    }

    public function __invoke()
    {
        return 'githubRepo.'">Fork me on GitHub';
    }

    private function extractGithubRepo(\Bookdown\Bookdown\Config\IndexConfig $config, $default = null)
    {
        $match = [];
        if(preg_match('/^https:\/\/raw.githubusercontent.com\/(?P<orga>[\w-_]+)\/(?P<repo>[\w-_]+)\/.*$/', $config->getFile(), $match)) {
            return 'https://github.com/' . $match['orga'] . '/' . $match['repo'];
        } else {

        };
    }
}

<?php

final class forkOnGithub
{
    private $githubRepo;

    public function __construct(\Bookdown\Bookdown\Config\IndexConfig $config)
    {
        $default = 'https://github.com/prooph/proophessor';
        if($config->isRemote()) {
            $this->githubRepo = $this->extractGithubRepo($config, $default);
        } else {
            $this->githubRepo = $default;
        }
    }

    public function __invoke()
    {
        return 'githubRepo.'">Fork me on GitHub';
    }

    private function extractGithubRepo(\Bookdown\Bookdown\Config\IndexConfig $config, $default = null)
    {
        $match = [];
        if(preg_match('/^https:\/\/raw.githubusercontent.com\/(?P<orga>[\w-_]+)\/(?P<repo>[\w-_]+)\/.*$/', $config->getFile(), $match)) {
            return 'https://github.com/' . $match['orga'] . '/' . $match['repo'];
        } else {
            return $default;
        };
    }
}

Return default if no match

Return default if no match


<?php

namespace Laravel\Passport\Http\Controllers;

use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;

class DenyAuthorizationController
{
    use RetrievesAuthRequestFromSession;

    /**
     * The response factory implementation.
     *
     * @var \Illuminate\Contracts\Routing\ResponseFactory
     */
    protected $response;

    /**
     * Create a new controller instance.
     *
     * @param  \Illuminate\Contracts\Routing\ResponseFactory  $response
     * @return void
     */
    public function __construct(ResponseFactory $response)
    {
        $this->response = $response;
    }

    /**
     * Deny the authorization request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function deny(Request $request)
    {
        $authRequest = $this->getAuthRequestFromSession($request);

        $clientUris = Arr::wrap($authRequest->getClient()->getRedirectUri());

        if (! in_array($uri = $authRequest->getRedirectUri(), $clientUris)) {
            $uri = Arr::first($clientUris);
        }

        $separator = $authRequest->getGrantTypeId() === 'implicit' ? '#' : '?';

        return $this->response->redirectTo(
            $uri.$separator.'error=access_denied&state='.$request->input('state')
        );
    }
}

<?php

namespace Laravel\Passport\Http\Controllers;

use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;

class DenyAuthorizationController
{
    use RetrievesAuthRequestFromSession;

    /**
     * The response factory implementation.
     *
     * @var \Illuminate\Contracts\Routing\ResponseFactory
     */
    protected $response;

    /**
     * Create a new controller instance.
     *
     * @param  \Illuminate\Contracts\Routing\ResponseFactory  $response
     * @return void
     */
    public function __construct(ResponseFactory $response)
    {
        $this->response = $response;
    }

    /**
     * Deny the authorization request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function deny(Request $request)
    {
        $authRequest = $this->getAuthRequestFromSession($request);

        $clientUris = Arr::wrap($authRequest->getClient()->getRedirectUri());

        if (! in_array($uri = $authRequest->getRedirectUri(), $clientUris)) {
            $uri = Arr::first($clientUris);
        }

        $separator = $authRequest->getGrantTypeId() === 'implicit' ? '#' : (strstr($uri,'?') ? '&' : '?');

        return $this->response->redirectTo(
            $uri.$separator.'error=access_denied&state='.$request->input('state')
        );
    }
}

Allow for URI with already existing query string


<?php
/**
 * WooRule - Rule integration for WooCommerce.
 *
 * @wordpress-plugin
 * @woocommerce-plugin
 *
 * Plugin Name:     WooRule
 * Plugin URI:      http://github.com/rulecom/woorule
 * Description:     Rule integration for WooCommerce
 * Version:         2.7.5
 * Author:          Rule
 * Author URI:      http://rule.se
 *
 * Text Domain:     woorule
 * Domain Path:     /languages
 *
 * @package WooRule
 */

define( 'WOORULE_VERSION', '2.7.5' );
define( 'WOORULE_PATH', plugin_dir_path( __FILE__ ) );
define( 'WOORULE_URL', plugin_dir_url( __FILE__ ) );

require_once WOORULE_PATH . 'inc/class-woorule.php';

$woorule = new Woorule();

<?php
/**
 * WooRule - Rule integration for WooCommerce.
 *
 * @wordpress-plugin
 * @woocommerce-plugin
 *
 * Plugin Name:     WooRule
 * Plugin URI:      http://github.com/rulecom/woorule
 * Description:     Rule integration for WooCommerce
 * Version:         2.7.5
 * Author:          Rule
 * Author URI:      http://rule.se
 *
 * Text Domain:     woorule
 * Domain Path:     /languages
 * WC requires at least: 3.0.0
 * WC tested up to: 6.5.1
 *
 * @package WooRule
 */

define( 'WOORULE_VERSION', '2.7.5' );
define( 'WOORULE_PATH', plugin_dir_path( __FILE__ ) );
define( 'WOORULE_URL', plugin_dir_url( __FILE__ ) );

require_once WOORULE_PATH . 'inc/class-woorule.php';

$woorule = new Woorule();

Add metadata of WooCommerce compatibility


<?php

namespace Faker\Test\Provider\en_AU;

use Faker\Generator;
use Faker\Provider\en_AU\PhoneNumber;

class PhoneNumberTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var Generator
     */
    private $faker;

    public function setUp()
    {
        $faker = new Generator();
        $faker->addProvider(new PhoneNumber($faker));
        $this->faker = $faker;
    }

    public function testPhoneNumberCanReturnData()
    {
      $number = $this->faker->phoneNumber;
      $this->assertNotEmpty($number);
    }
}

<?php

namespace Faker\Test\Provider\en_AU;

use Faker\Generator;
use Faker\Provider\en_AU\PhoneNumber;

class PhoneNumberTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var Generator
     */
    private $faker;

    public function setUp()
    {
        $faker = new Generator();
        $faker->addProvider(new PhoneNumber($faker));
        $this->faker = $faker;
    }

    public function testPhoneNumberCanReturnData()
    {
      $number = $this->faker->phoneNumber;
      $this->assertNotEmpty($number);
    }

    public function testPhoneNumberFormat()
    {
      $number = $this->faker->phoneNumber;
      $this->assertRegExp('/^(?:\+?61|0)[2-478](?:[ -]?[0-9]){8}$/', $number);
    }
}

Add testPhoneNumberFormat method to en_AU unit test class


<?php

class AddressTestCase extends TestCase
{
    public function testDataBaseAccess()
    {
        $address = App\Models\Address::all()->take(1);

        self::assertTrue(count($address) === 1);
    }

}

<?php

class AddressTestCase extends TestCase
{
    public function testDataBaseAccess()
    {
        $address = new App\Models\Address();
        $results = $address->query()->where('zip', '001-0000')->get();

        self::assertTrue(count($results) === 1);
    }

}

Set fixed value for the test.

Set fixed value for the test.


<?php

namespace Trafficgate\Transferer;

use PackageVersions\Versions;
use PHPUnit\Framework\TestCase;

class CommandTestCase extends TestCase
{
    /**
     * Empty quotes to use for symfony/process test comparators.
     *
     * @var string
     */
    public $emptyQuotes;

    public function setUp(): void
    {
        $this->determineEmptyQuotesForSymfonyProcess();
    }

    /**
     * Symfony/process returns either '' or "" depending on version.
     *
     * Versions less than or equal to 3.4.X return ''.
     * Versions greather than or equal to 4.0.0 return "".
     */
    private function determineEmptyQuotesForSymfonyProcess()
    {
        $this->emptyQuotes = "''";

        $symfonyProcessVersion = substr(
            explode(
                '@',
                Versions::getVersion('symfony/process')
            )[0],
            1
        );

        if (version_compare('4.0.0', $symfonyProcessVersion, '<')) {
            $this->emptyQuotes = '""';
        }
    }
}

<?php

namespace Trafficgate\Transferer;

use PackageVersions\Versions;
use PHPUnit\Framework\TestCase;

class CommandTestCase extends TestCase
{
    /**
     * Empty quotes to use for symfony/process test comparators.
     *
     * @var string
     */
    public $emptyQuotes;

    public function setUp(): void
    {
        $this->determineEmptyQuotesForSymfonyProcess();
    }

    /**
     * Symfony/process returns either '' or "" depending on version for empty arguments.
     *
     * Versions less than or equal to 4.1.6 return ''.
     * Versions greather than or equal to 4.1.7 return "".
     */
    private function determineEmptyQuotesForSymfonyProcess()
    {
        $this->emptyQuotes = "''";

        $symfonyProcessVersion = substr(
            explode(
                '@',
                Versions::getVersion('symfony/process')
            )[0],
            1
        );

        if (version_compare('4.1.7', $symfonyProcessVersion, '<')) {
            $this->emptyQuotes = '""';
        }
    }
}

Fix version-specific logic for symfony/process


<?php
namespace DlcUseCase\Form;

use DlcUseCase\Form\BasePriority;
use Zend\Form\Element;
use Zend\Form\Form as ZendForm;
use Zend\Form\FormInterface;

class EditUseCase extends BaseUseCase
{
    public function init()
    {
        parent::init();

        $this->setLabel('Edit use case');
    }

    public function bind($useCase, $flags = FormInterface::VALUES_NORMALIZED)
    {
        parent::bind($useCase, $flags);

        if ($useCase->getType() != null) {
            $this->byName['type']->setValue($useCase->getType()->getId());
        }

        if ($useCase->getCategory() != null) {
            $this->byName['category']->setValue($useCase->getCategory()->getId());
        }

        if ($useCase->getPriority() != null) {
            $this->byName['priority']->setValue($useCase->getPriority()->getId());
        }

        $dependenciesCollection = $this->byName['dependencies'];

        foreach ($dependenciesCollection->getFieldsets() as $fieldset) {
            $fieldset->byName['toNode']->setEmptyOption('Delete this dependency');
        }
    }
}

<?php
namespace DlcUseCase\Form;

use DlcUseCase\Form\BasePriority;
use Zend\Form\Element;
use Zend\Form\Form as ZendForm;
use Zend\Form\FormInterface;

class EditUseCase extends BaseUseCase
{
    public function init()
    {
        parent::init();

        $this->setLabel('Edit use case');
    }

    public function bind($useCase, $flags = FormInterface::VALUES_NORMALIZED)
    {
        parent::bind($useCase, $flags);

        if ($useCase->getType() != null) {
            $this->byName['type']->setValue($useCase->getType()->getId());
        }

        if ($useCase->getCategory() != null) {
            $this->byName['category']->setValue($useCase->getCategory()->getId());
        }

        if ($useCase->getPriority() != null) {
            $this->byName['priority']->setValue($useCase->getPriority()->getId());
        }

        $dependenciesCollection = $this->byName['dependencies'];

        foreach ($dependenciesCollection->getFieldsets() as $fieldset) {
            if ($fieldset->byName['toNode']->getValue() != null) {
                $fieldset->byName['toNode']->setEmptyOption('Delete this dependency');
            }
        }
    }
}

Add a fix for changing empty option of depencendy fieldset only if a value was set before


<?php

class Services_Twilio_Rest_Members
    extends Services_Twilio_ListResource
{
    /**
     * Return the member at the front of the queue. Note that any operations
     * performed on the Member returned from this function will use the /Front
     * Uri, not the Member's CallSid.
     *
     * @return Services_Twilio_Rest_Member The member at the front of the queue
     */
    public function front() {
        return new $this->instance_name($this->client, $this->uri . '/Front');
    }

    /* Participants are identified by CallSid, not like ME123 */
    public function getObjectFromJson($params, $idParam = 'sid') {
        return parent::getObjectFromJson($params, 'call_sid');
    }
}

<?php

class Services_Twilio_Rest_Members
    extends Services_Twilio_ListResource
{
    /**
     * Return the member at the front of the queue. Note that any operations
     * performed on the Member returned from this function will use the /Front
     * Uri, not the Member's CallSid.
     *
     * @return Services_Twilio_Rest_Member The member at the front of the queue
     */
    public function front() {
        return new $this->instance_name($this->client, $this->uri . '/Front');
    }

    /* Participants are identified by CallSid, not like ME123 */
    public function getObjectFromJson($params, $idParam = 'sid') {
        return parent::getObjectFromJson($params, 'call_sid');
    }

    public function getResourceName($camelized = false)
    {
      // The JSON property name is atypical.
      return $camelized ? 'Members' : 'queue_members';
    }
}

Fix account->queue->members JSON property name.


<?php
declare(strict_types=1);

namespace LotGD\Core\Tools\Model;

/**
 * Provides method and doctrine annotation for a property submodel
 */
trait PropertyManager
{
    private $propertyStorage = null;

    public function loadProperties()
    {
        if ($this->propertyStorage !== null) {
            return;
        }

        foreach ($this->properties as $property) {
            $this->propertyStorage[$property->getName()] = $property;
        }
    }

    public function getProperty(string $name, $default = null)
    {
        $this->loadProperties();

        if (isset($this->propertyStorage[$name])) {
            return $this->propertyStorage[$name]->getValue();
        } else {
            return $default;
        }
    }

    public function setProperty(string $name, $value)
    {
        $this->loadProperties();

        if (isset($this->propertyStorage[$name])) {
            $this->propertyStorage[$name]->setValue($value);
        } else {
            $className = $this->properties->getTypeClass()->name;
            $property = new $className();
            if (method_exists($property, "setOwner")) {
                $property->setOwner($this);
            }
            $property->setName($name);
            $property->setValue($value);

            $this->propertyStorage[$name] = $property;
            $this->properties->add($property);
        }
    }
}

<?php
declare(strict_types=1);

namespace LotGD\Core\Tools\Model;

/**
 * Provides method and doctrine annotation for a property submodel
 */
trait PropertyManager
{
    private $propertyStorage = null;

    public function loadProperties()
    {
        if ($this->propertyStorage !== null) {
            return;
        }

        foreach ($this->properties as $property) {
            $this->propertyStorage[$property->getName()] = $property;
        }
    }

    public function getProperty(string $name, $default = null)
    {
        $this->loadProperties();

        if (isset($this->propertyStorage[$name])) {
            return $this->propertyStorage[$name]->getValue();
        } else {
            return $default;
        }
    }

    public function unsetProperty(string $name)
    {
        $this->loadProperties();

        if (isset($this->propertyStorage[$name])) {
            $property = $this->propertyStorage[$name];
            $this->properties->removeElement($property);
            unset($this->propertyStorage[$name]);
        }
    }

    public function setProperty(string $name, $value)
    {
        $this->loadProperties();

        if (isset($this->propertyStorage[$name])) {
            $this->propertyStorage[$name]->setValue($value);
        } else {
            $className = $this->properties->getTypeClass()->name;
            $property = new $className();
            if (method_exists($property, "setOwner")) {
                $property->setOwner($this);
            }
            $property->setName($name);
            $property->setValue($value);

            $this->propertyStorage[$name] = $property;
            $this->properties->add($property);
        }
    }
}

Add unsetProperty for property managers

Add unsetProperty for property managers


<?php

/* This file is part of the Staq project, which is under MIT license */

namespace Staq\Util\Auth\Stack;

class View extends View\__Parent {

	/*************************************************************************
	  PRIVATE METHODS
	 *************************************************************************/
	protected function init_default_variables( ) {
		$page[ 'user_logged' ] = \Staq::App()->get_controller( 'Auth' )->is_logged( );
	}
}

<?php

/* This file is part of the Staq project, which is under MIT license */

namespace Staq\Util\Auth\Stack;

class View extends View\__Parent {

	/*************************************************************************
	  PRIVATE METHODS
	 *************************************************************************/
	public function render( ) {
		$this[ 'user_logged' ] = \Staq::App()->get_controller( 'Auth' )->is_logged( );
		parent::render( );
	}
}

Add user logged by default in pages

Add user logged by default in pages


<?php namespace ThibaudDauce\EloquentVariableModelConstructor;

trait VariableModelConstructorTrait {

  /**
   * Database field indicated class name.
   *
   * @var string
   */
  protected $class_name_field = 'class_name';

  /**
   * Create a new model instance that is existing.
   *
   * @override Illuminate\Database\Eloquent\Model
   * @param  array  $attributes
   * @return \Illuminate\Database\Eloquent\Model|static
   */
  public function newFromBuilder($attributes = array())
  {
    if (!isset($attributes->$class_name_field))
      return parent::newFromBuilder($attributes);

    $class = $attributes->$class_name_field;
    $instance = new $class;

    $instance->setRawAttributes((array) $attributes, true);

    return $instance;
  }

}

<?php namespace ThibaudDauce\EloquentVariableModelConstructor;

trait VariableModelConstructorTrait {

  /**
   * Get class name field.
   *
   * @return string
   */
  protected function getClassnameField()
  {
    return 'class_name';
  }

  /**
   * Create a new model instance that is existing.
   *
   * @override Illuminate\Database\Eloquent\Model
   * @param  array  $attributes
   * @return \Illuminate\Database\Eloquent\Model|static
   */
  public function newFromBuilder($attributes = array())
  {
    if (!isset($attributes[$this->getClassnameField()]))
      return parent::newFromBuilder($attributes);

    $class = $attributes[$this->getClassnameField()];
    $instance = new $class;

    $instance->setRawAttributes((array) $attributes, true);

    return $instance;
  }

}

Replace variable class name field by function get class name field


<?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\Filter;

class StripNewlines extends AbstractFilter
{

    /**
     * Defined by Zend\Filter\FilterInterface
     *
     * Returns $value without newline control characters
     *
     * @param  string $value
     * @return string
     */
    public function filter ($value)
    {
        return str_replace(array("\n", "\r"), '', $value);
    }
}

<?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\Filter;

class StripNewlines extends AbstractFilter
{

    /**
     * Defined by Zend\Filter\FilterInterface
     *
     * Returns $value without newline control characters
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        return str_replace(array("\n", "\r"), '', $value);
    }
}

[psr-2] Apply rules about spaces around method declarations

php-cs-fixer fix --fixers=function_declaration ./library
php-cs-fixer fix --fixers=function_declaration ./tests


<?php

declare(strict_types=1);

namespace Greenter\Factory;

use Greenter\Model\DocumentInterface;
use Greenter\Model\Summary\Summary;
use Greenter\Model\Voided\Reversion;
use Greenter\Model\Voided\Voided;
use Greenter\Services\SenderInterface;
use Greenter\Validator\ErrorCodeProviderInterface;
use Greenter\Ws\Services\BillSender;
use Greenter\Ws\Services\SummarySender;
use Greenter\Ws\Services\WsClientInterface;

class WsSenderResolver
{
    /**
     * @var string[]
     */
    private $summary;
    /**
     * @var WsClientInterface
     */
    private $client;
    /**
     * @var ErrorCodeProviderInterface|null
     */
    private $codeProvider;

    /**
     * WsSenderResolver constructor.
     * @param WsClientInterface $client
     * @param ErrorCodeProviderInterface|null $codeProvider
     */
    public function __construct(WsClientInterface $client, ?ErrorCodeProviderInterface $codeProvider)
    {
        $this->client = $client;
        $this->codeProvider = $codeProvider;
        $this->summary = [
            Summary::class,
            Voided::class,
            Reversion::class
        ];
    }

    public function find(DocumentInterface $document): SenderInterface
    {
        $docClass = get_class($document);
        $sender = in_array($docClass, $this->summary) ? new SummarySender() : new BillSender();
        $sender->setClient($this->client);
        $sender->setCodeProvider($this->codeProvider);

        return $sender;
    }
}

<?php

declare(strict_types=1);

namespace Greenter\Factory;

use Greenter\Model\Summary\Summary;
use Greenter\Model\Voided\Reversion;
use Greenter\Model\Voided\Voided;
use Greenter\Services\SenderInterface;
use Greenter\Validator\ErrorCodeProviderInterface;
use Greenter\Ws\Services\BillSender;
use Greenter\Ws\Services\SummarySender;
use Greenter\Ws\Services\WsClientInterface;

class WsSenderResolver
{
    /**
     * @var string[]
     */
    private $summary;
    /**
     * @var WsClientInterface
     */
    private $client;
    /**
     * @var ErrorCodeProviderInterface|null
     */
    private $codeProvider;

    /**
     * WsSenderResolver constructor.
     * @param WsClientInterface $client
     * @param ErrorCodeProviderInterface|null $codeProvider
     */
    public function __construct(WsClientInterface $client, ?ErrorCodeProviderInterface $codeProvider)
    {
        $this->client = $client;
        $this->codeProvider = $codeProvider;
        $this->summary = [
            Summary::class,
            Voided::class,
            Reversion::class
        ];
    }

    public function find(string $docClass): SenderInterface
    {
        $sender = in_array($docClass, $this->summary) ? new SummarySender() : new BillSender();
        $sender->setClient($this->client);
        $sender->setCodeProvider($this->codeProvider);

        return $sender;
    }
}

Set find by class name

Set find by class name


<?php

use Symfony\Component\ClassLoader\DebugUniversalClassLoader;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Debug\ErrorHandler;
use Symfony\Component\HttpKernel\Debug\ExceptionHandler;
use Sylius\Bundle\CoreBundle\Kernel\Kernel;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
        );

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

<?php

use Symfony\Component\ClassLoader\DebugUniversalClassLoader;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Debug\ErrorHandler;
use Symfony\Component\HttpKernel\Debug\ExceptionHandler;
use Sylius\Bundle\CoreBundle\Kernel\Kernel;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
        );

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

Allow bundles to extends sylius parameters


<?php
/**
 * mbc-transactional-digest
 *
 * Collect user .
 */

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');
// The number of messages for the consumer to reserve with each callback
// See consumeMwessage for further details.
// Necessary for parallel processing when more than one consumer is running on the same queue.
define('QOS_SIZE', 1);

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\MBC_LoggingGateway\MBC_LoggingGateway_Consumer;

// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-logging-gateway.config.inc';

// Kick off
echo '------- mbc-impoert-logging START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

$mb = $mbConfig->getProperty('messageBroker');
$mb->consumeMessage(array(new MBC_LoggingGateway_Consumer(), 'consumeLoggingGatewayQueue'), QOS_SIZE);

echo '------- mbc-impoert-logging END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

<?php
/**
 * mbc-transactional-digest
 *
 * Collect transactional campaign sign up message requests in a certain time period and
 * compose a single digest message request.
 */

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\ MBC_TransactionalDigest\MBC_TransactionalDigest_Controller;

// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-logging-gateway.config.inc';

// Kick off
echo '------- mbc-transactional-digest START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

$mb = $mbConfig->getProperty('messageBroker');
$mb->consumeMessage(array(new MBC_TransactionalDigest_Controller(), 'consumeTransactionalDigestQueue'));

echo '------- mbc-transactional-digest END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

Clean up to reference correct names of classes and related methods


<?php

namespace Galileo\SettingBundle\Lib\Model\ValueObject;

class Value
{
    private $value;

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

    public static function fromString($string)
    {
        return new Value($string);
    }

    function value()
    {
        return $this->value;
    }

    public function equalsTo(Value $value)
    {
        return $this->value === $value->value;
    }
}

<?php

namespace Galileo\SettingBundle\Lib\Model\ValueObject;

class Value
{
    private $value;

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

    public static function fromString($string)
    {
        return new Value($string);
    }

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

    public function equalsTo(Value $value)
    {
        return $this->value === $value->value;
    }
}

Add visiblity level for value object

Add visiblity level for value object


<?php

/**
 * Plugin Name: Papi
 * Description: Page Type API
 * Author: Fredrik Forsmo
 * Author URI: http://forsmo.me
 * Version: 2.3.0-dev
 * Plugin URI: https://wp-papi.github.io
 * Textdomain: papi
 */

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

// Load Composer autoload if it exists and
// the Container class isn't loaded.
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) &&
	! class_exists( '\\Frozzare\\Tank\\Container' ) ) {
	require_once __DIR__ . '/vendor/autoload.php';
}

// Load Papi loader.
require_once __DIR__ . '/src/papi-loader.php';

<?php

/**
 * Plugin Name: Papi
 * Description: Page Type API
 * Author: Fredrik Forsmo
 * Author URI: http://forsmo.me
 * Version: 2.3.0-dev
 * Plugin URI: https://wp-papi.github.io
 * Textdomain: papi
 */

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

// Load Composer autoload if it exists and
// the Container class isn't loaded.
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
	require_once __DIR__ . '/vendor/autoload.php';
}

// Load Papi loader.
require_once __DIR__ . '/src/papi-loader.php';

Remove class check for composer

Remove class check for composer


<?php

namespace Emergence\Database;

use PDO;

class PostgresConnection extends AbstractSqlConnection
{
    protected static $defaultInstance;

    public static function createInstance($pdo = null)
    {
        $pdo = $pdo ?: [];

        if (is_array($pdo)) {
            $dsn = 'pgsql:options=\'--client_encoding=UTF8\';dbname=' . $pdo['database'];

            $dsn .= ';host=' . ($pdo['host'] ?: 'localhost');
            $dsn .= ';port=' . ($pdo['port'] ?: 5432);

            if (!empty($pdo['application_name'])) {
                $dsn .= ';application_name=' . $pdo['application_name'];
            }

            $pdo = new PDO($dsn, $pdo['username'], $pdo['password']);
        }

        return parent::createInstance($pdo);
    }
}

<?php

namespace Emergence\Database;

use PDO;

class PostgresConnection extends AbstractSqlConnection
{
    protected static $defaultInstance;

    public static function createInstance($pdo = null)
    {
        $pdo = $pdo ?: [];

        if (is_array($pdo)) {
            $pdoConfig = $pdo;

            $dsn = 'pgsql:options=\'--client_encoding=UTF8\';dbname=' . $pdoConfig['database'];

            $dsn .= ';host=' . ($pdoConfig['host'] ?: 'localhost');
            $dsn .= ';port=' . ($pdoConfig['port'] ?: 5432);

            if (!empty($pdoConfig['application_name'])) {
                $dsn .= ';application_name=' . $pdoConfig['application_name'];
            }

            $pdo = new PDO($dsn, $pdoConfig['username'], $pdoConfig['password']);

            if (!empty($pdoConfig['search_path'])) {
                $pdo->query('SET search_path = "'.implode('","', $pdoConfig['search_path']).'"')->closeCursor();
            }
        }

        return parent::createInstance($pdo);
    }
}

Enable setting postgres search_path from site.json config


<?php
namespace Spotman\Acl\ResourceRulesCollectorFactory;

use BetaKiller\Factory\NamespaceBasedFactoryBuilder;
use Spotman\Acl\ResourceInterface;
use Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface;

class GenericAclResourceRulesCollectorFactory implements AclResourceRulesCollectorFactoryInterface
{
    /**
     * @var \BetaKiller\Factory\NamespaceBasedFactory
     */
    private $factory;

    /**
     * GenericAclResourceRulesCollectorFactory constructor.
     *
     * @param \BetaKiller\Factory\NamespaceBasedFactoryBuilder $factoryBuilder
     */
    public function __construct(NamespaceBasedFactoryBuilder $factoryBuilder)
    {
        $this->factory = $factoryBuilder
            ->createFactory()
            ->setClassNamespaces('Acl', 'ResourceRulesCollector')
            ->setClassSuffix('ResourceRulesCollector')
            ->setExpectedInterface(ResourceRulesCollectorInterface::class);
    }

    /**
     * @param \Spotman\Acl\ResourceInterface $resource
     *
     * @return \Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface
     * @throws \BetaKiller\Factory\FactoryException
     */
    public function createCollector(ResourceInterface $resource): ResourceRulesCollectorInterface
    {
        $collectorName = $resource->getResourceId();

        return $this->factory->create($collectorName);
    }
}

<?php
namespace Spotman\Acl\ResourceRulesCollectorFactory;

use BetaKiller\Factory\NamespaceBasedFactoryBuilderInterface;
use BetaKiller\Factory\NamespaceBasedFactoryInterface;
use Spotman\Acl\ResourceInterface;
use Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface;

class GenericAclResourceRulesCollectorFactory implements AclResourceRulesCollectorFactoryInterface
{
    /**
     * @var \BetaKiller\Factory\NamespaceBasedFactoryInterface
     */
    private NamespaceBasedFactoryInterface $factory;

    /**
     * GenericAclResourceRulesCollectorFactory constructor.
     *
     * @param \BetaKiller\Factory\NamespaceBasedFactoryBuilderInterface $factoryBuilder
     *
     * @throws \BetaKiller\Factory\FactoryException
     */
    public function __construct(NamespaceBasedFactoryBuilderInterface $factoryBuilder)
    {
        $this->factory = $factoryBuilder
            ->createFactory()
            ->setClassNamespaces('Acl', 'ResourceRulesCollector')
            ->setClassSuffix('ResourceRulesCollector')
            ->setExpectedInterface(ResourceRulesCollectorInterface::class);
    }

    /**
     * @param \Spotman\Acl\ResourceInterface $resource
     *
     * @return \Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface
     * @throws \BetaKiller\Factory\FactoryException
     */
    public function createCollector(ResourceInterface $resource): ResourceRulesCollectorInterface
    {
        $collectorName = $resource->getResourceId();

        return $this->factory->create($collectorName);
    }
}

Introduce NamespaceBasedFactoryBuilderInterface + related refactoring + CI fixes


<?php

namespace Opifer\EavBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpFoundation\Request;

/**
 * Template Repository
 */
class TemplateRepository extends EntityRepository
{
    /**
     * Find templates by request
     *
     * @param Request $request
     *
     * @return \Doctrine\Common\Collections\ArrayCollection
     */
    public function findByRequest(Request $request)
    {
        $qb = $this->createQueryBuilder('t');

        if ($request->get('name')) {
            $qb->andWhere('t.name =  :name')->setParameter('name', $request->get('name'));
        }

        return $qb->getQuery()->getArrayResult();
    }

    public function findOneByName($name){
        $qb = $this->createQueryBuilder('t');
        $qb->andWhere('t.name =  :name')->setParameter('name', $name);

        return $qb->getQuery()->getSingleResult();
    }
}

<?php

namespace Opifer\EavBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpFoundation\Request;

/**
 * Template Repository
 */
class TemplateRepository extends EntityRepository
{
    /**
     * Find templates by request
     *
     * @param Request $request
     *
     * @return \Doctrine\Common\Collections\ArrayCollection
     */
    public function findByRequest(Request $request)
    {
        $qb = $this->createQueryBuilder('t');

        if ($request->get('name')) {
            $qb->andWhere('t.name =  :name')->setParameter('name', $request->get('name'));
        }

        $qb->orderBy('t.displayName', 'ASC');

        return $qb->getQuery()->getArrayResult();
    }

    public function findOneByName($name){
        $qb = $this->createQueryBuilder('t');
        $qb->andWhere('t.name =  :name')->setParameter('name', $name);

        return $qb->getQuery()->getSingleResult();
    }
}

Return templates sorted by displayName by default


<?php
/**
* This file is part of the kreait eZ Publish Migrations Bundle
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/
namespace Kreait\EzPublish\MigrationsBundle\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration as BaseAbstractMigration;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

abstract class AbstractMigration extends BaseAbstractMigration implements ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * Sets the container
     *
     * @param ContainerInterface $container
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * Returns the container
     *
     * @return ContainerInterface
     */
    public function getContainer()
    {
        return $this->container;
    }
}

<?php
/**
* This file is part of the kreait eZ Publish Migrations Bundle
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/
namespace Kreait\EzPublish\MigrationsBundle\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration as BaseAbstractMigration;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;

abstract class AbstractMigration extends BaseAbstractMigration implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    /**
     * Returns the container
     *
     * @return ContainerInterface
     */
    protected function getContainer()
    {
        return $this->container;
    }
}

Use ContainerAwareTrait instead implementing it manually


<?php
/*
 * Modified: prepend directory path of current file, because of this file own different ENV under between Apache and command line.
 * NOTE: please remove this comment.
 */
defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..'));
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');

return new \Phalcon\Config([
    'database' => [
        'adapter'     => 'Mysql',
        'host'        => 'localhost',
        'username'    => 'root',
        'password'    => '',
        'dbname'      => 'test',
        'charset'     => 'utf8',
    ],
    'application' => [
        'appDir'         => APP_PATH . '/',
        'controllersDir' => APP_PATH . '/controllers/',
        'modelsDir'      => APP_PATH . '/models/',
        'migrationsDir'  => APP_PATH . '/migrations/',
        'viewsDir'       => APP_PATH . '/views/',
        'pluginsDir'     => APP_PATH . '/plugins/',
        'libraryDir'     => APP_PATH . '/library/',
        'cacheDir'       => BASE_PATH . '/cache/',
        'baseUri'        => '/@@name@@/',
    ]
]);

<?php
/*
 * Modified: prepend directory path of current file, because of this file own different ENV under between Apache and command line.
 * NOTE: please remove this comment.
 */
defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..'));
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');

return new \Phalcon\Config([
    'database' => [
        'adapter'     => 'Mysql',
        'host'        => 'localhost',
        'username'    => 'root',
        'password'    => '',
        'dbname'      => 'test',
        'charset'     => 'utf8',
    ],
    'application' => [
        'appDir'         => APP_PATH . '/',
        'controllersDir' => APP_PATH . '/controllers/',
        'modelsDir'      => APP_PATH . '/models/',
        'migrationsDir'  => APP_PATH . '/migrations/',
        'viewsDir'       => APP_PATH . '/views/',
        'pluginsDir'     => APP_PATH . '/plugins/',
        'libraryDir'     => APP_PATH . '/library/',
        'cacheDir'       => BASE_PATH . '/cache/',
        'baseUri'        => preg_replace('/public([\/\\\\])index.php$/', '', $_SERVER["PHP_SELF"]),
    ]
]);

Allow 'simple' project template 'url' service to understand non-root project paths.


<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright    Copyright 2013, Block 8 Limited.
* @license      https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link         http://www.phptesting.org/
*/

namespace PHPCI\Plugin;

/**
* PHP Code Sniffer Plugin - Allows PHP Code Sniffer testing.
* @author       Dan Cryer <dan@block8.co.uk>
* @package      PHPCI
* @subpackage   Plugins
*/
class PhpCodeSniffer implements \PHPCI\Plugin
{
    protected $directory;
    protected $args;
    protected $phpci;

    public function __construct(\PHPCI\Builder $phpci, array $options = array())
    {
        $this->phpci        = $phpci;
        $this->directory    = isset($options['directory']) ? $options['directory'] : $phpci->buildPath;
        $this->standard     = isset($options['standard']) ? $options['standard'] : 'PSR2';
    }

    public function execute()
    {
        $ignore = '';

        if (count($this->phpci->ignore)) {
            $map = function ($item) {
                return substr($item, -1) == '/' ? $item . '*' : $item . '/*';
            };

            $ignore = array_map($map, $this->phpci->ignore);

            $ignore = ' --ignore=' . implode(',', $ignore);
        }

        $cmd = PHPCI_BIN_DIR . 'phpcs --standard=%s %s "%s"';
        return $this->phpci->executeCommand($cmd, $this->standard, $ignore, $this->phpci->buildPath);
    }
}

<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright    Copyright 2013, Block 8 Limited.
* @license      https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link         http://www.phptesting.org/
*/

namespace PHPCI\Plugin;

/**
* PHP Code Sniffer Plugin - Allows PHP Code Sniffer testing.
* @author       Dan Cryer <dan@block8.co.uk>
* @package      PHPCI
* @subpackage   Plugins
*/
class PhpCodeSniffer implements \PHPCI\Plugin
{
    protected $directory;
    protected $args;
    protected $phpci;

    public function __construct(\PHPCI\Builder $phpci, array $options = array())
    {
        $this->phpci        = $phpci;
        $this->directory    = isset($options['directory']) ? $options['directory'] : $phpci->buildPath;
        $this->standard     = isset($options['standard']) ? $options['standard'] : 'PSR2';
    }

    public function execute()
    {
        $ignore = '';

        if (count($this->phpci->ignore)) {
            $ignore = ' --ignore=' . implode(',', $ignore);
        }

        $cmd = PHPCI_BIN_DIR . 'phpcs --standard=%s %s "%s"';
        return $this->phpci->executeCommand($cmd, $this->standard, $ignore, $this->phpci->buildPath);
    }
}

Fix for ignores in PHPCS

Fix for ignores in PHPCS


<?php if(!defined('SYSTEM')) die('no access');  ?>
<?php
$admin = get_instance('admin');
if( ! $admin->is_writable()): ?>

Your content and etc directories must be writeable for proper functionality.

WARNING:  If these are in you web root directory, it is NOT SAFE to make them writable.

Please see Setting up and securing an app
if you are unsure how to do this.

<?php endif; ?>

SimpleApp Open source application development framework for PHP 5

<?php if(!defined('SYSTEM')) die('no access');  ?>
<?php
$admin = get_instance('admin');
$auth = get_instance('simpleauth');
if( ! $admin->is_writable() && $auth->logged_in() !== false): ?>

Your content and etc directories must be writeable for proper functionality.

WARNING:  If these are in you web root directory, it is NOT SAFE to make them writable.

Please see Setting up and securing an app
if you are unsure how to do this.

<?php endif; ?>

SimpleApp Open source application development framework for PHP 5

Fix messaging so that writable directory error only displays if logged in.


<?php namespace Modules\Page\Providers;

use Modules\Core\Providers\RoutingServiceProvider as CoreRoutingServiceProvider;

class RouteServiceProvider extends CoreRoutingServiceProvider
{
    /**
     * The root namespace to assume when generating URLs to actions.
     * @var string
     */
    protected $namespace = 'Modules\Page\Http\Controllers';

    /**
     * @return string
     */
    protected function getFrontendRoute()
    {
        return false;
    }

    /**
     * @return string
     */
    protected function getBackendRoute()
    {
        return __DIR__ . '/../Http/backendRoutes.php';
    }

    /**
     * @return string
     */
    protected function getApiRoute()
    {
        return false;
    }
}

<?php namespace Modules\Page\Providers;

use Modules\Core\Providers\RoutingServiceProvider as CoreRoutingServiceProvider;

class RouteServiceProvider extends CoreRoutingServiceProvider
{
    /**
     * The root namespace to assume when generating URLs to actions.
     * @var string
     */
    protected $namespace = 'Modules\Page\Http\Controllers';

    /**
     * @return string
     */
    protected function getFrontendRoute()
    {
        return __DIR__ . '/../Http/frontendRoutes.php';
    }

    /**
     * @return string
     */
    protected function getBackendRoute()
    {
        return __DIR__ . '/../Http/backendRoutes.php';
    }

    /**
     * @return string
     */
    protected function getApiRoute()
    {
        return false;
    }
}

Load the front end routes

Load the front end routes


<?php

/* This file is part of the Staq project, which is under MIT license */

namespace Staq\Core\Data\Stack\Attribute;

class SerializedList extends SerializedArray
{

    /* PUBLIC USER METHODS
     *************************************************************************/
    public function get()
    {
        $list = parent::get();
        return array_values($list);
    }

    public function set($list)
    {
        \UArray::doConvertToArray($list);
        $list = array_values($list);
        return parent::set($list);
    }

    public function add($add)
    {
        $list = $this->get();
        $list[] = $add;
        $this->set($list);
        return $this;
    }

    public function addList($addList)
    {
        $list = $this->get();
        $list = array_merge($list, $addList);
        $this->set($list);
        return $this;
    }
}

<?php

/* This file is part of the Staq project, which is under MIT license */

namespace Staq\Core\Data\Stack\Attribute;

class SerializedList extends SerializedArray
{

    /* PUBLIC USER METHODS
     *************************************************************************/
    public function get()
    {
        $list = parent::get();
        $list = array_values($list);
        $list = array_map($list, array($this, 'formatItem'));
        return $list;
    }

    public function set($list)
    {
        \UArray::doConvertToArray($list);
        $list = array_values($list);
        $list = array_filter($list, array($this, 'validateItem'));
        $list = array_map($list, array($this, 'formatItemSeed'));
        return parent::set($list);
    }

    public function add($add)
    {
        $list = $this->get();
        $list[] = $add;
        $this->set($list);
        return $this;
    }

    public function addList($addList)
    {
        $list = $this->get();
        $list = array_merge($list, $addList);
        $this->set($list);
        return $this;
    }

    /* PRIVATE USER METHODS
     *************************************************************************/
    protected function validateItem($item) {
        return true;
    }

    protected function formatItemSeed($item) {
        return $item;
    }

    protected function formatItem($item) {
        return $item;
    }
}

Add validation hooks on serialized list

Add validation hooks on serialized list


<?php

namespace Ojs\ImportBundle\Helper;

class FileHelper {
    public static $mimeToExtMap = [
        'application/pdf'    => 'pdf',
        'image/jpeg'         => 'jpg',
        'application/msword' => 'doc',
        'application/zip'    => 'zip',
        'application/xml'    => 'xml',
        'application/octet-stream' => 'bin',
        'application/text-plain:formatted' => 'txt',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx'
    ];
}

<?php

namespace Ojs\ImportBundle\Helper;

class FileHelper {
    public static $mimeToExtMap = [
        'application/pdf'    => 'pdf',
        'image/jpeg'         => 'jpg',
        'image/png'          => 'png',
        'application/msword' => 'doc',
        'application/zip'    => 'zip',
        'application/xml'    => 'xml',
        'application/octet-stream' => 'bin',
        'application/text-plain:formatted' => 'txt',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx'
    ];
}

Add PNG to mime to extension map

Add PNG to mime to extension map


<?php
/**
 * Used to store saved customer payment cards
 */

$installer = $this;
$installer->startSetup();

$installer->run("
CREATE TABLE {$this->getTable('ebanx_user_cards')} (
    `ebanx_card_id` int(11) unsigned NOT NULL auto_increment,
    `user_id` int(11) NOT NULL default 0,
    `token` varchar(255) NOT NULL default '',
    `masked_number` varchar(20) NOT NULL default '',
    `brand` varchar(255) NOT NULL default '',
    `payment_method` varchar(255) NOT NULL default '',
     PRIMARY KEY (ebanx_card_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

");

$installer->endSetup();

<?php
/**
 * Used to store saved customer payment cards
 */

$installer = $this;
$installer->startSetup();

if (!$installer->tableExists('ebanx_user_cards')) {

	$installer->run("
	CREATE TABLE {$this->getTable('ebanx_user_cards')} (
	    `ebanx_card_id` int(11) unsigned NOT NULL auto_increment,
	    `user_id` int(11) NOT NULL default 0,
	    `token` varchar(255) NOT NULL default '',
	    `masked_number` varchar(20) NOT NULL default '',
	    `brand` varchar(255) NOT NULL default '',
	    `payment_method` varchar(255) NOT NULL default '',
	     PRIMARY KEY (ebanx_card_id)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;

");
}

$installer->endSetup();

Check if table exists before creating

Check if table exists before creating


<?php
namespace Flipside;
/**
 * Singleton class
 *
 * This file describes the Singleton parent class
 *
 * PHP version 5 and 7
 *
 * @author Patrick Boyd / problem@burningflipside.com
 * @copyright Copyright (c) 2015, Austin Artistic Reconstruction
 * @license http://www.apache.org/licenses/ Apache 2.0 License
 */

/**
 * A class that only allows a single instance to be created.
 *
 * This class only allows a single instance to be created. This is especially useful for
 * database and other abstractions to reduce the number of connections.
 */
class Singleton
{
    /**
     * Return the instance of the object
     *
     * This function returns the object instance if it exists and if not it will create a new copy
     */
    public static function getInstance()
    {
        static $instances = array();
        $class = get_called_class();
        if(!isset($instances[$class]))
        {
            $instances[$class] = new static();
        }
        return $instances[$class];
    }

    /**
     * A singleton constructor should not be publically accessible. All callers should use getInstance()
     */
    protected function __construct()
    {
    }

    /**
     * A singleton can not be cloned
     */
    private function __clone()
    {
    }

    /**
     * A singleton can not be serialized and deserialized
     *
     * @SuppressWarnings("UnusedPrivateMethod")
     */
    private function __wakeup()
    {
    }
}
/* vim: set tabstop=4 shiftwidth=4 expandtab: */

<?php
namespace Flipside;
/**
 * Singleton class
 *
 * This file describes the Singleton parent class
 *
 * PHP version 5 and 7
 *
 * @author Patrick Boyd / problem@burningflipside.com
 * @copyright Copyright (c) 2015, Austin Artistic Reconstruction
 * @license http://www.apache.org/licenses/ Apache 2.0 License
 */

/**
 * A class that only allows a single instance to be created.
 *
 * This class only allows a single instance to be created. This is especially useful for
 * database and other abstractions to reduce the number of connections.
 */
class Singleton
{
    /**
     * Return the instance of the object
     *
     * This function returns the object instance if it exists and if not it will create a new copy
     */
    public static function getInstance()
    {
        static $instances = array();
        $class = get_called_class();
        if(!isset($instances[$class]))
        {
            $instances[$class] = new static();
        }
        return $instances[$class];
    }

    /**
     * A singleton constructor should not be publically accessible. All callers should use getInstance()
     */
    protected function __construct()
    {
    }

    /**
     * A singleton can not be cloned
     */
    private function __clone()
    {
    }
}
/* vim: set tabstop=4 shiftwidth=4 expandtab: */

Remove wakeup method as that isn't supported any longer


<?php

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('auth', 'Api\AuthController@auth');

Route::group(['middleware' => 'jwt.auth', 'namespace' => 'Api'], function () {
    Route::post('auth/me', 'AuthController@me');
    Route::post('auth/refresh', 'AuthController@refresh');
});

Route::group(['middleware' => 'api'], function () {

	/**
	 * GET
	 */
	Route::get('/', function ()    {
        return 'GET api';
    });
    Route::get('observations', function ()    {
        return 'GET api/observations';
    });
    Route::get('observations/{id}', function ($id)    {
        return 'GET api/observations/' . $id;
    });
    Route::get('observations/{id}', function ($id)    {
        return 'GET api/observations/' . $id;
    });
    Route::get('observations/{id}/picture', function ($id)    {
        return 'GET api/observations/' . $id . '/picture';
    });

    /**
	 * POST
	 */
    Route::post('observations', function ()    {
        return 'POST api/observations';
    });
    Route::post('observations/vote', function ()    {
        return 'POST api/observations/vote';
    });
});

Add API routes without real implementation


<?php

declare(strict_types = 1);

namespace Sop\JWX\JWE\KeyAlgorithm\Feature;

/**
 * Trait for key algorithms employing random CEK generation.
 */
trait RandomCEK
{
    /**
     * Generate a random content encryption key.
     *
     * @param int $length Key length in bytes
     *
     * @throws \RuntimeException
     *
     * @return string
     */
    public function cekForEncryption(int $length): string
    {
        $ret = openssl_random_pseudo_bytes($length);
        if (false === $ret) {
            throw new \RuntimeException('openssl_random_pseudo_bytes() failed.');
        }
        return $ret;
    }
}

<?php

declare(strict_types = 1);

namespace Sop\JWX\JWE\KeyAlgorithm\Feature;

/**
 * Trait for key algorithms employing random CEK generation.
 */
trait RandomCEK
{
    /**
     * Generate a random content encryption key.
     *
     * @param int $length Key length in bytes
     *
     * @throws \RuntimeException
     *
     * @return string
     */
    public function cekForEncryption(int $length): string
    {
        if ($length < 1) {
            throw new \InvalidArgumentException("Length must be greater than 0.");
        }
        $ret = openssl_random_pseudo_bytes($length);
        if (false === $ret) {
            throw new \RuntimeException('openssl_random_pseudo_bytes() failed.');
        }
        return $ret;
    }
}

Unify error between php versions

Unify error between php versions