<?php

namespace Oro\Bundle\TranslationBundle\Helper;

use Oro\Bundle\ConfigBundle\Config\ConfigManager;
use Oro\Bundle\LocaleBundle\DependencyInjection\Configuration;
use Oro\Bundle\TranslationBundle\Entity\Language;

class LanguageHelper
{
    /** @var ConfigManager */
    protected $configManager;

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

    /**
     * @param Language $language
     */
    public function updateSystemConfiguration(Language $language)
    {
        $languages = $this->configManager->get($this->getConfigurationName(), true);

        if ($language->isEnabled()) {
            if(!in_array($language->getCode(), $languages, true)){
                $languages[] = $language->getCode();
            }
        } else {
            if (false !== ($index = array_search($language->getCode(), $languages, true))) {
                unset($languages[$index]);
            }
        }

        $this->configManager->set($this->getConfigurationName(), $languages);
        $this->configManager->flush();
    }

    /**
     * @return string
     */
    protected function getConfigurationName()
    {
        return Configuration::getConfigKeyByName(Configuration::LANGUAGES);
    }
}

<?php

namespace Oro\Bundle\TranslationBundle\Helper;

use Oro\Bundle\ConfigBundle\Config\ConfigManager;
use Oro\Bundle\LocaleBundle\DependencyInjection\Configuration;
use Oro\Bundle\TranslationBundle\Entity\Language;

class LanguageHelper
{
    /** @var ConfigManager */
    protected $configManager;

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

    /**
     * @param Language $language
     */
    public function updateSystemConfiguration(Language $language)
    {
        $languages = $this->configManager->get($this->getConfigurationName(), true);

        if ($language->isEnabled()) {
            if (!in_array($language->getCode(), $languages, true)) {
                $languages[] = $language->getCode();
            }
        } else {
            if (false !== ($index = array_search($language->getCode(), $languages, true))) {
                unset($languages[$index]);
            }
        }

        $this->configManager->set($this->getConfigurationName(), $languages);
        $this->configManager->flush();
    }

    /**
     * @return string
     */
    protected function getConfigurationName()
    {
        return Configuration::getConfigKeyByName(Configuration::LANGUAGES);
    }
}

BAP-11412: Implement enable/disable operations
- CS Fix


<?php
class Kwc_Advanced_IntegratorTemplate_Embed_ContentSender extends Kwf_Component_Abstract_ContentSender_Default
{
    protected function _render($includeMaster)
    {
        header('X-Robots-Tag: noindex');
        $domain = $this->_data->getParentByClass('Root_Domain_Component')->getAbsoluteUrl();
        $hasDynamicParts = false;
        $ret = parent::_render($includeMaster, $hasDynamicParts);
        $ret = str_replace('href="/', 'href="' . $domain . '/', $ret);
        $ret = str_replace('src="/', 'src="' . $domain . '/', $ret);
        return $ret;
    }
}

<?php
class Kwc_Advanced_IntegratorTemplate_Embed_ContentSender extends Kwf_Component_Abstract_ContentSender_Default
{
    protected function _render($includeMaster)
    {
        header('X-Robots-Tag: noindex');
        $domain = $this->_data->getParentByClass('Root_Domain_Component')->getAbsoluteUrl();
        $hasDynamicParts = false;
        $ret = parent::_render($includeMaster, $hasDynamicParts);
        $ret = str_replace('href="/', 'href="' . $domain . '/', $ret);
        $ret = str_replace('src="/', 'src="' . $domain . '/', $ret);
        $ret = str_replace("src='/", "src='" . $domain . '/', $ret);
        return $ret;
    }
}

Replace also deferred js url in Integrator Template


<?php
namespace RocketTheme\Toolbox\ArrayTraits;

/**
 * Implements getters and setters.
 *
 * @package RocketTheme\Toolbox\ArrayTraits
 * @author RocketTheme
 * @license MIT
 */
trait Getters
{
    use NestedArrayAccess;

    /**
     * Magic setter method
     *
     * @param mixed $offset Asset name value
     * @param mixed $value  Asset value
     */
    public function __set($offset, $value)
    {
        $this->offsetSet($offset, $value);
    }

    /**
     * Magic getter method
     *
     * @param  mixed $offset Asset name value
     * @return mixed         Asset value
     */
    public function __get($offset)
    {
       return $this->offsetGet($offset);
    }

    /**
     * Magic method to determine if the attribute is set
     *
     * @param  mixed   $offset Asset name value
     * @return boolean         True if the value is set
     */
    public function __isset($offset)
    {
        return $this->offsetExists($offset);
    }

    /**
     * Magic method to unset the attribute
     *
     * @param mixed $offset The name value to unset
     */
    public function __unset($offset)
    {
        $this->offsetUnset($offset);
    }
}

<?php
namespace RocketTheme\Toolbox\ArrayTraits;

/**
 * Implements getters and setters.
 *
 * @package RocketTheme\Toolbox\ArrayTraits
 * @author RocketTheme
 * @license MIT
 */
trait NestedArrayAccessWithGetters
{
    use NestedArrayAccess;

    /**
     * Magic setter method
     *
     * @param mixed $offset Asset name value
     * @param mixed $value  Asset value
     */
    public function __set($offset, $value)
    {
        $this->offsetSet($offset, $value);
    }

    /**
     * Magic getter method
     *
     * @param  mixed $offset Asset name value
     * @return mixed         Asset value
     */
    public function __get($offset)
    {
       return $this->offsetGet($offset);
    }

    /**
     * Magic method to determine if the attribute is set
     *
     * @param  mixed   $offset Asset name value
     * @return boolean         True if the value is set
     */
    public function __isset($offset)
    {
        return $this->offsetExists($offset);
    }

    /**
     * Magic method to unset the attribute
     *
     * @param mixed $offset The name value to unset
     */
    public function __unset($offset)
    {
        $this->offsetUnset($offset);
    }
}

Fix typo on last commit

Fix typo on last commit


<?php
/**
 * This file is part of PHP Mess Detector.
 *
 * Copyright (c) Manuel Pichler <mapi@phpmd.org>.
 * All rights reserved.
 *
 * Licensed under BSD License
 * For full copyright and license information, please see the LICENSE file.
 * Redistributions of files must retain the above copyright notice.
 *
 * @author Manuel Pichler <mapi@phpmd.org>
 * @copyright Manuel Pichler. All rights reserved.
 * @license https://opensource.org/licenses/bsd-license.php BSD License
 * @link http://phpmd.org/
 */

class testRuleAppliesMultipleTimesToMethodWithExitExpression
{
    public function testRuleAppliesMultipleTimesToMethodWithExitExpression()
    {
        if (true) {
            exit(0);
        } else {
            if (time() % 42 === 0) {
                exit(1);
            }
        }
        exit(2);
    }
}

<?php
/**
 * This file is part of PHP Mess Detector.
 *
 * Copyright (c) Manuel Pichler <mapi@phpmd.org>.
 * All rights reserved.
 *
 * Licensed under BSD License
 * For full copyright and license information, please see the LICENSE file.
 * Redistributions of files must retain the above copyright notice.
 *
 * @author Manuel Pichler <mapi@phpmd.org>
 * @copyright Manuel Pichler. All rights reserved.
 * @license https://opensource.org/licenses/bsd-license.php BSD License
 * @link http://phpmd.org/
 */

class testRuleAppliesMultipleTimesToMethodWithExitExpression
{
    public function testRuleAppliesMultipleTimesToMethodWithExitExpression()
    {
        if (true) {
            exit(0);
        } elseif (time() % 42 === 0) {
            exit(1);
        }
        exit(2);
    }
}

Use elseif instead of else + nested if

Use elseif instead of else + nested if

Co-authored-by: Kyle <a691fe45072ea6917fdb7509f2e859c5439778af@users.noreply.github.com>


<?php
/**
 * @title            API Interface
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2012-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 / Payment / Gateway / Api
 * @version          1.0
 */

namespace PH7\Framework\Payment\Gateway\Api;

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

interface Api
{
    /**
     * Get Checkout URL.
     *
     * @param string $sOptionalParam Default ''
     *
     * @return string
     */
    public function getUrl($sOptionalParam = '');

    /**
     * Get message status.
     *
     * @return string
     */
    public function getMsg();

    /**
     * Check if the transaction is valid.
     *
     * @param string $sOptionalParam1 Default ''
     * @param string $sOptionalParam2 Default ''
     *
     * @return boolean
     */
    public function valid($sOptionalParam1 = '', $sOptionalParam2 = '');
}

<?php
/**
 * @title            API Interface
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2012-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 / Payment / Gateway / Api
 */

namespace PH7\Framework\Payment\Gateway\Api;

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

interface Api
{
    /**
     * Get Checkout URL.
     *
     * @param string $sOptionalParam Default ''
     *
     * @return string
     */
    public function getUrl($sOptionalParam = '');

    /**
     * Get message status.
     *
     * @return string
     */
    public function getMsg();

    /**
     * Check if the transaction is valid.
     *
     * @param string $sOptionalParam1 Default ''
     * @param string $sOptionalParam2 Default ''
     *
     * @return boolean
     */
    public function valid($sOptionalParam1 = '', $sOptionalParam2 = '');
}

Remove redundant @version phpdoc tag

[CleanUp] Remove redundant @version phpdoc tag


<?php

/*
 * (c) Prezent Internet B.V. <info@prezent.nl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Prezent\Tests\Doctrine\Translatable\Mapping\Driver;

use Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator;
use Prezent\Doctrine\Translatable\Mapping\Driver\YamlDriver;

class YamlDriverTest extends BaseDriverTest
{
    protected function getDriver()
    {
        $locator = new SymfonyFileLocator([
            __DIR__ . '/../../../../Fixture/yaml' => 'Prezent\\Tests\\Fixture',
        ], '.yml');

        return new YamlDriver($locator);
    }
}

<?php

/*
 * (c) Prezent Internet B.V. <info@prezent.nl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Prezent\Tests\Doctrine\Translatable\Mapping\Driver;

use Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator;
use Prezent\Doctrine\Translatable\Mapping\Driver\YamlDriver;

class YamlDriverTest extends BaseDriverTest
{
    protected function getDriver()
    {
        $locator = new SymfonyFileLocator(array(
            __DIR__ . '/../../../../Fixture/yaml' => 'Prezent\\Tests\\Fixture',
        ), '.yml');

        return new YamlDriver($locator);
    }
}

Make test run on PHP 5.3

Make test run on PHP 5.3


<?php

namespace Amenophis\Bundle\SocialBundle\Twig;

use Amenophis\Bundle\SocialBundle\Service\SocialManager;

class SocialExtension extends \Twig_Extension
{
    public function __construct(SocialManager $service)
    {
        $this->service = $service;
    }

    public function getFunctions()
    {
        return array(
            'social_is' => new \Twig_Function_Method($this, 'social_is'),
            'social_count' => new \Twig_Function_Method($this, 'social_count'),
        );
    }

    public function social_is($type, $item)
    {
        return $this->service->is($type, $item);
    }

    public function social_count($type, $item)
    {
        return $this->service->count($type, $item);
    }

    public function getName()
    {
        return 'amenophis_social_extension';
    }
}

<?php

namespace Amenophis\Bundle\SocialBundle\Twig;

use Amenophis\Bundle\SocialBundle\Manager\SocialManager;

class SocialExtension extends \Twig_Extension
{
    public function __construct(SocialManager $service)
    {
        $this->service = $service;
    }

    public function getFunctions()
    {
        return array(
            'social_is' => new \Twig_Function_Method($this, 'social_is'),
            'social_count' => new \Twig_Function_Method($this, 'social_count'),
            'social_related' => new \Twig_Function_Method($this, 'social_related'),
            'social_related_owner' => new \Twig_Function_Method($this, 'social_related_owner'),
        );
    }

    public function social_is($type, $item)
    {
        return $this->service->is($type, $item);
    }

    public function social_count($type, $item)
    {
        return $this->service->count($type, $item);
    }

    public function social_related($type, $item)
    {
        return $this->service->related($type, $item);
    }

     public function social_related_owner($social_item)
    {
        return $this->service->related_owner($social_item);
    }

    public function getName()
    {
        return 'amenophis_social_extension';
    }
}

Add related et related_owner methods

Add related et related_owner methods


<?php
declare(strict_types=1);

return [
    [
        'table' => 'schema_generator_comment',
        'columns' => [
            'id' => ['type' => 'integer'],
            'title' => ['type' => 'string', 'null' => true],
        ],
    ],
    [
        'table' => 'schema_generator',
        'columns' => [
            'id' => ['type' => 'integer'],
            'relation_id' => ['type' => 'integer', 'null' => true],
            'title' => ['type' => 'string', 'null' => true],
            'body' => 'text',
        ],
        'constraints' => [
            'primary' => ['type' => 'primary', 'columns' => ['id']],
            'relation_idx' => [
                'type' => 'foreign',
                'columns' => ['relation_id'],
                'references' => ['schema_generator_comment', 'id'],
            ],
        ],
        'indexes' => [
            'title_idx' => [
                'type' => 'index',
                'columns' => ['title'],
            ],
        ],
    ],
];

<?php
declare(strict_types=1);

return [
    [
        'table' => 'schema_generator_comment',
        'columns' => [
            'id' => ['type' => 'integer'],
            'title' => ['type' => 'string', 'null' => true],
        ],
    ],
    [
        'table' => 'schema_generator',
        'columns' => [
            'id' => ['type' => 'integer'],
            'relation_id' => ['type' => 'integer'],
            'title' => ['type' => 'string', 'null' => true],
            'body' => 'text',
        ],
        'constraints' => [
            'primary' => ['type' => 'primary', 'columns' => ['id']],
            'relation_fk' => [
                'type' => 'foreign',
                'columns' => ['relation_id'],
                'references' => ['schema_generator_comment', 'id'],
            ],
        ],
        'indexes' => [
            'relation_idx' => [
                'type' => 'index',
                'columns' => ['relation_id'],
            ],
            'title_idx' => [
                'type' => 'index',
                'columns' => ['title'],
            ],
        ],
    ],
];

Add index and rename foreign key.

Add index and rename foreign key.


<?php
/**
 * This file is part of PHP Mess Detector.
 *
 * Copyright (c) Manuel Pichler <mapi@phpmd.org>.
 * All rights reserved.
 *
 * Licensed under BSD License
 * For full copyright and license information, please see the LICENSE file.
 * Redistributions of files must retain the above copyright notice.
 *
 * @author Manuel Pichler <mapi@phpmd.org>
 * @copyright Manuel Pichler. All rights reserved.
 * @license https://opensource.org/licenses/bsd-license.php BSD License
 * @link http://phpmd.org/
 */

function testRuleAppliesMultipleTimesToFunctionWithEvalExpression()
{
    if (true) {
        eval('$a = 17;');
    } else {
        if (time() % 42 === 0) {
            eval('$a = 23;');
        }
    }
    eval('$a = 42;');
}

<?php
/**
 * This file is part of PHP Mess Detector.
 *
 * Copyright (c) Manuel Pichler <mapi@phpmd.org>.
 * All rights reserved.
 *
 * Licensed under BSD License
 * For full copyright and license information, please see the LICENSE file.
 * Redistributions of files must retain the above copyright notice.
 *
 * @author Manuel Pichler <mapi@phpmd.org>
 * @copyright Manuel Pichler. All rights reserved.
 * @license https://opensource.org/licenses/bsd-license.php BSD License
 * @link http://phpmd.org/
 */

function testRuleAppliesMultipleTimesToFunctionWithEvalExpression()
{
    if (true) {
        eval('$a = 17;');
    } elseif (time() % 42 === 0) {
        eval('$a = 23;');
    }
    eval('$a = 42;');
}

Use elseif instead of else + nested if


<?php

class Ticket extends \Eloquent {
	protected $fillable = [
		'title',
		'description',
		'priority_id',
		'owner_id'
	];

	public function user() {

		return $this->belongsTo('User');
	}
}

<?php

class Ticket extends \Eloquent {
	protected $fillable = [
		'title',
		'description',
		'priority_id',
		'owner_id'
	];

	public function owner() {

		return $this->belongsTo('User');
	}
}

Rename user to owner for model relationship to users


<?php

namespace Majora\OAuthServerBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * Class MajoraOAuthServerExtension.
 *
 * @author Raphael De Freitas <raphael@de-freitas.net>
 */
class MajoraOAuthServerExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);
        $container->setParameter('majora_oauth_server.config', $config);
    }

    /**
     * {@inheritdoc}
     */
    public function getAlias()
    {
        return 'majora_oauth_server';
    }
}

<?php

namespace Majora\OAuthServerBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * Class MajoraOAuthServerExtension.
 *
 * @author Raphael De Freitas <raphael@de-freitas.net>
 */
class MajoraOAuthServerExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('majora_oauth_server.storage.access_token', $config['storage']['access_token']);
        $container->setParameter('majora_oauth_server.storage.auth_code', $config['storage']['auth_code']);
        $container->setParameter('majora_oauth_server.storage.client', $config['storage']['client']);
        $container->setParameter('majora_oauth_server.storage.refresh_token', $config['storage']['refresh_token']);
    }

    /**
     * {@inheritdoc}
     */
    public function getAlias()
    {
        return 'majora_oauth_server';
    }
}

Break the parameters into multiples parameters


<?php
namespace HomoChecker\Model;

use TrueBV\Punycode;

class Status
{
    public function __construct(HomoInterface $homo, string $icon = null, string $status = null, float $duration = null)
    {
        $this->homo = (object)[
            'screen_name' => $homo->screen_name,
            'url'         => $homo->url,
            'display_url' => $this->createDisplayURL($homo->url),
            'secure'      => $this->isSecure($homo->url),
        ];

        if (isset($icon)) {
            $this->homo->icon = $icon;
        }
        if (isset($status)) {
            $this->status = $status;
        }
        if (isset($duration)) {
            $this->duration = $duration;
        }
    }

    protected function createDisplayURL(string $url): string
    {
        $domain = parse_url($url, PHP_URL_HOST);
        if (!is_string($domain)) {
            return '';
        }
        $path = (string)parse_url($url, PHP_URL_PATH);
        return (new Punycode)->decode($domain) . $path;
    }

    protected function isSecure(string $url): bool
    {
        return parse_url($url, PHP_URL_SCHEME) === 'https';
    }
}

<?php
namespace HomoChecker\Model;

use TrueBV\Punycode;

class Status
{
    public function __construct(HomoInterface $homo, string $icon = null, string $status = null, float $duration = null)
    {
        $this->homo = (object)[
            'screen_name' => $homo->screen_name,
            'url'         => $homo->url,
            'display_url' => $this->createDisplayURL($homo->url),
            'secure'      => $this->isSecure($homo->url),
        ];

        if (isset($icon)) {
            $this->homo->icon = $icon;
        }
        if (isset($status)) {
            $this->status = $status;
        }
        if (isset($duration)) {
            $this->duration = $duration;
        }
    }

    protected function createDisplayURL(string $url): string
    {
        $domain = parse_url($url, PHP_URL_HOST);
        if (!is_string($domain)) {
            return '';
        }
        $path = (string)parse_url($url, PHP_URL_PATH);
        return (new Punycode)->decode($domain) . $path;
    }

    protected function isSecure(string $url): bool
    {
        return strtolower(parse_url($url, PHP_URL_SCHEME)) === 'https';
    }
}

Fix a bug where scheme with uppercase is not handled


<?php
/**
 * Delete spam older than 30 days
 */

if(php_sapi_name() !== 'cli') {
	die('CLI only');
}

date_default_timezone_set('Europe/London');

require dirname(__FILE__) . '/../bootstrap.php';

$manager = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment');
$manager->filter("spam = 1")
		->filter("timestamp < DATE_SUB(NOW(), INTERVAL 30 DAY);");

$values = $manager->values();

if(!$values) {
	echo "Nothing to do.\n";
	return;
}

foreach($values as $record) {
	$id = $record->getId();

	// clean akismet log - this actually cascades but we can do it manually to be sure
	$akManager = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\AkismetLog', 'akismet_log');
	$akManager->filter("comment_id = %i", array($id));

	$akValues = $akManager->values();

	if($akValues) {
		foreach($akValues as $akRecord) {
			$akRecord->delete();
		}
	}

	$record->delete();
}

echo "All done.\n";

<?php
/**
 * Delete spam older than 30 days
 */

if(php_sapi_name() !== 'cli') {
	die('CLI only');
}

date_default_timezone_set('Europe/London');

require dirname(__FILE__) . '/../bootstrap.php';

$manager = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment');
$manager->filter("spam = 1")
		->filter("timestamp < DATE_SUB(NOW(), INTERVAL 30 DAY);");

$values = $manager->values();

if(!$values) {
	echo "Nothing to do.\n";
	return;
}

$app = App::getInstance();

foreach($values as $record) {
	$id = $record->getId();

	$app['db']->query("DELETE FROM akismet_log WHERE comment_id = ".$id);
	$app['db']->query("DELETE FROM comment WHERE id = ".$id);
}

echo "All done.\n";

Update the spam cleaner script as the delete() function no longer removes records from the DB (we want it to).


<!doctype html>

    <meta charset="utf-8">
    <title>Speedtests</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <link rel="icon" href="speedometer_transparent.png">
    <link rel="apple-touch-icon" href="speedometer.png">

    <link rel="stylesheet" href="vendor/morris/morris.css">
    <link rel="stylesheet" href="vendor/addtohomescreen/addtohomescreen.css">
    <link rel="stylesheet" href="main.css">

Remove language from HTML tag

Remove language from HTML tag


<?php

declare(strict_types=1);

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

/**
 * Class BadRequestController
 */
class BadRequestController extends AbstractController
{
    /**
     * This is the catch-all action for the api.
     * It sends a 404 and dies.
     */
    #[Route(
        '/api/{url}',
        requirements: [
            'url' => '(?!doc).+',
        ],
        defaults: [
            'url' => null,
        ],
        methods: ['GET'],
        priority: 2,
    )]
    public function indexAction()
    {
        throw $this->createNotFoundException();
    }
}

<?php

declare(strict_types=1);

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

/**
 * Class BadRequestController
 */
class BadRequestController extends AbstractController
{
    /**
     * This is the catch-all action for the api.
     * It sends a 404 and dies.
     */
    #[Route(
        '/api/{url}',
        requirements: [
            'url' => '(?!doc).+',
        ],
        defaults: [
            'url' => null,
        ],
        methods: ['GET'],
        priority: -1,
    )]
    public function indexAction()
    {
        throw $this->createNotFoundException();
    }
}

Fix priority on bad request route

Fix priority on bad request route

Higher put this at the top of the list, we want it last.


<?php namespace Felixkiss\SlugRoutes;

use Illuminate\Routing\Router;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class SlugRouter extends Router
{
    public function model($key, $class, Closure $callback = null)
    {
        return $this->bind($key, function($value) use ($class, $callback)
        {
            if (is_null($value)) return null;

            // For model binders, we will attempt to retrieve the model using the find
            // method on the model instance. If we cannot retrieve the models we'll
            // throw a not found exception otherwise we will return the instance.
            $model = new $class;

            if($model instanceof SluggableInterface)
            {
                $model = $model->where($model->getSlugIdentifier(), $value)->first();
            }
            else
            {
                $model = $model->find($value);
            }

            if ( ! is_null($model))
            {
                return $model;
            }

            // If a callback was supplied to the method we will call that to determine
            // what we should do when the model is not found. This just gives these
            // developer a little greater flexibility to decide what will happen.
            if ($callback instanceof Closure)
            {
                return call_user_func($callback);
            }

            throw new NotFoundHttpException;
        });
    }
}

<?php namespace Felixkiss\SlugRoutes;

use Illuminate\Routing\Router;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class SlugRouter extends Router
{
    public function model($key, $class, Closure $callback = null, $forceId = false)
    {
        return $this->bind($key, function($value) use ($class, $callback, $forceId)
        {
            if (is_null($value)) return null;

            // For model binders, we will attempt to retrieve the model using the find
            // method on the model instance. If we cannot retrieve the models we'll
            // throw a not found exception otherwise we will return the instance.
            $model = new $class;

            if($forceId === false && $model instanceof SluggableInterface)
            {
                $model = $model->where($model->getSlugIdentifier(), $value)->first();
            }
            else
            {
                $model = $model->find($value);
            }

            if ( ! is_null($model))
            {
                return $model;
            }

            // If a callback was supplied to the method we will call that to determine
            // what we should do when the model is not found. This just gives these
            // developer a little greater flexibility to decide what will happen.
            if ($callback instanceof Closure)
            {
                return call_user_func($callback);
            }

            throw new NotFoundHttpException;
        });
    }
}

Add parameter to Route::model() to force default behavior of using id

This is useful, if you generally want to bind with a slug (web interface)
but sometimes (e.g. API) want to use id.


<?php
namespace GraphQL\Executor;

use GraphQL\Error\Error;

class ExecutionResult implements \JsonSerializable
{
    /**
     * @var array
     */
    public $data;

    /**
     * @var Error[]
     */
    public $errors;

    /**
     * @var array[]
     */
    public $extensions;

    /**
     * @var callable
     */
    private $errorFormatter = ['GraphQL\Error\Error', 'formatError'];

    /**
     * @param array $data
     * @param array $errors
     * @param array $extensions
     */
    public function __construct(array $data = null, array $errors = [], array $extensions = [])
    {
        $this->data = $data;
        $this->errors = $errors;
        $this->extensions = $extensions;
    }

    /**
     * @param callable $errorFormatter
     * @return $this
     */
    public function setErrorFormatter(callable $errorFormatter)
    {
        $this->errorFormatter = $errorFormatter;
        return $this;
    }

    /**
     * @return array
     */
    public function toArray()
    {
        $result = [];

        if (null !== $this->data) {
            $result['data'] = $this->data;
        }

        if (!empty($this->errors)) {
            $result['errors'] = array_map($this->errorFormatter, $this->errors);
        }

        if (!empty($this->extensions)) {
            $result['extensions'] = (array) $this->extensions;
        }

        return $result;
    }

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

<?php
namespace GraphQL\Executor;

use GraphQL\Error\Error;

class ExecutionResult implements \JsonSerializable
{
    /**
     * @var array
     */
    public $data;

    /**
     * @var Error[]
     */
    public $errors;

    /**
     * @var array[]
     */
    public $extensions;

    /**
     * @var callable
     */
    private $errorFormatter = ['GraphQL\Error\Error', 'formatError'];

    /**
     * @param array $data
     * @param array $errors
     * @param array $extensions
     */
    public function __construct(array $data = null, array $errors = [], array $extensions = [])
    {
        $this->data = $data;
        $this->errors = $errors;
        $this->extensions = $extensions;
    }

    /**
     * @param callable $errorFormatter
     * @return $this
     */
    public function setErrorFormatter(callable $errorFormatter)
    {
        $this->errorFormatter = $errorFormatter;
        return $this;
    }

    /**
     * @return array
     */
    public function toArray()
    {
        $result = [];

        if (!empty($this->errors)) {
            $result['errors'] = array_map($this->errorFormatter, $this->errors);
        }

        if (null !== $this->data) {
            $result['data'] = $this->data;
        }

        if (!empty($this->extensions)) {
            $result['extensions'] = (array) $this->extensions;
        }

        return $result;
    }

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

Make 'errors' top property in response array


<?php
namespace NoughtsAndCrosses\Game;
use NoughtsAndCrosses\Game\Paper\Paper;
use NoughtsAndCrosses\Game\Pencil\Pencil;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * GameServiceProvider
 *
 * @package noughtsandcrosses
 */

 class GameServiceProvider implements ServiceProviderInterface
{
    public function register(Container $pimple)
    {
        $pimple['paper'] = function() {
            return new Paper();
        };

        $pimple['pencil'] = function() {
            return new Pencil();
        };
    }
}

<?php
namespace NoughtsAndCrosses\Game;
use NoughtsAndCrosses\Game\Paper\Paper;
use NoughtsAndCrosses\Game\Pencil\Pencil;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Service Provider for Game.
 *
 * @package noughtsandcrosses
 */

 class GameServiceProvider implements ServiceProviderInterface
{
    public function register(Container $pimple)
    {
        $pimple['paper'] = function() {
            return new Paper();
        };

        $pimple['pencil'] = function() {
            return new Pencil();
        };
    }
}

Edit "Service Provider for Game"

Edit "Service Provider for Game"


<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Auth\Facebook\Listener;

use Flarum\Event\ConfigureWebApp;
use Illuminate\Contracts\Events\Dispatcher;

class AddClientAssets
{
    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(ConfigureWebApp::class, [$this, 'addAssets']);
    }

    /**
     * @param ConfigureClientView $event
     */
    public function addAssets(ConfigureWebApp $event)
    {
        if ($event->isForum()) {
            $event->addAssets([
                __DIR__.'/../../js/forum/dist/extension.js',
                __DIR__.'/../../less/forum/extension.less'
            ]);
            $event->addBootstrapper('flarum/auth/facebook/main');
        }

        if ($event->isAdmin()) {
            $event->addAssets([
                __DIR__.'/../../js/admin/dist/extension.js'
            ]);
            $event->addBootstrapper('flarum/auth/facebook/main');
        }
    }
}

<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Flarum\Auth\Facebook\Listener;

use Flarum\Frontend\Event\Rendering;
use Illuminate\Contracts\Events\Dispatcher;

class AddClientAssets
{
    /**
     * @param Dispatcher $events
     */
    public function subscribe(Dispatcher $events)
    {
        $events->listen(Rendering::class, [$this, 'addAssets']);
    }

    /**
     * @param Rendering $event
     */
    public function addAssets(Rendering $event)
    {
        if ($event->isForum()) {
            $event->addAssets([
                __DIR__.'/../../js/forum/dist/extension.js',
                __DIR__.'/../../less/forum/extension.less'
            ]);
            $event->addBootstrapper('flarum/auth/facebook/main');
        }

        if ($event->isAdmin()) {
            $event->addAssets([
                __DIR__.'/../../js/admin/dist/extension.js'
            ]);
            $event->addBootstrapper('flarum/auth/facebook/main');
        }
    }
}

Update namespaces for beta 8

Update namespaces for beta 8

Refs flarum/core#1235.


<?php
class Kwc_Box_TitleEditable_Form extends Kwc_Abstract_Form
{
    protected function _initFields()
    {
        parent::_initFields();
        $this->add(new Kwf_Form_Field_TextField('title', trlKwf('Title')))
            ->setWidth(400)
            ->setHelpText(trlKwf('optional, if not set the title will be autogenerated from the sitename.'));
    }
}

<?php
class Kwc_Box_TitleEditable_Form extends Kwc_Abstract_Form
{
    protected function _initFields()
    {
        parent::_initFields();
        $this->add(new Kwf_Form_Field_TextField('title', trlKwf('Page Title')))
            ->setWidth(400)
            ->setHelpText(trlKwf('optional, if not set the title will be autogenerated from the sitename.'));
    }
}

Change form label to make more clear what title this is


<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Pagination Language Lines
	|--------------------------------------------------------------------------
	|
	| The following language lines are used by the paginator library to build
	| the simple pagination links. You are free to change them to anything
	| you want to customize your views to better match your application.
	|
	*/

	'previous' => '« Previous',

	'next'     => 'Next »',

);

<?php

return [

	/*
	|--------------------------------------------------------------------------
	| Pagination Language Lines
	|--------------------------------------------------------------------------
	|
	| The following language lines are used by the paginator library to build
	| the simple pagination links. You are free to change them to anything
	| you want to customize your views to better match your application.
	|
	*/

	'previous' => '« Previous',

	'next'     => 'Next »',

];

Convert language PHP 5.4 arrays.

Convert language PHP 5.4 arrays.


<?php
class Kwc_Basic_ImageEnlarge_EnlargeTag_ImagePage_Trl_ContentSender extends Kwf_Component_Abstract_ContentSender_Lightbox
{
    protected function _getOptions()
    {
        $dim = $this->_data->parent->getComponent()->getImageDimensions();
        $options = array(
            'width' => $dim['width'],
            'height' => $dim['height'],
            'style' => 'CenterBox' //TODO get from master
        );
        return $options;
    }
}

<?php
class Kwc_Basic_ImageEnlarge_EnlargeTag_ImagePage_Trl_ContentSender extends Kwf_Component_Abstract_ContentSender_Lightbox
{
    protected function _getOptions()
    {
        $dim = $this->_data->parent->getComponent()->getImageDimensions();
        $options = array(
            'width' => $dim['width'],
            'height' => $dim['height'],
            'style' => 'CenterBox' //TODO get from master
        );
        $options['lightboxUrl'] = $this->_data->url;
        return $options;
    }
}

Add lightboxUrl like in master

Add lightboxUrl like in master

Fixes ImageEnlarge in trl


<?php

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

/**
 * Class BaseUser.
 */
class BaseUser
{
    /**
     * @var int
     */
    private $id;

    /**
     * @var string
     */
    private $username;

    private $enabled;

    /**
     * BaseUser constructor.
     */
    public function __construct(int $id, string $username)
    {
        $this->id = $id;
        $this->username = $username;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    public function getUsername(): string
    {
        return $this->username;
    }

    public static function loadValidatorMetadata(ClassMetadata $metadata): void
    {
        $allowEmptyString = property_exists(Assert\Length::class, 'allowEmptyString') ? ['allowEmptyString' => true] : [];

        $metadata->addPropertyConstraint('username', new Assert\Length([
            'min' => 2,
            'max' => 120,
            'groups' => ['Registration'],
        ] + $allowEmptyString));
    }
}

<?php

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;

/**
 * Class BaseUser.
 */
class BaseUser
{
    /**
     * @var int
     */
    private $id;

    /**
     * @var string
     */
    private $username;

    private $enabled;

    /**
     * BaseUser constructor.
     */
    public function __construct(int $id, string $username)
    {
        $this->id = $id;
        $this->username = $username;
    }

    public function getId(): int
    {
        return $this->id;
    }

    public function getUsername(): string
    {
        return $this->username;
    }

    public static function loadValidatorMetadata(ClassMetadata $metadata): void
    {
        $allowEmptyString = property_exists(Assert\Length::class, 'allowEmptyString') ? ['allowEmptyString' => true] : [];

        $metadata->addPropertyConstraint('username', new Assert\Length([
            'min' => 2,
            'max' => 120,
            'groups' => ['Registration'],
        ] + $allowEmptyString));
    }
}

Add more return types after fixing a typo in my script


<?php
return function ($class) {
    static $map;

    if (!$map) {
        $map = include __DIR__ . '/autoload_classmap.php';
    }

    if (!isset($map[$class])) {
        return false;
    }
    return include $map[$class];
};

<?php
return function ($class) {
    static $map = null;

    if (!$map) {
        $map = include __DIR__ . '/autoload_classmap.php';
    }

    if (!isset($map[$class])) {
        return false;
    }
    return include $map[$class];
};

Fix to prevent SDK warning

Fix to prevent SDK warning


<?php

declare(strict_types=1);

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

class CreateTaggablesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(config('rinvex.taggable.tables.taggables'), function (Blueprint $table) {
            // Columns
            $table->integer('tag_id')->unsigned();
            $table->integer('taggable_id')->unsigned();
            $table->string('taggable_type');
            $table->timestamps();

            // Indexes
            $table->unique(['tag_id', 'taggable_id', 'taggable_type'], 'taggables_ids_type_unique');
            $table->foreign('tag_id')->references('id')->on(config('rinvex.taggable.tables.tags'))
                  ->onDelete('cascade')->onUpdate('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists(config('rinvex.taggable.tables.taggables'));
    }
}

<?php

declare(strict_types=1);

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

class CreateTaggablesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(config('rinvex.taggable.tables.taggables'), function (Blueprint $table) {
            // Columns
            $table->integer('tag_id')->unsigned();
            $table->morphs('taggable');
            $table->timestamps();

            // Indexes
            $table->unique(['tag_id', 'taggable_id', 'taggable_type'], 'taggables_ids_type_unique');
            $table->foreign('tag_id')->references('id')->on(config('rinvex.taggable.tables.tags'))
                  ->onDelete('cascade')->onUpdate('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists(config('rinvex.taggable.tables.taggables'));
    }
}

Enforce consistant morph table schema

Enforce consistant morph table schema


<?php

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

class CreateCtdailyqcTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('ctdailyqc', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('machine_id')->unsigned()->nullable();
            $table->date('qcdate')->nullable();
            $table->enum('scan_type', ['A', 'H'])->nullable();
            $table->float('water_hu', 4, 1)->nullable();
            $table->float('water_sd', 4, 1)->nullable();
            $table->boolean('artifacts')->nullable();
            $table->text('notes')->nullable();
            $table->index(['machine_id', 'id']);
            $table->index('qcdate');
            $table->softDeletes();
            $table->timestamps();
        });
    }

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

<?php

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

class CreateCtdailyqcTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('ctdailyqc', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('machine_id')->unsigned()->nullable();
            $table->date('qcdate')->nullable();
            $table->enum('scan_type', ['Axial', 'Helical'])->nullable();
            $table->float('water_hu', 4, 1)->nullable();
            $table->float('water_sd', 4, 1)->nullable();
            $table->enum('artifacts', ['Y', 'N'])->nullable();
            $table->text('notes')->nullable();
            $table->index(['machine_id', 'id']);
            $table->index('qcdate');
            $table->softDeletes();
            $table->timestamps();
        });
    }

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

Change scan_type and artifacts fields to enums


<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

<?php the_title(); ?>

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

			<?php the_excerpt(); ?>

	<?php else : ?>

			<?php the_content( __( 'Continue reading →', 'scaffold' ) ); ?>

	<?php endif; ?>

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

<?php the_title(); ?>

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

			<?php the_excerpt(); ?>
			<a href="<?php the_permalink(); ?>"><?php _e('Read more', 'scaffold') ?>

	<?php else : ?>

			<?php the_content( __( 'Continue reading →', 'scaffold' ) ); ?>

	<?php endif; ?>

Read more link on search

Read more link on search


<?php

$m = new Mustache_Engine([
  'loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/build/govuk_template/views/layouts', [
    'extension' => '.html',
  ]),
]);

$template = $m->loadTemplate('govuk_template');

echo $template->render([
  'pageTitle' => \Missing\String::get_output(function () { wp_title('|', true, 'right'); }),
  'assetPath' => get_template_directory_uri().'/build/govuk_template/assets/',
  'head' => \Missing\String::get_output('wp_head'),
  'bodyClasses' => \Missing\String::get_output('body_class'),
  'content' => \Missing\String::get_output(function () {
    ?>

          <?php include roots_template_path() ?>
          <?php if(!is_single() || !is_page()) { get_template_part('templates/paging'); } ?>

          <?php get_template_part('templates/sidebar') ?>

    <?php
  }),
  'bodyEnd' => \Missing\String::get_output('wp_footer'),
]);

<?php

$m = new Mustache_Engine([
  'loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/build/govuk_template/views/layouts', [
    'extension' => '.html',
  ]),
]);

$template = $m->loadTemplate('govuk_template');

echo $template->render([
  'pageTitle' => \Missing\String::get_output(function () { wp_title('|', true, 'right'); }),
  'assetPath' => get_template_directory_uri().'/build/govuk_template/assets/',
  'head' => \Missing\String::get_output('wp_head'),
  'bodyClasses' => \Missing\String::get_output('body_class'),
  'content' => \Missing\String::get_output(function () {
    ?>

      <?php do_action('get_header') ?>
      <?php get_template_part('templates/header') ?>
      <?php if (is_home()) : ?>
        <?php get_template_part('templates/featured') ?>
      <?php endif ?>

          <?php include roots_template_path() ?>
          <?php if(!is_single() || !is_page()) { get_template_part('templates/paging'); } ?>

          <?php get_template_part('templates/sidebar') ?>

    <?php
  }),
  'bodyEnd' => \Missing\String::get_output('wp_footer'),
]);

Add the header back in

Add the header back in


<?php

namespace CryptoMarketTest;

class ConfigDataExample
{
    const MONGODB_URI = 'mongodb://localhost';
    const MONGODB_DBNAME = 'coindata';

    const ACCOUNTS_CONFIG = array(
        'Btce' => array(
            'key' => '',
            'secret' => ''
        ),
        'Bitfinex'=> array(
            'key' => '',
            'secret' => ''
        ),
        'Bitstamp'=> array(
            'key' => '',
            'secret' => '',
            'custid' => ''
        ),
        'BitVC'=> array(
            'key' => '',
            'secret' => '',
        ),
//      'JPMChase' => array(
//          'name' => 'imapmailbox',
//          'username' => 'username',
//          'password' => 'password'
//      ),
        'Gdax'=> array(
            'key' => '',
            'secret' => '',
            'passphrase' =>''
        ),
        'Gemini'=> array(
            'key' => '',
            'secret' => ''
        ),
        'Kraken'=> array(
            'key' => '',
            'secret' => ''
        ),
        'Poloniex'=> array(
            'key' => '',
            'secret' => ''
        ),
        'Yunbi'=> array(
            'key' => '',
            'secret' => '',
        ),
    );
}

<?php

namespace CryptoMarketTest;

class ConfigDataExample
{
    const MONGODB_URI = 'mongodb://localhost';
    const MONGODB_DBNAME = 'coindata';

    const ACCOUNTS_CONFIG = array(
//        'Btce' => array(
//            'key' => '',
//            'secret' => ''
//        ),
        'Bitfinex'=> array(
            'key' => '',
            'secret' => ''
        ),
        'Bitstamp'=> array(
            'key' => '',
            'secret' => '',
            'custid' => ''
        ),
//        'BitVC'=> array(
//            'key' => '',
//            'secret' => '',
//        ),
//      'JPMChase' => array(
//          'name' => 'imapmailbox',
//          'username' => 'username',
//          'password' => 'password'
//      ),
        'Gdax'=> array(
            'key' => '',
            'secret' => '',
            'passphrase' =>''
        ),
        'Gemini'=> array(
            'key' => '',
            'secret' => ''
        ),
        'Kraken'=> array(
            'key' => '',
            'secret' => ''
        ),
        'Poloniex'=> array(
            'key' => '',
            'secret' => ''
        ),
//        'Yunbi'=> array(
//            'key' => '',
//            'secret' => '',
//        ),
    );
}

Remove defunct exchanges from example config


<?php

function movim_cache($key)
{
	$arglist = func_get_args();
	$key = $arglist[0];
	$content = $arglist[1];

	$user = new User();
	$login = $user->getLogin();

	if(!is_dir(BASE_PATH."/user/".$login."/cache"))
		mkdir(BASE_PATH."/user/".$login."/cache", 0766);

	if(func_num_args() == 1) {
		if(file_exists(BASE_PATH."/user/".$login."/cache/".$key)) {
			$content = unserialize(file_get_contents(BASE_PATH."/user/".$login."/cache/".$key));
		}

		if(isset($content) && $content != "")
			return $content;
		else
			return "";
	}

	if(func_num_args() == 2) {
        if(!file_put_contents(BASE_PATH."/user/".$login."/cache/".$key, serialize($content))) {
            throw new MovimException(sprintf(t("Couldn't set cache file %s"), $key));
        }
	}
}

<?php

function movim_cache($key)
{
	$arglist = func_get_args();
	$key = $arglist[0];
	$content = $arglist[1];

	$user = new User();
	$login = $user->getLogin();

	if(!is_dir(BASE_PATH."/user/".$login."/cache"))
		mkdir(BASE_PATH."/user/".$login."/cache", 0755);

	if(func_num_args() == 1) {
		if(file_exists(BASE_PATH."/user/".$login."/cache/".$key)) {
			$content = unserialize(file_get_contents(BASE_PATH."/user/".$login."/cache/".$key));
		}

		if(isset($content) && $content != "")
			return $content;
		else
			return "";
	}

	if(func_num_args() == 2) {
        if(!file_put_contents(BASE_PATH."/user/".$login."/cache/".$key, serialize($content))) {
            throw new MovimException(sprintf(t("Couldn't set cache file %s"), $key));
        }
	}
}

Change cache folders rights (766 -> 755)


<?php
namespace Payum\Core\Bridge\Symfony\Security;

use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\AbstractGenericTokenFactory;
use Payum\Core\Security\TokenInterface;
use Payum\Core\Storage\StorageInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class TokenFactory extends AbstractGenericTokenFactory
{
    /**
     * @var \Symfony\Component\Routing\RouterInterface
     */
    protected $urlGenerator;

    /**
     * @param UrlGeneratorInterface $urlGenerator
     * @param StorageInterface $tokenStorage
     * @param StorageRegistryInterface $storageRegistry
     * @param string $capturePath
     * @param string $notifyPath
     */
    public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath)
    {
        $this->urlGenerator = $urlGenerator;

        parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath);
    }

    /**
     * @param string $path
     * @param array $parameters
     *
     * @return string
     */
    protected function generateUrl($path, array $parameters = array())
    {
        return $this->urlGenerator->generate($path, $parameters, UrlGeneratorInterface::ABSOLUTE_URL);
    }
}

<?php
namespace Payum\Core\Bridge\Symfony\Security;

use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\AbstractGenericTokenFactory;
use Payum\Core\Storage\StorageInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class TokenFactory extends AbstractGenericTokenFactory
{
    /**
     * @var \Symfony\Component\Routing\RouterInterface
     */
    protected $urlGenerator;

    /**
     * @param UrlGeneratorInterface $urlGenerator
     * @param StorageInterface $tokenStorage
     * @param StorageRegistryInterface $storageRegistry
     * @param string $capturePath
     * @param string $notifyPath
     */
    public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath)
    {
        $this->urlGenerator = $urlGenerator;

        parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath);
    }

    /**
     * @param string $path
     * @param array $parameters
     *
     * @return string
     */
    protected function generateUrl($path, array $parameters = array())
    {
        return $this->urlGenerator->generate($path, $parameters, true);
    }
}

[security][symfony] Fix fatal error on old symfony versions.

PHP Fatal error:  Undefined class constant 'ABSOLUTE_URL' in ....


<?php

namespace App\Actions;

use App\Shell\Shell;
use Symfony\Component\Process\ExecutableFinder;

class CreateDatabase
{
    use LamboAction;

    protected $finder;
    protected $shell;

    public function __construct(Shell $shell, ExecutableFinder $finder)
    {
        $this->finder = $finder;
        $this->shell = $shell;
    }

    public function __invoke()
    {
        if (! (config('lambo.store.create_database') || config('lambo.store.full'))) {
            return;
        }

        $this->logStep('Creating database');

        if ($this->mysqlExists()) {
            $process = $this->shell->execInProject($this->command());
            $this->abortIf(! $process->isSuccessful(), "The new database was not created.", $process);
            $this->info('Created a new database ' . config('lambo.store.database_name'));
        }

        $this->warn("MySql does not seem to be installed. Skipping new database creation.");
    }

    protected function mysqlExists()
    {
        return $this->finder->find('mysql') !== null;
    }

    protected function command()
    {
        return sprintf(
            'mysql --user=%s --password=%s -e "CREATE DATABASE IF NOT EXISTS %s";',
            config('lambo.store.database_username'),
            config('lambo.store.database_password'),
            config('lambo.store.database_name')
        );
    }
}

<?php

namespace App\Actions;

use App\Shell\Shell;
use Symfony\Component\Process\ExecutableFinder;

class CreateDatabase
{
    use LamboAction;

    protected $finder;
    protected $shell;

    public function __construct(Shell $shell, ExecutableFinder $finder)
    {
        $this->finder = $finder;
        $this->shell = $shell;
    }

    public function __invoke()
    {
        if (! (config('lambo.store.create_database') || config('lambo.store.full'))) {
            return;
        }

        if (! $this->mysqlExists()) {
            $this->warn("MySql does not seem to be installed. Skipping new database creation.");
            return;
        }

        $this->logStep('Creating database');
        $process = $this->shell->execInProject($this->command());
        $this->abortIf(! $process->isSuccessful(), "The new database was not created.", $process);
        $this->info('Created a new database ' . config('lambo.store.database_name'));
    }

    protected function mysqlExists()
    {
        return $this->finder->find('mysql') !== null;
    }

    protected function command()
    {
        return sprintf(
            'mysql --user=%s --password=%s -e "CREATE DATABASE IF NOT EXISTS %s";',
            config('lambo.store.database_username'),
            config('lambo.store.database_password'),
            config('lambo.store.database_name')
        );
    }
}

Exit early if MySql is not present. Fixes MySql not installed message being displayed when database creation was successful.


<?php

class Denkmal_Form_Message extends CM_Form_Abstract {

    protected function _initialize() {
        $this->registerField(new Denkmal_FormField_VenueNearby(['name' => 'venue']));
        $this->registerField(new CM_FormField_Text(['name' => 'text']));
        $this->registerField(new CM_FormField_FileImage(['name' => 'image']));
        $this->registerField(new Denkmal_FormField_Tags(['name' => 'tags', 'cardinality' => 3]));

        $this->registerAction(new Denkmal_FormAction_Message_Create($this));
    }
}

<?php

class Denkmal_Form_Message extends CM_Form_Abstract {

    protected function _initialize() {
        $this->registerField(new Denkmal_FormField_VenueNearby(['name' => 'venue']));
        $this->registerField(new CM_FormField_Text(['name' => 'text', 'lengthMax' => 500]));
        $this->registerField(new CM_FormField_FileImage(['name' => 'image']));
        $this->registerField(new Denkmal_FormField_Tags(['name' => 'tags', 'cardinality' => 3]));

        $this->registerAction(new Denkmal_FormAction_Message_Create($this));
    }
}

Define max length for message text

Define max length for message text


<?php

use Hubzero\Content\Migration\Base;

// No direct access
defined('_HZEXEC_') or die();

/**
 * Migration script for adding offering_id to notes
 **/
class Migration20170815000001ComPublications extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		if (!$this->db->tableHasField('#__publications', 'featured'))
		{
			$query = "ALTER TABLE `#__publications` ADD `featured` TINYINT(1)  NOT NULL  DEFAULT '0';";
			$this->db->setQuery($query);
			$this->db->query();
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		if ($this->db->tableHasField('#__publications', 'featured'))
		{
			$query = "ALTER TABLE `#__publications` DROP `featured`;";
			$this->db->setQuery($query);
			$this->db->query();
		}
	}
}

[COM_PUBLICATIONS] Add a new line to a file to conform with tht formatting styles


<?php

/*
 * TODO add file header and class description
 */

namespace Goatherd\Phpcs;

use Composer\Package\PackageInterface;

use Composer\Installer\LibraryInstaller;

class Installer extends LibraryInstaller
{
    /**
     * {@inheritDoc}
     */
    public function getInstallPath(PackageInterface $package)
    {
        // fix package name to denote single directory
        $name = str_replace(array('/', '\\'), '-', $package->getPrettyName());
        return $this->vendorDir . 'squizlabs/php_codesniffer/CodeSniffer/Standards/' . $name;
    }

    /**
     * {@inheritDoc}
     */
    public function supports($packageType)
    {
        return 'phpcs-standard' === $packageType;
    }
}

<?php

/*
 * TODO add file header and class description
 */

namespace Goatherd\Phpcs;

use Composer\Package\PackageInterface;

use Composer\Installer\LibraryInstaller;

class Installer extends LibraryInstaller
{
    /**
     * {@inheritDoc}
     */
    public function getInstallPath(PackageInterface $package)
    {
        // fix package name to denote single directory
        $name = str_replace(array('/', '\\'), '-', $package->getPrettyName());
        return $this->vendorDir . '/squizlabs/php_codesniffer/CodeSniffer/Standards/' . $name;
    }

    /**
     * {@inheritDoc}
     */
    public function supports($packageType)
    {
        return 'phpcs-standard' === $packageType;
    }
}

Add missing slash to installPath.

Add missing slash to installPath.


<?php

namespace Tests\AppBundle\API;

use AppBundle\API\FlowerColor;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class FlowerColorTest extends KernelTestCase
{
    /**
     * @var \Doctrine\Bundle\DoctrineBundle\Registry
     */
    private $doctrine;
    private $flowerColor;

    /**
     * {@inheritDoc}
     */
    protected function setUp()
    {
        self::bootKernel();

        $this->doctrine = static::$kernel->getContainer()
            ->get('doctrine');

        $this->flowerColor = new FlowerColor($this->doctrine);
    }

    public function testDescription()
    {
        $desc = $this->flowerColor->getDesc();
        $this->assertEquals($desc['description']['en'], 'Assign flower colors to plants.');
        $this->assertEquals($desc['label']['en'], 'Flower Color');
        $this->assertEquals($desc['icon'], 'https://wikidatagame.iimog.org/assets/img/marguerite-1154604_960_720.jpg');
    }
}

<?php

namespace Tests\AppBundle\API;

use AppBundle\API\FlowerColor;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class FlowerColorTest extends KernelTestCase
{
    /**
     * @var \Doctrine\Bundle\DoctrineBundle\Registry
     */
    private $doctrine;
    private $flowerColor;

    /**
     * {@inheritDoc}
     */
    protected function setUp()
    {
        self::bootKernel();

        $this->doctrine = static::$kernel->getContainer()
            ->get('doctrine');

        $this->flowerColor = new FlowerColor($this->doctrine);
    }

    public function testDescription()
    {
        $desc = $this->flowerColor->getDesc();
        $this->assertEquals($desc['description']['en'], 'Assign flower colors to plants.');
        $this->assertEquals($desc['label']['en'], 'Flower Color');
        $this->assertEquals($desc['icon'], 'https://wikidatagame.iimog.org/assets/img/marguerite-1154604_960_720.jpg');
    }

    public function testTiles()
    {
        $tiles = $this->flowerColor->getTiles(5);
        $this->assertEquals(count($tiles), 5);
    }
}

Add test for tiles (correct number)

Add test for tiles (correct number)


<?php
class Kwc_Abstract_Composite_Cc_Component extends Kwc_Chained_Cc_Component
{
    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        foreach ($this->getData()->getChildComponents(array('generator' => 'child')) as $c) {
            if ($ret[$c->id]) $ret[$c->id] = $c; // Bei TextImage kann zB. Bild ausgeblendet werden und soll dann in Übersetzung auch nicht angezeigt werden
        }
        return $ret;
    }

    public function hasContent()
    {
        foreach ($this->getData()->getChildComponents(array('generator' => 'child')) as $c) {
            if ($c->hasContent()) return true;
        }
        return false;
    }
}

<?php
class Kwc_Abstract_Composite_Cc_Component extends Kwc_Chained_Cc_Component
{
    public function getTemplateVars(Kwf_Component_Renderer_Abstract $renderer = null)
    {
        $ret = parent::getTemplateVars($renderer);
        foreach ($this->getData()->getChildComponents(array('generator' => 'child')) as $c) {
            if ($ret[$c->id]) $ret[$c->id] = $c; // Bei TextImage kann zB. Bild ausgeblendet werden und soll dann in Übersetzung auch nicht angezeigt werden
        }
        return $ret;
    }

    public function hasContent()
    {
        foreach ($this->getData()->getChildComponents(array('generator' => 'child')) as $c) {
            if ($c->hasContent()) return true;
        }
        return false;
    }
}

Add renderer for Composite_Cc getTemplateVars

fixes Cc html component (which needs renderer)


<?php
require '../src/Curl/Curl.php';

use \Curl\Curl;

define('GITTIP_USERNAME', 'XXXXXXXXXX');
define('GITTIP_API_KEY', 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX');

$data = array(
    array(
        'username' => 'user' . mt_rand(),
        'platform' => 'gittip',
        'amount' =>  '0.02',
    ),
    array(
        'username' => 'user' . mt_rand(),
        'platform' => 'gittip',
        'amount' =>  '0.02',
    ),
);

$curl = new Curl();
$curl->setHeader('Content-Type', 'application/json');
$curl->setBasicAuthentication(GITTIP_API_KEY);
$curl->post('https://www.gittip.com/' . GITTIP_USERNAME . '/tips.json', json_encode($data));

foreach ($curl->response as $tip) {
    echo $tip->amount . ' given to ' . $tip->username . '.' . "\n";
}

<?php
require '../src/Curl/Curl.php';

use \Curl\Curl;

define('GRATIPAY_USERNAME', 'XXXXXXXXXX');
define('GRATIPAY_API_KEY', 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX');

$data = array(
    array(
        'username' => 'user' . mt_rand(),
        'platform' => 'gittip',
        'amount' =>  '0.02',
    ),
    array(
        'username' => 'user' . mt_rand(),
        'platform' => 'gittip',
        'amount' =>  '0.02',
    ),
);

$curl = new Curl();
$curl->setHeader('Content-Type', 'application/json');
$curl->setBasicAuthentication(GRATIPAY_API_KEY);
$curl->post('https://www.gittip.com/' . GRATIPAY_USERNAME . '/tips.json', json_encode($data));

foreach ($curl->response as $tip) {
    echo $tip->amount . ' given to ' . $tip->username . '.' . "\n";
}

Rename variables from Gittip to Gratipay


        <?php foreach ($details as $key => $detail): ?>
        <?php if (in_array($detail_action_mode, array('add', 'update')) && $key == $detail_key): ?>
        <?php include_partial('detailItemForm', array('detail' => $detail, 'key' => $key, 'onglets' => $onglets, 'form' => $form, 'is_new' => ($detail_action_mode == 'add'))) ?>
        <?php else: ?>
        <?php
                    include_partial('detailItem', array('detail' => $detail,
                        'key' => $key,
                        'onglets' => $onglets,
                        'acheteurs' => $acheteurs,
                        'has_acheteurs_mout' => $has_acheteurs_mout)) ?>
        <?php endif; ?>
<?php endforeach; ?>
<?php if (!$onglets->getCurrentCepage()->getConfig()->hasOnlyOneDetail() && $detail_action_mode != 'add') :?>
        <a href="<?php echo url_for($onglets->getUrl('recolte_add')->getRawValue()) ?>" id="ajout_col" class="">
<?php endif; ?>

        <?php foreach ($details as $key => $detail): ?>
        <?php if (in_array($detail_action_mode, array('add', 'update')) && $key == $detail_key): ?>
        <?php include_partial('detailItemForm', array('detail' => $detail, 'key' => $key, 'onglets' => $onglets, 'form' => $form, 'is_new' => ($detail_action_mode == 'add'))) ?>
        <?php else: ?>
        <?php
                    include_partial('detailItem', array('detail' => $detail,
                        'key' => $key,
                        'onglets' => $onglets,
                        'acheteurs' => $acheteurs,
                        'has_acheteurs_mout' => $has_acheteurs_mout)) ?>
        <?php endif; ?>
<?php endforeach; ?>
<?php if (! $onglets->getCurrentCepage()->getConfig()->hasOnlyOneDetail() || !count($details) ) :?>
        <a href="<?php echo url_for($onglets->getUrl('recolte_add')->getRawValue()) ?>" id="ajout_col" class="">
<?php endif; ?>

Revert "Rebug sur le bouton ajouter quand on est en mode ajout le bouton n'est pas affiché"

This reverts commit 039afa977340c9ae0342dd5cf9b03114768a3db1.


<?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\CoreBundle\Listener;

use Sylius\Bundle\CoreBundle\Processor\CatalogPromotionClearerInterface;
use Sylius\Bundle\CoreBundle\Processor\CatalogPromotionProcessorInterface;
use Sylius\Component\Promotion\Event\CatalogPromotionConfigurationRemoved;
use Sylius\Component\Resource\Repository\RepositoryInterface;

final class CatalogPromotionConfigurationRemovedListener
{
    private CatalogPromotionClearerInterface $catalogPromotionClearer;

    private CatalogPromotionProcessorInterface $catalogPromotionProcessor;

    private RepositoryInterface $catalogPromotionRepository;

    public function __construct(
        CatalogPromotionClearerInterface $catalogPromotionClearer,
        CatalogPromotionProcessorInterface $catalogPromotionProcessor,
        RepositoryInterface $catalogPromotionRepository
    ) {
        $this->catalogPromotionClearer = $catalogPromotionClearer;
        $this->catalogPromotionProcessor = $catalogPromotionProcessor;
        $this->catalogPromotionRepository = $catalogPromotionRepository;
    }

    public function __invoke(CatalogPromotionConfigurationRemoved $event): void
    {
        $this->catalogPromotionClearer->clear();

        foreach ($this->catalogPromotionRepository->findAll() as $catalogPromotion) {
            $this->catalogPromotionProcessor->process($catalogPromotion);
        }
    }
}

<?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\CoreBundle\Listener;

use Sylius\Bundle\CoreBundle\Processor\CatalogPromotionClearerInterface;
use Sylius\Component\Promotion\Event\CatalogPromotionConfigurationRemoved;

final class CatalogPromotionConfigurationRemovedListener
{
    private CatalogPromotionClearerInterface $catalogPromotionClearer;

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

    public function __invoke(CatalogPromotionConfigurationRemoved $event): void
    {
        $this->catalogPromotionClearer->clear();
    }
}

Remove apply from removing listener

Remove apply from removing listener


<?php

namespace WP_CLI;

/**
 * A Upgrader Skin for WordPress that only generates plain-text
 *
 * @package wp-cli
 */
class UpgraderSkin extends \WP_Upgrader_Skin {

	public $api;

	function header() {}
	function footer() {}
	function bulk_header() {}
	function bulk_footer() {}

	function error( $error ) {
		if ( !$error )
			return;

		if ( is_string( $error ) && isset( $this->upgrader->strings[ $error ] ) )
			$error = $this->upgrader->strings[ $error ];

		// TODO: show all errors, not just the first one
		\WP_CLI::warning( $error );
	}

	function feedback( $string ) {
		if ( isset( $this->upgrader->strings[$string] ) )
			$string = $this->upgrader->strings[$string];

		if ( strpos($string, '%') !== false ) {
			$args = func_get_args();
			$args = array_splice($args, 1);
			if ( !empty($args) )
				$string = vsprintf($string, $args);
		}

		if ( empty($string) )
			return;

		$string = str_replace( '…', '...', strip_tags( $string ) );

		\WP_CLI::log( $string );
	}
}

<?php

namespace WP_CLI;

/**
 * A Upgrader Skin for WordPress that only generates plain-text
 *
 * @package wp-cli
 */
class UpgraderSkin extends \WP_Upgrader_Skin {

	public $api;

	function header() {}
	function footer() {}
	function bulk_header() {}
	function bulk_footer() {}

	function error( $error ) {
		if ( !$error )
			return;

		if ( is_string( $error ) && isset( $this->upgrader->strings[ $error ] ) )
			$error = $this->upgrader->strings[ $error ];

		// TODO: show all errors, not just the first one
		\WP_CLI::warning( $error );
	}

	function feedback( $string ) {
		if ( isset( $this->upgrader->strings[$string] ) )
			$string = $this->upgrader->strings[$string];

		if ( strpos($string, '%') !== false ) {
			$args = func_get_args();
			$args = array_splice($args, 1);
			if ( !empty($args) )
				$string = vsprintf($string, $args);
		}

		if ( empty($string) )
			return;

		$string = str_replace( '…', '...', strip_tags( $string ) );
		$string = html_entity_decode( $string, ENT_QUOTES, get_bloginfo( 'charset' ) );

		\WP_CLI::log( $string );
	}
}

Use `html_entity_decode()` for decoding entities in upgrader strings.


<?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\Component\Order\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

interface OrderRepositoryInterface extends RepositoryInterface
{
    public function countPlacedOrders(): int;

    /**
     * @return array|OrderInterface[]
     */
    public function findLatest(int $count): array;

    public function findLatestCart(): ?OrderInterface;

    public function findOneByNumber(string $number): ?OrderInterface;

    public function findOneByTokenValue(string $tokenValue): ?OrderInterface;

    public function findCartById($id): ?OrderInterface;

    /**
     * @return array|OrderInterface[]
     */
    public function findCartsNotModifiedSince(\DateTimeInterface $terminalDate): array;

    public function createCartQueryBuilder(): QueryBuilder;
}

<?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\Component\Order\Repository;

use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

interface OrderRepositoryInterface extends RepositoryInterface
{
    public function countPlacedOrders(): int;

    /**
     * @return array|OrderInterface[]
     */
    public function findLatest(int $count): array;

    public function findLatestCart(): ?OrderInterface;

    public function findOneByNumber(string $number): ?OrderInterface;

    public function findOneByTokenValue(string $tokenValue): ?OrderInterface;

    public function findCartByTokenValue(string $tokenValue): ?OrderInterface;

    public function findCartById($id): ?OrderInterface;

    /**
     * @return array|OrderInterface[]
     */
    public function findCartsNotModifiedSince(\DateTimeInterface $terminalDate): array;

    public function createCartQueryBuilder(): QueryBuilder;
}

Add token value based cart context

[API][Cart] Add token value based cart context


<a class="brand" href="<?= esc_url(home_url('/')); ?>"><svg class="icon icon-logo"><use xlink:href="#icon-logo"/></svg><?php bloginfo('name'); ?> — Design for a changing world.

      <?php
      if (has_nav_menu('primary_navigation')) :
        wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav']);
      endif;
      ?>

        Collection<svg class="icon icon-collection"><use xlink:href="#icon-collection"></svg>
        Search<svg class="icon icon-search"><use xlink:href="#icon-search"></svg>

  <?php global $collection; $collection = \Firebelly\Collections\get_active_collection(); ?>
  <section class="collection mini" data-id="<?= $collection->ID ?>">
    <?php include(locate_template('templates/collection.php')); ?>

<a class="brand" href="<?= esc_url(home_url('/')); ?>"><svg class="icon icon-logo"><use xlink:href="#icon-logo"/></svg><?php bloginfo('name'); ?> — <?php echo get_bloginfo ( 'description' ); ?>

      <?php
      if (has_nav_menu('primary_navigation')) :
        wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav']);
      endif;
      ?>

        Collection<svg class="icon icon-collection"><use xlink:href="#icon-collection"></svg>
        Search<svg class="icon icon-search"><use xlink:href="#icon-search"></svg>

  <?php global $collection; $collection = \Firebelly\Collections\get_active_collection(); ?>
  <section class="collection mini" data-id="<?= $collection->ID ?>">
    <?php include(locate_template('templates/collection.php')); ?>

Set site tagline variable to display next to the logo


<?php

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

class CreateBusinessesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('businesses', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('category_id')->unsigned();
            $table->foreign('category_id')->references('id')->on('categories');
            $table->string('slug')->unique();
            $table->string('name');
            $table->string('description');
            $table->string('postal_address')->nullable();
            $table->string('phone')->nullable();
            $table->string('social_facebook')->nullable();
            $table->string('timezone');
            $table->enum('strategy', ['dateslot', 'timeslot'])->default('timeslot'); /* Appointment Booking Strategy */
            $table->softDeletes();
            $table->timestamps();
        });
    }

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

}

<?php

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

class CreateBusinessesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('businesses', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('category_id')->unsigned();
            $table->foreign('category_id')->references('id')->on('categories');
            $table->string('slug')->unique();
            $table->string('name');
            $table->string('description');
            $table->string('postal_address')->nullable();
            $table->string('phone')->nullable();
            $table->string('social_facebook')->nullable();
            $table->string('timezone');
            $table->string('strategy', 15)->default('timeslot'); /* Appointment Booking Strategy */
            $table->softDeletes();
            $table->timestamps();
        });
    }

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

}

Remove enum to gain flexibility

Remove enum to gain flexibility


<?php namespace Way\Generators\Commands;

use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class ModelGeneratorCommand extends GeneratorCommand {

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a model';

    /**
     * The path where the file will be created
     *
     * @return mixed
     */
    protected function getFileGenerationPath()
    {
        $path = $this->getPathByOptionOrConfig('path', 'model_target_path');

        return $path. '/' . ucwords($this->argument('modelName')) . '.php';
    }

    /**
     * Fetch the template data
     *
     * @return array
     */
    protected function getTemplateData()
    {
        return [
            'NAME' => ucwords($this->argument('modelName'))
        ];
    }

    /**
     * Get path to the template for the generator
     *
     * @return mixed
     */
    protected function getTemplatePath()
    {
        return $this->getPathByOptionOrConfig('templatePath', 'model_template_path');
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['modelName', InputArgument::REQUIRED, 'The name of the desired Eloquent model']
        ];
    }

}

<?php namespace Way\Generators\Commands;

use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class ModelGeneratorCommand extends GeneratorCommand {

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a model';

    /**
     * The path where the file will be created
     *
     * @return mixed
     */
    protected function getFileGenerationPath()
    {
        $path = $this->getPathByOptionOrConfig('path', 'model_target_path');

        return $path. '/' . ucwords($this->argument('modelName')) . '.php';
    }

    /**
     * Fetch the template data
     *
     * @return array
     */
    protected function getTemplateData()
    {
        return [
            'NAME' => ucwords($this->argument('modelName')),
            'NAMESPACE' => $this->getNamespace('root')
        ];
    }

    /**
     * Get path to the template for the generator
     *
     * @return mixed
     */
    protected function getTemplatePath()
    {
        return $this->getPathByOptionOrConfig('templatePath', 'model_template_path');
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['modelName', InputArgument::REQUIRED, 'The name of the desired Eloquent model']
        ];
    }

}

Add template var for model generation

Add template var for model generation


<?php

$lines = array();
foreach($report->logs as $entry) {
    $date = Utilities::formatDate($entry->created);

    $lid = 'report_';
    if($report->target_type == 'Recipient')
        $lid .= 'recipient_';

    if($entry->author_type == 'Guest')
        $lid .= 'guest_';

    $lid .= 'event_'.$entry->event;

    $action = Lang::tr($lid)->r(
        array(
            'author' => $entry->author,
            'log' => $entry
        ),
        $entry->target
    );

    $lines[] = array('date' => $date, 'action' => $action);
}

// Find longest date to compute first column width
$dw = max(array_map(function($line) {
    return strlen($line['date']);
}, $lines));

foreach($lines as $line) {
    echo $line['date'].str_repeat(' ', $dw - strlen($line['date'])).' : ';

    echo chunk_split($line['action'], 76, GlobalConstants::NEW_LINE.str_repeat(' ', $dw + 3));
}

<?php

$lines = array();
foreach($report->logs as $entry) {
    $date = Utilities::formatDate($entry->created);

    $lid = 'report_';
    if($report->target_type == 'Recipient')
        $lid .= 'recipient_';

    if($entry->author_type == 'Guest')
        $lid .= 'guest_';

    $lid .= 'event_'.$entry->event;

    $action = Lang::tr($lid)->r(
        array(
            'event' => $entry->event,
            'date' => $entry->created,
            'time_taken' => $entry->time_taken,
            'author' => $entry->author,
            'log' => $entry
        ),
        $entry->target
    );

    $lines[] = array('date' => $date, 'action' => $action);
}

// Find longest date to compute first column width
$dw = max(array_map(function($line) {
    return strlen($line['date']);
}, $lines));

foreach($lines as $line) {
    echo $line['date'].str_repeat(' ', $dw - strlen($line['date'])).' : ';

    echo chunk_split($line['action'], 76, GlobalConstants::NEW_LINE.str_repeat(' ', $dw + 3));
}

Add data available to report template

Add data available to report template

git-svn-id: 28fe03dfd74dd77dcc8ecfe99fabcec8eed81bba@3509 8555b757-d854-4b86-925a-82fd84c90ff4


<?php

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

class CreateTriosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('trios', function (Blueprint $table) {
            $table->increments('id');
            $table->string('sentence1');
            $table->string('sentence2');
            $table->string('sentence3');
            $table->string('explanation1');
            $table->string('explanation2');
            $table->string('explanation3');
            $table->string('answer');
            $table->timestamps();
        });
    }

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

<?php

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

class CreateTriosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('trios', function (Blueprint $table) {
            $table->increments('id');
            $table->primary('id');
            $table->string('sentence1');
            $table->string('sentence2');
            $table->string('sentence3');
            $table->string('explanation1');
            $table->string('explanation2');
            $table->string('explanation3');
            $table->string('answer');
            $table->timestamps();
        });
    }

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

Add primary key in id column in trios table.


<?php

namespace Oro\Bundle\EntityMergeBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

use Oro\Bundle\EntityMergeBundle\Data\EntityData;
use Oro\Bundle\EntityMergeBundle\Exception\InvalidArgumentException;

class SourceEntityValidator extends DoctrineHelperValidator
{
    /**
     * {@inheritdoc}
     */
    public function validate($value, Constraint $constraint)
    {
        if (!$value instanceof EntityData) {
            throw new InvalidArgumentException(
                sprintf(
                    'Oro\Bundle\EntityMergeBundle\Data\EntityData supported only, %s given',
                    is_object($value) ? get_class($value) : gettype($value)
                )
            );
        }

        /* @var EntityData $value */
        $entities = $value->getEntities();
        $fields = $value->getFields();

        foreach ($fields as $field) {
            $sourceEntity = $field->getSourceEntity();
            foreach ($entities as $entity) {
                if ($this->doctrineHelper->isEntityEqual($entity, $sourceEntity)) {
                    break 2;
                }
            }

            $this->context->addViolation(
                /* @var SourceEntity $constraint */
                $constraint->message,
                ['{{ limit }}' => $field->getFieldName()]
            );
        }
    }
}

<?php

namespace Oro\Bundle\EntityMergeBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

use Oro\Bundle\EntityMergeBundle\Data\EntityData;
use Oro\Bundle\EntityMergeBundle\Exception\InvalidArgumentException;

class SourceEntityValidator extends DoctrineHelperValidator
{
    /**
     * {@inheritdoc}
     */
    public function validate($value, Constraint $constraint)
    {
        if (!$value instanceof EntityData) {
            throw new InvalidArgumentException(
                sprintf(
                    'Oro\Bundle\EntityMergeBundle\Data\EntityData supported only, %s given',
                    is_object($value) ? get_class($value) : gettype($value)
                )
            );
        }

        /* @var EntityData $value */
        $entities = $value->getEntities();
        $fields = $value->getFields();

        foreach ($fields as $field) {
            $sourceEntity = $field->getSourceEntity();
            if (!is_object($sourceEntity)) {
                continue;
            }
            foreach ($entities as $entity) {
                if ($this->doctrineHelper->isEntityEqual($entity, $sourceEntity)) {
                    break 2;
                }
            }

            $this->context->addViolation(
                /* @var SourceEntity $constraint */
                $constraint->message,
                ['{{ limit }}' => $field->getFieldName()]
            );
        }
    }
}

ISDOT-98: Configure Campaign entity merge option&mass action for grid


<?php

namespace Civi\Api4\Service\Spec\Provider;

use Civi\Api4\Service\Spec\FieldSpec;
use Civi\Api4\Service\Spec\RequestSpec;

class NoteCreationSpecProvider implements SpecProviderInterface {

  /**
   * @param RequestSpec $spec
   */
  public function modifySpec(RequestSpec $spec) {
    $spec->getFieldByName('note')->setRequired(TRUE);
  }

  /**
   * @param string $entity
   * @param string $action
   *
   * @return bool
   */
  public function applies($entity, $action) {
    return $entity === 'Note' && $action === 'create';
  }

}

<?php

namespace Civi\Api4\Service\Spec\Provider;

use Civi\Api4\Service\Spec\RequestSpec;

class NoteCreationSpecProvider implements SpecProviderInterface {

  /**
   * @param RequestSpec $spec
   */
  public function modifySpec(RequestSpec $spec) {
    $spec->getFieldByName('note')->setRequired(TRUE);
    $spec->getFieldByName('entity_table')->setDefaultValue('civicrm_contact');
  }

  /**
   * @param string $entity
   * @param string $action
   *
   * @return bool
   */
  public function applies($entity, $action) {
    return $entity === 'Note' && $action === 'create';
  }

}

Set default value for note entity

Set default value for note entity


<?php

namespace AdminBundle\Controller;

use DemandeSubventionBundle\Entity\Demandessubvention;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\VarDumper\VarDumper;

class DefaultController extends Controller
{
    public function indexAction()
    {
        if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN'))
        {
//      Get Association
            $associations = $this->getDoctrine()
                ->getRepository('AssociationBundle:Associations')
                ->findAll();

            $demandessubvention = array(); //Array of Demande de Subvention

            foreach($associations as $assoc) {
//            Get Demande Subvention
                $demandessubvention = $this->getDoctrine()
                    ->getRepository('DemandeSubventionBundle:Demandessubvention')
                    ->findBy(array('associationsNumassoc' => $assoc));
            };

            // redirect authenticated users to homepage
            return $this->render('AdminBundle:Default:index.html.twig',array('associations' => $associations, 'demandessubvention' => $demandessubvention));
        }
        else if ($this->get('security.authorization_checker')->isGranted('ROLE_USER')) {

            // redirect authenticated admin to homepage
            return $this->redirectToRoute('AssociationBundle_homepage');
        } else {
            return $this->redirectToRoute('UserBundle_login');
        }
    }
}

<?php

namespace AdminBundle\Controller;

use DemandeSubventionBundle\Entity\Demandessubvention;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\VarDumper\VarDumper;

class DefaultController extends Controller
{
    public function indexAction()
    {
        if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN'))
        {
//      Get Association
            $associations = $this->getDoctrine()
                ->getRepository('AssociationBundle:Associations')
                ->findAll();

            $demandessubvention = array(); //Array of Demande de Subvention

            $demandessubvention = $this->getDoctrine()
                    ->getRepository('DemandeSubventionBundle:Demandessubvention')
                    ->findAll();

            // redirect authenticated users to homepage
            return $this->render('AdminBundle:Default:index.html.twig',array('associations' => $associations, 'demandessubvention' => $demandessubvention));
        }
        else if ($this->get('security.authorization_checker')->isGranted('ROLE_USER')) {

            // redirect authenticated admin to homepage
            return $this->redirectToRoute('AssociationBundle_homepage');
        } else {
            return $this->redirectToRoute('UserBundle_login');
        }
    }
}

Fix a little last bug.

Fix a little last bug.


<?php declare(strict_types=1);

namespace hollodotme\Readis\Application\ReadModel\Constants;

abstract class KeyType
{
	public const HASH   = 'hash';

	public const LIST   = 'list';

	public const SET    = 'set';

	public const STRING = 'string';
}

<?php declare(strict_types=1);

namespace hollodotme\Readis\Application\ReadModel\Constants;

abstract class KeyType
{
	public const HASH       = 'hash';

	public const LIST       = 'list';

	public const SET        = 'set';

	public const SORTED_SET = 'zset';

	public const STRING     = 'string';
}

Add sorted set to key types

Add sorted set to key types


<?php

namespace Bugsnag\BugsnagBundle\DependencyInjection;

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

class BugsnagExtension extends Extension
{
    /**
     * Loads a specific configuration.
     *
     * @param array            $configs
     * @param ContainerBuilder $container
     *
     * @return void
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $config = $this->processConfiguration(new Configuration(), $configs);

        $loader = new YamlFileLoader(
            $container,
            new FileLocator(__DIR__.'/../Resources/config')
        );

        $loader->load('services.yml');

        foreach ($config as $key => $value) {
            $container->setParameter("bugsnag.{$key}", $value);
        }

        if ($container->hasParameter('kernel.project_dir')) {
            $symfonyRoot = $container->getParameter('kernel.project_dir');
        } else {
            $symfonyRoot = realpath(
                $container->getParameter('kernel.root_dir').'/../'
            );
        }

        $container->setParameter('bugsnag.symfony_root', $symfonyRoot);
    }
}

<?php

namespace Bugsnag\BugsnagBundle\DependencyInjection;

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

class BugsnagExtension extends Extension
{
    /**
     * Loads a specific configuration.
     *
     * @param array            $configs
     * @param ContainerBuilder $container
     *
     * @return void
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $config = $this->processConfiguration(new Configuration(), $configs);

        $loader = new YamlFileLoader(
            $container,
            new FileLocator(__DIR__.'/../Resources/config')
        );

        $loader->load('services.yml');

        foreach ($config as $key => $value) {
            $container->setParameter("bugsnag.{$key}", $value);
        }

        if ($container->hasParameter('kernel.project_dir')) {
            $symfonyRoot = $container->getParameter('kernel.project_dir');
        } else {
            $symfonyRoot = realpath(
                $container->getParameter('kernel.root_dir').'/..'
            );
        }

        $container->setParameter('bugsnag.symfony_root', $symfonyRoot);
    }
}

Remove trailing slash from realpath call

realpath returns paths without trailing slashes. This change makes
that clearer in the call


<?php

namespace Madewithlove\Tactician;

use League\Tactician\CommandBus;
use League\Tactician\Handler\CommandHandlerMiddleware;
use League\Tactician\Handler\CommandNameExtractor\ClassNameExtractor;
use League\Tactician\Handler\MethodNameInflector\HandleInflector;

class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(CommandBus::class, function () {
            $middlewares = [];

            $middlewares[] = new CommandHandlerMiddleware(
                new ClassNameExtractor(),
                new ContainerLocator($this->app),
                new HandleInflector()
            );

            return new CommandBus($middlewares);
        });

        $this->app->alias(CommandBus::class, 'bus');
    }

    /**
     * @return array
     */
    public function provides()
    {
        return [
            CommandBus::class,
            'bus',
        ];
    }
}

<?php

namespace Madewithlove\Tactician;

use League\Tactician\CommandBus;
use League\Tactician\Handler\CommandHandlerMiddleware;
use League\Tactician\Handler\CommandNameExtractor\ClassNameExtractor;
use League\Tactician\Handler\MethodNameInflector\HandleInflector;
use League\Tactician\Plugins\LockingMiddleware;

class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(CommandBus::class, function () {
            $middlewares = [];

            $middlewares[] = new LockingMiddleware();
            $middlewares[] = new CommandHandlerMiddleware(
                new ClassNameExtractor(),
                new ContainerLocator($this->app),
                new HandleInflector()
            );

            return new CommandBus($middlewares);
        });

        $this->app->alias(CommandBus::class, 'bus');
    }

    /**
     * @return array
     */
    public function provides()
    {
        return [
            CommandBus::class,
            'bus',
        ];
    }
}

Add locking middleware as default

Add locking middleware as default