<?php

namespace Oro\Bundle\NotificationBundle;

use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Oro\Bundle\NotificationBundle\DependencyInjection\Compiler\EventsCompilerPass;
use Oro\Bundle\NotificationBundle\DependencyInjection\Compiler\NotificationHandlerPass;

class OroNotificationBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new NotificationHandlerPass());
        $container->addCompilerPass(new EventsCompilerPass(), PassConfig::TYPE_AFTER_REMOVING);
    }
}

<?php

namespace Oro\Bundle\NotificationBundle;

use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Oro\Bundle\MessageQueueBundle\DependencyInjection\Compiler\AddTopicMetaPass;
use Oro\Bundle\NotificationBundle\Async\Topics;
use Oro\Bundle\NotificationBundle\DependencyInjection\Compiler\EventsCompilerPass;
use Oro\Bundle\NotificationBundle\DependencyInjection\Compiler\NotificationHandlerPass;

class OroNotificationBundle extends Bundle
{
    /**
     * {@inheritdoc}
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new NotificationHandlerPass());
        $container->addCompilerPass(new EventsCompilerPass(), PassConfig::TYPE_AFTER_REMOVING);

        $addTopicPass = AddTopicMetaPass::create()
            ->add(Topics::SEND_NOTIFICATION_EMAIL)
        ;
        $container->addCompilerPass($addTopicPass);
    }
}

BAP-11752: Replace JMS Job with Message Queue in NotificationBundle

 - registering topic in the bundle


<?php

namespace Yolo\DependencyInjection;

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

class ServiceControllerExtension extends Extension
{
    public function load(array $config, ContainerBuilder $container)
    {
        $container
            ->register('controller_resolver.service', 'Yolo\DependencyInjection\ServiceControllerResolver')
            ->setArguments([
                new Reference('controller_resolver.decorated'),
                new Reference('service_container'),
            ])
            ->addTag('controller_resolver.decorator', []);
    }
}

<?php

namespace Yolo\DependencyInjection;

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

class ServiceControllerExtension extends Extension
{
    public function load(array $config, ContainerBuilder $container)
    {
        $container
            ->register('controller_resolver.service', 'Yolo\DependencyInjection\ServiceControllerResolver')
            ->setArguments([
                new Reference('controller_resolver.decorated'),
                new Reference('service_container'),
            ])
            ->addTag('controller_resolver.decorator', []);
    }
}

Use DI extension base class from DI component


<?php

class AccessKeysSiteConfig extends DataObjectDecorator {

    function extraStatics() {
        return array(
            'db' => array(
                'SearchAccessKey' => 'VarChar(1)',
                'SkipToMainContentAccessKey' => 'VarChar(1)',
                'AccessibilityHelpAccessKey' => 'VarChar(1)'
            )
        );
    }

    public function updateCMSFields(FieldSet &$fields) {

        $tf1 = new TextField('SearchAccessKey');
	    $tf1->setMaxLength(1);
	    $fields->addFieldToTab('Root.Accessibility', $tf1);
	    $fields->renameField("SearchAccessKey", _t('AccessKey.SEARCH_ACCESS_KEY'));

	    $tf2 = new TextField('SkipToMainContentAccessKey');
	    $tf2->setMaxLength(1);
	    $fields->addFieldToTab('Root.Accessibility', $tf2);
	    $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY'));

	    $tf3 = new TextField('AccessibilityHelpAccessKey');
	    $tf3->setMaxLength(1);
	    $fields->addFieldToTab('Root.Accessibility', $tf3);
	    $fields->renameField("AccessibilityHelpAccessKey", _t('AccessKey.ACCESSIBILITY_HELP_ACCESS_KEY'));
	}

}
?>

<?php

class AccessKeysSiteConfig extends DataObjectDecorator {

    function extraStatics() {
        return array(
            'db' => array(
                'SkipToMainContentAccessKey' => 'VarChar(1)'
            )
        );
    }

    public function updateCMSFields(FieldSet &$fields) {
	    $tf2 = new TextField('SkipToMainContentAccessKey');
	    $tf2->setMaxLength(1);
	    $fields->addFieldToTab('Root.Accessibility', $tf2);
	    $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY'));
	}

}
?>

FIX: Remove access key fields that are not required


<?php
/**
 * @author @fabfuel <fabian@fabfuel.de>
 * @created 25.11.14, 08:12
 */
namespace Fabfuel\Prophiler\Plugin\Phalcon\Mvc;

use Phalcon\Events\Event;
use Phalcon\Mvc\ViewInterface;

interface ViewPluginInterface
{
    /**
     * @param Event $event
     * @param ViewInterface $view
     * @return void()
     */
    public function beforeRenderView(Event $event, ViewInterface $view);

    /**
     * @param Event $event
     * @param ViewInterface $view
     * @return void()
     */
    public function afterRenderView(Event $event, ViewInterface $view);

    /**
     * @param Event $event
     * @param ViewInterface $view
     * @return void()
     */
    public function afterRender(Event $event, ViewInterface $view);
}

<?php
/**
 * @author @fabfuel <fabian@fabfuel.de>
 * @created 25.11.14, 08:12
 */
namespace Fabfuel\Prophiler\Plugin\Phalcon\Mvc;

use Phalcon\Events\Event;
use Phalcon\Mvc\ViewInterface;

interface ViewPluginInterface
{
    /**
     * @param Event $event
     * @param ViewInterface $view
     * @return void
     */
    public function beforeRenderView(Event $event, ViewInterface $view);

    /**
     * @param Event $event
     * @param ViewInterface $view
     * @return void
     */
    public function afterRenderView(Event $event, ViewInterface $view);

    /**
     * @param Event $event
     * @param ViewInterface $view
     * @return void
     */
    public function afterRender(Event $event, ViewInterface $view);
}

Fix typo in @return annotation

Fix typo in @return annotation


<?php namespace Anomaly\PostsModule\Post;

use Anomaly\PostsModule\Post\Contract\PostInterface;
use Anomaly\Streams\Platform\Support\Authorizer;
use Illuminate\Auth\Guard;

/**
 * Class PostAuthorizer
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 * @package       Anomaly\PostsModule\Post
 */
class PostAuthorizer
{

    /**
     * The authorization utility.
     *
     * @var Guard
     */
    protected $guard;

    /**
     * The authorizer utility.
     *
     * @var Authorizer
     */
    protected $authorizer;

    /**
     * Create a new PostAuthorizer instance.
     *
     * @param Guard      $guard
     * @param Authorizer $authorizer
     */
    public function __construct(Guard $guard, Authorizer $authorizer)
    {
        $this->guard      = $guard;
        $this->authorizer = $authorizer;
    }

    /**
     * Authorize the post.
     *
     * @param PostInterface $post
     */
    public function authorize(PostInterface $post)
    {
        if (!$post->isEnabled() && !$this->guard->user()) {
            abort(404);
        }

        if (!$this->authorizer->authorize('anomaly.module.posts::view_drafts')) {
            abort(404);
        }
    }
}

<?php namespace Anomaly\PostsModule\Post;

use Anomaly\PostsModule\Post\Contract\PostInterface;
use Anomaly\Streams\Platform\Support\Authorizer;
use Illuminate\Auth\Guard;

/**
 * Class PostAuthorizer
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 * @package       Anomaly\PostsModule\Post
 */
class PostAuthorizer
{

    /**
     * The authorization utility.
     *
     * @var Guard
     */
    protected $guard;

    /**
     * The authorizer utility.
     *
     * @var Authorizer
     */
    protected $authorizer;

    /**
     * Create a new PostAuthorizer instance.
     *
     * @param Guard      $guard
     * @param Authorizer $authorizer
     */
    public function __construct(Guard $guard, Authorizer $authorizer)
    {
        $this->guard      = $guard;
        $this->authorizer = $authorizer;
    }

    /**
     * Authorize the post.
     *
     * @param PostInterface $post
     */
    public function authorize(PostInterface $post)
    {
        if (!$post->isEnabled() && !$this->authorizer->authorize('anomaly.module.posts::view_drafts')) {
            abort(404);
        }
    }
}

Fix issue where posts were being authorized when not needed.


<?php

/**
 * @author Petr Pliska <petr.pliska@post.cz>
 */

namespace App\Module\Web\Controller;

/**
 * PSR-7 interfaces
 * @see http://www.php-fig.org/psr/psr-7/
 */
use Psr\Http\Message\{RequestInterface, ResponseInterface};

class IndexController extends AbstractWebController
{
    /**
     * @inject
     * @var  League\Monga\Database
     */
    protected $monga;

    /**
     * @inject("db.dsn")
     * @var [type]
     */
    protected $test;
    /**
     * @inject
     * @var Dibi\Connection
     */
    protected $dibi;

    /**
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function defaultAction(RequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        dump($this->dibi);exit;
       // $command = new \App\Service\Command\User\Register('alice@example.com', 'secret');
       // $this->commandBus->handle($command);
        return $this->view->render('web/index/default.latte');
    }
}

<?php

/**
 * @author Petr Pliska <petr.pliska@post.cz>
 */

namespace App\Module\Web\Controller;

/**
 * PSR-7 interfaces
 * @see http://www.php-fig.org/psr/psr-7/
 */
use Psr\Http\Message\{RequestInterface, ResponseInterface};

class IndexController extends AbstractWebController
{
    /**
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function defaultAction(RequestInterface $request, ResponseInterface $response): ResponseInterface
    {
       // $command = new \App\Service\Command\User\Register('alice@example.com', 'secret');
       // $this->commandBus->handle($command);
        return $this->view->render('web/index/default.latte');
    }
}

Remove dependencies from index controller


<?php

namespace wcf\data\user\avatar;

/**
 * A safe avatar supports a broadly supported fallback image format.
 *
 * @author  Tim Duesterhus
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Data\User\Avatar
 */
interface ISafeFormatAvatar extends IUserAvatar
{
    /**
     * @see IUserAvatar::getURL()
     */
    public function getSafeURL(?int $size = null): string;

    /**
     * @see IUserAvatar::getImageTag()
     */
    public function getSafeImageTag(?int $size = null): string;
}

<?php

namespace wcf\data\user\avatar;

/**
 * A safe avatar supports a broadly supported fallback image format.
 *
 * @author  Tim Duesterhus
 * @copyright   2001-2021 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\Data\User\Avatar
 * @since 5.4
 */
interface ISafeFormatAvatar extends IUserAvatar
{
    /**
     * @see IUserAvatar::getURL()
     */
    public function getSafeURL(?int $size = null): string;

    /**
     * @see IUserAvatar::getImageTag()
     */
    public function getSafeImageTag(?int $size = null): string;
}

Add missing `@since` to ISafeFormatAvatar


<?php
/**
 * ExtReferenceConverterInterface class file
 */

namespace Graviton\DocumentBundle\Service;

/**
 * Extref converter interface
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://swisscom.ch
 */
interface ExtReferenceConverterInterface
{
    /**
     * return the mongodb representation from a extref URL
     *
     * @param string $url Extref URL
     * @return array
     * @throws \InvalidArgumentException
     */
    public function getDbRef($url);

    /**
     * return the extref URL
     *
     * @param object $dbRef DB ref
     * @return string
     * @throws \InvalidArgumentException
     */
    public function getUrl($dbRef);
}

<?php
/**
 * ExtReferenceConverterInterface class file
 */

namespace Graviton\DocumentBundle\Service;

/**
 * Extref converter interface
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://swisscom.ch
 */
interface ExtReferenceConverterInterface
{
    /**
     * return the mongodb representation from a extref URL
     *
     * @param string $url Extref URL
     * @return object
     * @throws \InvalidArgumentException
     */
    public function getDbRef($url);

    /**
     * return the extref URL
     *
     * @param object $dbRef DB ref
     * @return string
     * @throws \InvalidArgumentException
     */
    public function getUrl($dbRef);
}

Fix return type in DocBlock.

Fix return type in DocBlock.


<?php

/* vim: set shiftwidth=2 expandtab softtabstop=2: */

namespace Boris;

class Autocompletion {
    private $symbols = [];

    public function __construct() {
    }

    public function complete($status)
    {
        $chunk = substr($status['line'], 0, $status['cursor']);

        /**
         * Verify if we are in a variable context
         * Take the last word and check if the first character is a '$'
         */
        $tokens = preg_split('/[^a-zA-Z_\$]/', $chunk);
        $current = end($tokens);
        if($current && $current[0] == '$') {
            return $this->getVariables();
        } else {
            return $this->getSymbols();
        }
    }

    private function getSymbols() {
        if(empty($this->symbols)) {
            $this->symbols = call_user_func_array(
                "array_merge", array_values(get_defined_functions())
            );

            $this->symbols = array_merge(
                $this->symbols, array_keys(get_defined_constants())
            );
        }

        return $this->symbols;
    }

    private function getVariables() {
        /**
         * TODO: Find a way to access EvalWorker context/scope to access vars
         */
        return ['this', 'container'];
    }

}

<?php

/* vim: set shiftwidth=2 expandtab softtabstop=2: */

namespace Boris;

class Autocompletion {
    private $symbols = [];

    public function __construct() {
    }

    public function complete($status)
    {
        $chunk = substr($status['line'], 0, $status['cursor']);

        /**
         * Verify if we are in a variable context
         * Take the last word and check if the first character is a '$'
         */
        $tokens = preg_split('/[^a-zA-Z_\$]/', $chunk);
        $current = end($tokens);
        if($current && $current[0] == '$') {
            return $this->getVariables();
        } else {
            return $this->getSymbols();
        }
    }

    private function getSymbols() {
        if(empty($this->symbols)) {
            $this->symbols = call_user_func_array(
                "array_merge", array_values(get_defined_functions())
            );

            $this->symbols = array_merge(
                $this->symbols, array_keys(get_defined_constants())
            );
        }

        return $this->symbols;
    }

    private function getVariables() {
        /**
         * TODO: Find a way to access EvalWorker context/scope to access vars
         */
        return array('this', 'container');
    }

}

Use old array syntax for Autocomplete

Use old array syntax for Autocomplete


<?php
/**
 * Config class
 * Configuration for Skeleton\Core
 *
 * @author Christophe Gosiau <christophe@tigron.be>
 * @author Gerry Demaret <gerry@tigron.be>
 */

namespace Skeleton\Core;

class Config {

	/**
	 * Application directory
	 *
	 * @access public
	 * @var string $application_dir
	 */
	public static $application_dir = null;

	/**
	 * Asset directory
	 *
	 * A directory which will be searched for media failes in addition to the
	 * application's media path
	 *
	 * @access public
	 * @var string $asset_dir
	 */
	public static $asset_dir = null;

	/**
	 * Name of the module that handles 403 errors
	 *
	 * @access public
	 * @var string $module_403
	 */
	public static $module_403 = null;

	/**
	 * Name of the session
	 *
	 * @access public
	 * @var string $session_name
	 */
	public static $session_name = 'APP';

	/**
	 * Name of the variable to store the sticky session object in
	 *
	 * @access public
	 * @var string $sticky_session_namse
	 */
	public static $sticky_session_name = 'sys_sticky_session';
}

<?php
/**
 * Config class
 * Configuration for Skeleton\Core
 *
 * @author Christophe Gosiau <christophe@tigron.be>
 * @author Gerry Demaret <gerry@tigron.be>
 */

namespace Skeleton\Core;

class Config {

	/**
	 * Application directory
	 *
	 * @access public
	 * @var string $application_dir
	 */
	public static $application_dir = null;

	/**
	 * Asset directory
	 *
	 * A directory which will be searched for media failes in addition to the
	 * application's media path
	 *
	 * @access public
	 * @var string $asset_dir
	 */
	public static $asset_dir = null;

	/**
	 * Temp directory
	 *
	 * @access public
	 * @var string $tmp_dir
	 */
	public static $tmp_dir = null;

	/**
	 * Name of the module that handles 403 errors
	 *
	 * @access public
	 * @var string $module_403
	 */
	public static $module_403 = null;

	/**
	 * Name of the session
	 *
	 * @access public
	 * @var string $session_name
	 */
	public static $session_name = 'APP';

	/**
	 * Name of the variable to store the sticky session object in
	 *
	 * @access public
	 * @var string $sticky_session_namse
	 */
	public static $sticky_session_name = 'sys_sticky_session';
}

Add temp directory config setting

Add temp directory config setting


<?php
/**
 * Garp_Application
 * Provides the extra functionality of being able to cache config files.
 * @author Harmen Janssen | grrr.nl
 * @modifiedby $LastChangedBy: $
 * @version $Revision: $
 * @package Garp
 * @lastmodified $Date: $
 */
class Garp_Application extends Zend_Application {
	/**
	 * Load configuration file of options.
	 *
	 * Optionally will cache the configuration.
	 *
	 * @param  string $file
	 * @throws Zend_Application_Exception When invalid configuration file is provided
	 * @return array
	 */
	protected function _loadConfig($file) {
		$config = Garp_Cache_Ini::factory($file);
		// Save the configuration in the registry so it can be accessed from anywhere
		Zend_Registry::set('config', $config);
		return $config->toArray();
	}
}

<?php
/**
 * Garp_Application
 * Provides the extra functionality of being able to cache config files.
 * @author Harmen Janssen | grrr.nl
 * @modifiedby $LastChangedBy: $
 * @version $Revision: $
 * @package Garp
 * @lastmodified $Date: $
 */
class Garp_Application extends Zend_Application {
	/**
	 * Load configuration file of options.
	 *
	 * Optionally will cache the configuration.
	 *
	 * @param  string $file
	 * @throws Zend_Application_Exception When invalid configuration file is provided
	 * @return array
	 */
	protected function _loadConfig($file) {
		$suffix      = pathinfo($file, PATHINFO_EXTENSION);
        $suffix      = ($suffix === 'dist')
                     ? pathinfo(basename($file, ".$suffix"), PATHINFO_EXTENSION)
                     : $suffix;
		if ($suffix == 'ini') {
			$config = Garp_Cache_Ini::factory($file)->toArray();
		} else {
			$config = parent::_loadConfig($file);
		}
		return $config;
	}

	public function bootstrap($resource = null) {
		Zend_Registry::set('config', new Zend_Config($this->getOptions()));
		return parent::bootstrap();
	}
}

Refactor to better cache configuration

Refactor to better cache configuration


<form method="POST" action="{{ action('SettingsController@update') }}">
    <input type="hidden" name="_method" value="PATCH" />
    {!! csrf_field() !!}

    @if(version_compare($version, '5.3.0') < 0)
        @include('geniusts_preferences::settings_5_2')
    @else
        @include('geniusts_preferences::settings_5_3')
    @endif

            <button type="submit" class="btn btn-primary">
                Save
            </button>

</form>

<form method="POST" action="{{ action('SettingsController@update') }}">
    @if($errors->count())

            <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>

                @foreach($errors->all() as $error)

                        {{ $error }}

                @endforeach

    @endif

    <input type="hidden" name="_method" value="PATCH"/>
    {!! csrf_field() !!}

    @if(version_compare($version, '5.3.0') < 0)
        @include('geniusts_preferences::settings_5_2')
    @else
        @include('geniusts_preferences::settings_5_3')
    @endif

            <button type="submit" class="btn btn-primary">
                Save
            </button>

</form>

Add errors to the form

Add errors to the form


<?php
/**
 * Go! OOP&AOP PHP framework
 *
 * @copyright     Copyright 2011, Lissachenko Alexander <lisachenko.it@gmail.com>
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

namespace go\core;

/**
 * @package go
 * @subpackage core
 */
class Autoload
{
    static function init()
    {
        spl_autoload_register(self::getLoader());
    }

    protected static function getLoader()
    {
        return function($className) {
            $className = ltrim($className, '\\');
            $fileName  = '';
            $namespace = '';
            if ($lastNsPos = strripos($className, '\\')) {
                $namespace = substr($className, 0, $lastNsPos);
                $className = substr($className, $lastNsPos + 1);
                $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
            }
            $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

            require $fileName;
        };
    }

}

<?php
/**
 * Go! OOP&AOP PHP framework
 *
 * @copyright     Copyright 2011, Lissachenko Alexander <lisachenko.it@gmail.com>
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

namespace go\core;

/**
 * @package go
 * @subpackage core
 */
class Autoload
{
    const CLASS_LOADER_FILTER_PREFIX = 'go.core.classloader.';

    static function init()
    {
        spl_autoload_register(self::getLoader());
        stream_filter_register(self::CLASS_LOADER_FILTER_PREFIX . '*', __NAMESPACE__ . '\\'. 'ClassLoader') or die('bad');
    }

    protected static function getLoader()
    {
        return function($originalClassName) {
            $className = ltrim($originalClassName, '\\');
            $fileName  = '';
            $namespace = '';
            if ($lastNsPos = strripos($className, '\\')) {
                $namespace = substr($className, 0, $lastNsPos);
                $className = substr($className, $lastNsPos + 1);
                $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
            }
            $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

            $resolvedFileName = $fileName;//stream_resolve_include_path($fileName);
            if ($resolvedFileName) {
                $isCore = strpos($namespace, 'go\core') === 0;
                if (!$isCore) {
                    require "php://filter/read=".Autoload::CLASS_LOADER_FILTER_PREFIX."$originalClassName/resource=$resolvedFileName";
                } else {
                    require $resolvedFileName;
                }
            }
            return (bool)$resolvedFileName;
        };
    }

}

Add support for ClassLoader for loading and processing php sourcecode


<?php

namespace BrainBundle\Tests\Controller;

use Liip\FunctionalTestBundle\Test\WebTestCase;

class WernickeControllerTest extends WebTestCase
{
    public function testMarkovAction()
    {
        // Make new client
        $client = $this->makeClient();

        // Request for page
        $crawler = $client->request('GET', '/brain/markov');

        // Check if the request is success
        $this->assertStatusCode(200, $client);

        // Select a form
        $form = $crawler->selectButton('Submit')->form();

        // Submit without data
        $crawler = $client->submit($form);
        // Check if status code is 200
        $this->assertStatusCode(200, $client);
        // Check if contains error
        $this->assertContains('Input text must be provided', $client->getResponse()->getContent());

        // Submit the form with data
        $form = $crawler->selectButton('Submit')->form();
        $form->setValues(['form[input_text]' => 'Lorem Ipsum dolor sit amet', 'form[length]' => '10']);
        $client->submit($form);
        $this->assertStatusCode(200, $client);
    }
}

<?php

namespace BrainBundle\Tests\Controller;

use Liip\FunctionalTestBundle\Test\WebTestCase;

class WernickeControllerTest extends WebTestCase
{
    public function testMarkovAction()
    {
        // Make new client
        $client = $this->makeClient();

        // Request for page
        $crawler = $client->request('GET', '/brain/markov');

        // Check if the request is success
        $this->assertStatusCode(200, $client);

        // Select a form
        $form = $crawler->selectButton('Submit')->form();

        // Submit without data
        $crawler = $client->submit($form);
        // Check if status code is 200
        $this->assertStatusCode(200, $client);
        // Check if contains error
        $this->assertContains('Input text must be provided', $client->getResponse()->getContent());

        // Submit the form with data
        $form = $crawler->selectButton('Submit')->form();
        $form->setValues(['form[input_text]' => 'Lorem Ipsum dolor sit amet', 'form[length]' => '10']);
        $client->submit($form);
        $this->assertStatusCode(200, $client);
        $text = $client->getCrawler()->filter('div.output p')->text();
        echo $text;
    }
}

Add test cases for brain

Add test cases for brain


<?php

namespace vxPHP\Form\FormElement\FormElementWithOptions;

use vxPHP\Form\FormElement\FormElementWithOptions\FormElementFragment;

/**
 * a single option belonging to a group of <input type="option"> elements
 * sharing the same name
 *
 * @author Gregor Kofler
 * @version 0.4.0 2015-01-24
 */
class RadioOptionElement extends FormElementFragment {

	/**
	 * initialize option with value, label and parent RadioElement
	 *
	 * @param string $value
	 * @param string $label
	 * @param RadioElement $formElement
	 */
	public function __construct($value, $label, RadioElement $formElement = NULL) {

		parent::__construct($value, NULL, $label, $formElement);

	}

	/**
	 * render element; when $force is FALSE a cached element rendering is re-used
	 *
	 * @param string $force
	 */
	public function render($force = FALSE) {

		if(empty($this->html) || $force) {
			$checked = $this->selected ? " checked='checked'" : '';
			$this->html = "<input name='{$this->parentElement->getName()}' type='radio' value='{$this->getValue()}'$checked>{$this->getLabel()}";
		}

		return $this->html;

	}
}

<?php

namespace vxPHP\Form\FormElement\FormElementWithOptions;

use vxPHP\Form\FormElement\FormElementWithOptions\FormElementFragment;

/**
 * a single option belonging to a group of <input type="option"> elements
 * sharing the same name
 *
 * @author Gregor Kofler
 * @version 0.4.1 2015-11-14
 */
class RadioOptionElement extends FormElementFragment {

	/**
	 * initialize option with value, label and parent RadioElement
	 *
	 * @param string $value
	 * @param string $label
	 * @param RadioElement $formElement
	 */
	public function __construct($value, $label, RadioElement $formElement = NULL) {

		parent::__construct($value, NULL, $label, $formElement);

	}

	/**
	 * render element; when $force is FALSE a cached element rendering is re-used
	 *
	 * @param string $force
	 */
	public function render($force = FALSE) {

		if(empty($this->html) || $force) {

			$this->html = sprintf(
				'<input name="%s" type="radio" value="%s"%s><label>%s</label>',
				$this->parentElement->getName(),
				$this->getValue(),
				$this->selected ? " checked='checked'" : '',
				$this->getLabel()
			);
		}

		return $this->html;

	}
}

Put text for radio elements into label tags


<?php

namespace CommerceGuys\Platform\Cli\Command;

use CommerceGuys\Platform\Cli\Model\Environment;

class EnvironmentCommand extends PlatformCommand
{

    /**
     * @param string $operation
     * @param array|null $environment
     *
     * @return bool Whether the operation is allowed on the environment.
     */
    protected function operationAllowed($operation, array $environment = null)
    {
        $data = $environment ?: $this->environment;
        if (!$data) {
            return false;
        }
        $environment = new Environment($data);
        return $environment->operationAllowed($operation);
    }

}

<?php

namespace CommerceGuys\Platform\Cli\Command;

use CommerceGuys\Platform\Cli\Model\Environment;

class EnvironmentCommand extends PlatformCommand
{

    /**
     * @param string $operation
     * @param array|null $environment
     *
     * @return bool Whether the operation is allowed on the environment.
     */
    protected function operationAllowed($operation, array $environment = null)
    {
        $data = $environment ?: $this->environment;
        if (!$data) {
            return false;
        }
        $wrapper = new Environment($data);
        $result = $wrapper->operationAllowed($operation);

        // Refresh the environment to work around caching issues.
        // @todo remove this when HTTP caching is enabled
        if (!$result && $environment === null) {
            $data = $this->getEnvironment($wrapper->id(), null, true);
            if (!$data) {
                throw new \RuntimeException("Environment not found: " . $wrapper->id());
            }
            $wrapper = new Environment($data);
            return $wrapper->operationAllowed($operation);
        }

        return $result;
    }

}

Work around 'operation not allowed' for a stale environment cache.


<?php

namespace Math;

use ReflectionClass;

class RationalTest extends Dev\TestCase {

    public function testClassExists() {
        $this->assertTrue(class_exists('Math\\Rational'));
    }

    public function testClassIsFinal() {
        $this->assertTrue((new ReflectionClass('Math\\Rational'))->isFinal());
    }
}

<?php

namespace Math;

use ReflectionClass;

class RationalTest extends Dev\TestCase {

    public function testClassExists() {
        $this->assertTrue(class_exists('Math\\Rational'));
    }

    public function testClassIsFinal() {
        $this->assertTrue((new ReflectionClass('Math\\Rational'))->isFinal());
    }

    public function testIsPositiveMethod() {
        $this->assertTrue($this->make(3, 7)->isPositive());
        $this->assertTrue($this->make(-5, -10)->isPositive());
        $this->assertFalse($this->make(15, -25)->isPositive());
        $this->assertFalse($this->make(-123, 515)->isPositive());
    }

    public function testIsNegativeMethod() {
        $this->assertTrue($this->make(1, -2)->isNegative());
        $this->assertTrue($this->make(-55, 3)->isNegative());
        $this->assertFalse($this->make(1234, 12)->isNegative());
        $this->assertFalse($this->make(-678, -8961)->isNegative());
    }

    public function testIsZeroMethod() {
        $this->assertTrue($this->make(0, 234)->isZero());
        $this->assertTrue($this->make(0, -15)->isZero());
        $this->assertFalse($this->make(1, 1)->isZero());
        $this->assertFalse($this->make(-15, -2)->isZero());
        $this->assertFalse($this->make(-3, 1234)->isZero());
        $this->assertFalse($this->make(5, -2)->isZero());
    }

    private function make(int $num, int $denom): Rational {
        return new Rational(new Integer($num), new Integer($denom));
    }
}

Write some tests for Rational and RealContract.


<?php

/*
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Entities;

use Longman\TelegramBot\Exception\TelegramException;

class UserProfilePhotos extends Entity
{

    protected $total_count;
    protected $photos;

    public function __construct(array $data)
    {

        $this->total_count = isset($data['total_count']) ? $data['total_count'] : null;
        if ($this->total_count === null && !is_numeric($this->total_count)) {
            throw new TelegramException('total_count is empty!');
        }
        $this->photos = isset($data['photos']) ? $data['photos'] : null;
        if ($this->photos === null || !is_array($data['photos'])) {
            throw new TelegramException('photos is empty!');
        }

        $photos = [];
        foreach ($this->photos as $key => $photo) {
            if (is_array($photo)) {
                foreach ($photo as $photo_size) {
                    $photos[$key][] = new PhotoSize($photo_size);
                }
            } else {
                throw new TelegramException('photo is not an array!');
            }
        }

        $this->photos = $photos;
    }

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

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

<?php

/*
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Entities;

use Longman\TelegramBot\Exception\TelegramException;

class UserProfilePhotos extends Entity
{

    protected $total_count;
    protected $photos;

    public function __construct(array $data)
    {

        $this->total_count = isset($data['total_count']) ? $data['total_count'] : null;
        if ($this->total_count === null || !is_numeric($this->total_count)) {
            throw new TelegramException('total_count is empty!');
        }
        $this->photos = isset($data['photos']) ? $data['photos'] : null;
        if ($this->photos === null || !is_array($data['photos'])) {
            throw new TelegramException('photos is empty!');
        }

        $photos = [];
        foreach ($this->photos as $key => $photo) {
            if (is_array($photo)) {
                foreach ($photo as $photo_size) {
                    $photos[$key][] = new PhotoSize($photo_size);
                }
            } else {
                throw new TelegramException('photo is not an array!');
            }
        }

        $this->photos = $photos;
    }

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

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

Fix for /whoami with a user who doesn't have a profile picture

&& should be ||


<?php

namespace SlmQueueSqsTest\Controller;

use PHPUnit_Framework_TestCase as TestCase;
use SlmQueueSqs\Controller\SqsWorkerController;
use Zend\Mvc\Router\RouteMatch;

class SqsWorkerControllerTest extends TestCase
{
    public function testCorrectlyCountJobs()
    {
        $queue         = $this->getMock('SlmQueue\Queue\QueueInterface');
        $worker        = $this->getMock('SlmQueue\Worker\WorkerInterface');
        $pluginManager = $this->getMock('SlmQueue\Queue\QueuePluginManager', [], [], '', false);

        $pluginManager->expects($this->once())
                      ->method('get')
                      ->with('newsletter')
                      ->will($this->returnValue($queue));

        $controller    = new SqsWorkerController($worker, $pluginManager);

        $routeMatch = new RouteMatch(array('queue' => 'newsletter'));
        $controller->getEvent()->setRouteMatch($routeMatch);

        $worker->expects($this->once())
               ->method('processQueue')
               ->with($queue)
               ->will($this->returnValue(1));

        $result = $controller->processAction();

        $this->assertEquals("Finished worker for queue 'newsletter' with 1 jobs\n", $result);
    }
}

<?php

namespace SlmQueueSqsTest\Controller;

use PHPUnit_Framework_TestCase as TestCase;
use SlmQueueSqs\Controller\SqsWorkerController;
use Zend\Mvc\Router\RouteMatch;

class SqsWorkerControllerTest extends TestCase
{
    public function testCorrectlyCountJobs()
    {
        $queue         = $this->getMock('SlmQueue\Queue\QueueInterface');
        $worker        = $this->getMock('SlmQueue\Worker\WorkerInterface');
        $pluginManager = $this->getMock('SlmQueue\Queue\QueuePluginManager', array(), array(), '', false);

        $pluginManager->expects($this->once())
                      ->method('get')
                      ->with('newsletter')
                      ->will($this->returnValue($queue));

        $controller    = new SqsWorkerController($worker, $pluginManager);

        $routeMatch = new RouteMatch(array('queue' => 'newsletter'));
        $controller->getEvent()->setRouteMatch($routeMatch);

        $worker->expects($this->once())
               ->method('processQueue')
               ->with($queue)
               ->will($this->returnValue(1));

        $result = $controller->processAction();

        $this->assertEquals("Finished worker for queue 'newsletter' with 1 jobs\n", $result);
    }
}

Fix test for PHP 5.3

Fix test for PHP 5.3


Update wiki-like text format to markdown.


<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2016-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 / App / System / Core / Class
 */

namespace PH7;

class TwoFactorAuthCore
{
    const PROFILE_ID_SESS_NAME = '2fa_profile_id';
}

<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2016-2019, 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 / App / System / Core / Class
 */

namespace PH7;

final class TwoFactorAuthCore
{
    const PROFILE_ID_SESS_NAME = '2fa_profile_id';
}

[StaticClass] Use final keyword to make sure it won't be extended


<?php

/**
 * Feed form.
 *
 * @package    form
 * @subpackage feed
 */
class FeedForm extends BaseFeedForm
{
  public function configure()
  {
    $this->setWidgets(Array(
        'id' => new sfWidgetFormInputHidden(),
        'podcast_id' => new sfWidgetFormInputHidden(),
        'title' => new sfWidgetFormTextarea(),
        'slug'=> new sfWidgetFormInput(),
        'rss_url'=> new sfWidgetFormInput(),
    ));

    $this->setValidators(array(
        'id' => new sfValidatorInteger(array('required' => false)),
        'podcast_id' => new sfValidatorInteger(array('required' => true)),
        'title' => new sfValidatorString(array('required' => true)),
        'slug' => new sfValidatorString(array('required' => false)),
        'rss_url' => new sfValidatorUrl(Array('required' => false)),
    ));

  }
}

<?php

/**
 * Feed form.
 *
 * @package    form
 * @subpackage feed
 */
class FeedForm extends BaseFeedForm
{
  public function configure()
  {
    $this->setWidgets(Array(
        'id' => new sfWidgetFormInputHidden(),
        'podcast_id' => new sfWidgetFormInputHidden(),
        'title' => new sfWidgetFormInput(),
        'slug'=> new sfWidgetFormInput(),
        'rss_url'=> new sfWidgetFormInput(),
    ));

    $this->setValidators(array(
        'id' => new sfValidatorInteger(array('required' => false)),
        'podcast_id' => new sfValidatorInteger(array('required' => true)),
        'title' => new sfValidatorString(array('required' => true)),
        'slug' => new sfValidatorString(array('required' => false)),
        'rss_url' => new sfValidatorUrl(Array('required' => false)),
    ));

  }
}

Switch title from textarea to textinput

Switch title from textarea to textinput


<?php

namespace Aztech\Phinject\Tests\ResolverSpecifications;

use Aztech\Phinject\ContainerFactory;
class ServiceNameResolverSpecificationTest extends \PHPUnit_Framework_TestCase
{

    public function testServiceNameIsInjectable()
    {
        $yaml = <<<YML
classes:
    myNamedService:
        class: \stdClass
        properties:
            myName: \$name
YML;

        $container = ContainerFactory::createFromInlineYaml($yaml);
        $service = $container->get('myNamedService');

        $this->assertEquals('myNamedService', $service->myName);
    }
}

<?php

namespace Aztech\Phinject\Tests\ResolverSpecifications;

use Aztech\Phinject\ContainerFactory;
class ServiceNameResolverSpecificationTest extends \PHPUnit_Framework_TestCase
{

    public function testServiceNameIsInjectedIntoService()
    {
        $yaml = <<<YML
classes:
    myNamedService:
        class: \stdClass
        properties:
            myName: \$name
YML;

        $container = ContainerFactory::createFromInlineYaml($yaml);
        $service = $container->get('myNamedService');

        $this->assertEquals('myNamedService', $service->myName);
    }

    public function testDependencyServiceNameIsCorrectlyInjectedIntoDependency()
    {
        $yaml = <<<YML
classes:
    myNamedService:
        class: \stdClass
        properties:
            myName: \$name
            myDependency: '@myNamedDependency'
    myNamedDependency:
        class: \stdClass
        properties:
            myName: \$name
YML;

        $container = ContainerFactory::createFromInlineYaml($yaml);
        $service = $container->get('myNamedService');

        $this->assertEquals('myNamedService', $service->myName);
        $this->assertEquals('myNamedDependency', $service->myDependency->myName);
    }
}

Add extra test for $name

Add extra test for $name


<?php

declare(strict_types=1);

namespace Psi\Component\Grid\Filter;

use Psi\Component\Grid\FilterInterface;
use Psi\Component\ObjectAgent\Query\Comparison;
use Psi\Component\ObjectAgent\Query\Expression;
use Psi\Component\ObjectAgent\Query\Query;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class BooleanFilter implements FilterInterface
{
    const CHOICE_ANY = 'any';

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('value', ChoiceType::class, [
            'choices' => [
                self::CHOICE_ANY => 'any',
                1 => 'yes',
                0 => 'no',
            ],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function isApplicable(array $filterData): bool
    {
        return self::CHOICE_ANY !== $filterData['value'];
    }

    /**
     * {@inheritdoc}
     */
    public function getExpression(string $fieldName, array $data): Expression
    {
        return Query::comparison(
            Comparison::EQUALS,
            $fieldName,
            $data['value']
        );
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $options)
    {
    }
}

<?php

declare(strict_types=1);

namespace Psi\Component\Grid\Filter;

use Psi\Component\Grid\FilterInterface;
use Psi\Component\ObjectAgent\Query\Comparison;
use Psi\Component\ObjectAgent\Query\Expression;
use Psi\Component\ObjectAgent\Query\Query;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class BooleanFilter implements FilterInterface
{
    const CHOICE_ANY = 'any';

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('value', ChoiceType::class, [
            'choices' => [
                1 => 'yes',
                0 => 'no',
            ],
            'empty_value' => self::CHOICE_ANY
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function isApplicable(array $filterData): bool
    {
        return isset($filterData['value']);
    }

    /**
     * {@inheritdoc}
     */
    public function getExpression(string $fieldName, array $data): Expression
    {
        return Query::comparison(
            Comparison::EQUALS,
            $fieldName,
            $data['value']
        );
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $options)
    {
    }
}

Use empty value with grid

Use empty value with grid


<?php
// Routes

$app->get('/', function ($request, $response, $args) {
    return $this->renderer->render($response, 'index.html', []);
});

<?php
// Routes

$app->get('/[index.php]', function ($request, $response, $args) {
    return $this->renderer->render($response, 'index.html', []);
});

Add routing option to maintain backwards compatibility


<?php

namespace Collective\Html;

use Illuminate\Support\ServiceProvider;

class HtmlServiceProvider extends ServiceProvider
{

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerHtmlBuilder();

        $this->registerFormBuilder();

        $this->app->alias('html', 'Collective\Html\HtmlBuilder');
        $this->app->alias('form', 'Collective\Html\FormBuilder');
    }

    /**
     * Register the HTML builder instance.
     *
     * @return void
     */
    protected function registerHtmlBuilder()
    {
        $this->app->singleton('html', function ($app) {
            return new HtmlBuilder($app['url'], $app['view']);
        });
    }

    /**
     * Register the form builder instance.
     *
     * @return void
     */
    protected function registerFormBuilder()
    {
        $this->app->singleton('form', function ($app) {
            $form = new FormBuilder($app['html'], $app['url'], $app['view'], $app['session.store']->getToken());

            return $form->setSessionStore($app['session.store']);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['html', 'form', 'Collective\Html\HtmlBuilder', 'Collective\Html\FormBuilder'];
    }
}

<?php

namespace Collective\Html;

use Illuminate\Support\ServiceProvider;

class HtmlServiceProvider extends ServiceProvider
{

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerHtmlBuilder();

        $this->registerFormBuilder();

        $this->app->alias('html', 'Collective\Html\HtmlBuilder');
        $this->app->alias('form', 'Collective\Html\FormBuilder');
    }

    /**
     * Register the HTML builder instance.
     *
     * @return void
     */
    protected function registerHtmlBuilder()
    {
        $this->app->singleton('html', function ($app) {
            return new HtmlBuilder($app['url'], $app['view']);
        });
    }

    /**
     * Register the form builder instance.
     *
     * @return void
     */
    protected function registerFormBuilder()
    {
        $this->app->singleton('form', function ($app) {
            $form = new FormBuilder($app['html'], $app['url'], $app['view'], $app['session.store']->token());

            return $form->setSessionStore($app['session.store']);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['html', 'form', 'Collective\Html\HtmlBuilder', 'Collective\Html\FormBuilder'];
    }
}

Fix getToken rename issue in 5.4

Fix getToken rename issue in 5.4


<?php

use Spatie\Seeders\Faker;

function faker(): Faker
{
    return app(Faker::class);
}

<?php

use Spatie\Seeders\Faker;

/** @return \Faker\Generator|Spatie\Seeders\Faker */
function faker(): Faker
{
    return app(Faker::class);
}

Add fake docblock to help with IDE method completion


<?php namespace Ixudra\Portfolio\Repositories\Eloquent;

use Ixudra\Core\Repositories\Eloquent\BaseEloquentRepository;

use Ixudra\Portfolio\Models\Customer;

class EloquentCustomerRepository extends BaseEloquentRepository {

    protected function getModel()
    {
        return new Customer;
    }

    protected function getTable()
    {
        return 'customers';
    }

    public function search($filters, $resultsPerPage)
    {
        $results = $this->getModel();
        foreach( $filters as $key => $value ) {
            if( !$this->hasString( $filters, $key ) ) {
                continue;
            }

            $results = $results->where( $key, 'like', $value );
        }

        return $results
            ->select($this->getTable() .'.*')
            ->paginate($resultsPerPage)
            ->appends($filters)
            ->appends('results_per_page', $resultsPerPage);
    }

}

<?php namespace Ixudra\Portfolio\Repositories\Eloquent;

use Ixudra\Core\Repositories\Eloquent\BaseEloquentRepository;

use Ixudra\Portfolio\Models\Customer;

class EloquentCustomerRepository extends BaseEloquentRepository {

    protected function getModel()
    {
        return new Customer;
    }

    protected function getTable()
    {
        return 'customers';
    }

    public function search($filters, $resultsPerPage)
    {
        $results = $this->getModel();
        $results = $results
            ->join('projects', 'customers.id', '=', 'projects.customer_id');

        foreach( $filters as $key => $value ) {
            if( !$this->hasString( $filters, $key ) ) {
                continue;
            }

            $results = $results->where( $key, 'like', $value );
        }

        return $results
            ->select($this->getTable() .'.*')
            ->paginate($resultsPerPage)
            ->appends($filters)
            ->appends('results_per_page', $resultsPerPage);
    }

}

Select only customers that have one or more projects


<?php
/**
 * We made many changes in this code.
 * By pH7 (Pierre-Henry SORIA).
 */

// JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl
namespace PFBC\Element;

class Textarea extends \PFBC\Element
{
    protected $attributes = array('class' => 'pfbc-textarea', 'rows' => '5');

    public function jQueryDocumentReady()
    {
        echo 'jQuery("#', $this->attributes['id'], '").outerWidth(jQuery("#', $this->attributes['id'], '").width());';
    }

    public function render()
    {
        $iLength = (!empty($this->attributes['value'])) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : '0';

        echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>';

        if (!empty($this->attributes['value'])) {
            echo $this->filter($this->attributes['value']);
        }

        echo '</textarea>
attributes['id'], '_rem_len">' . $iLength . ' ', t('character(s).'), '
';
    }
}

<?php
/**
 * Changes made by Pierre-Henry Soria.
 */

// JavaScript file is located in the directory ~static/js/str.js which is included in the file ~templates/themes/base/tpl/layout.tpl
namespace PFBC\Element;

class Textarea extends \PFBC\Element
{
    protected $attributes = array('class' => 'pfbc-textarea', 'rows' => '5');

    public function jQueryDocumentReady()
    {
        echo 'jQuery("#', $this->attributes['id'], '").outerWidth(jQuery("#', $this->attributes['id'], '").width());';
    }

    public function render()
    {
        $iLength = (!empty($this->attributes['value'])) ? (new \PH7\Framework\Str\Str)->length($this->attributes['value']) : '0';

        echo '<textarea onkeyup="textCounter(\'', $this->attributes['id'], '\',\'', $this->attributes['id'], '_rem_len\')"', $this->getAttributes('value'), $this->getHtmlRequiredIfApplicable(), '>';

        if (!empty($this->attributes['value'])) {
            echo $this->filter($this->attributes['value']);
        }

        echo '</textarea>
attributes['id'], '_rem_len">' . $iLength . ' ', t('character(s).'), '
';
    }
}

Change notice comment concerning the changes of the PFBC class


<?php

namespace Oro\Bundle\SoapBundle\Tests\EventListener;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

use Oro\Bundle\SoapBundle\EventListener\LocaleListener;

class LocaleListenerTest extends \PHPUnit_Framework_TestCase
{
    /** @var LocaleListener */
    protected $listener;

    /** @var string */
    protected $defaultLocale;

    protected function setUp()
    {
        $this->defaultLocale = \Locale::getDefault();
    }

    protected function tearDown()
    {
        \Locale::setDefault($this->defaultLocale);
    }

    public function testOnKernelRequest()
    {
        $customLocale = 'fr';

        $request = new Request(['_locale' => $customLocale]);
        //$request->server->set('REQUEST_URI', '/api/rest/test');
        $request->setDefaultLocale($this->defaultLocale);

        $this->listener = new LocaleListener();
        $this->listener->onKernelRequest($this->createGetResponseEvent($request));

        $this->assertEquals($customLocale, $request->getLocale());
    }

    /**
     * @param Request $request
     * @return GetResponseEvent
     */
    protected function createGetResponseEvent(Request $request)
    {
        $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
            ->disableOriginalConstructor()
            ->setMethods(array('getRequest'))
            ->getMock();

        $event->expects($this->once())
            ->method('getRequest')
            ->will($this->returnValue($request));

        return $event;
    }
}

<?php

namespace Oro\Bundle\SoapBundle\Tests\EventListener;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

use Oro\Bundle\SoapBundle\EventListener\LocaleListener;

class LocaleListenerTest extends \PHPUnit_Framework_TestCase
{
    /** @var LocaleListener */
    protected $listener;

    /** @var string */
    protected $defaultLocale;

    protected function setUp()
    {
        $this->defaultLocale = \Locale::getDefault();
    }

    protected function tearDown()
    {
        \Locale::setDefault($this->defaultLocale);
    }

    public function testOnKernelRequest()
    {
        $customLocale = 'fr';

        $request = new Request(['locale' => $customLocale]);
        $request->server->set('REQUEST_URI', '/api/rest/test');
        $request->setDefaultLocale($this->defaultLocale);

        $this->listener = new LocaleListener();
        $this->listener->onKernelRequest($this->createGetResponseEvent($request));

        $this->assertEquals($customLocale, $request->getLocale());
    }

    /**
     * @param Request $request
     * @return GetResponseEvent
     */
    protected function createGetResponseEvent(Request $request)
    {
        $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
            ->disableOriginalConstructor()
            ->setMethods(array('getRequest'))
            ->getMock();

        $event->expects($this->once())
            ->method('getRequest')
            ->will($this->returnValue($request));

        return $event;
    }
}

OEE-624: Add multi language support for Outlook layouts


<?php

namespace Oro\Bundle\ApiBundle\Processor;

use Oro\Bundle\ApiBundle\Provider\ConfigProvider;
use Oro\Bundle\ApiBundle\Processor\DeleteList\DeleteListContext;
use Oro\Bundle\ApiBundle\Provider\MetadataProvider;
use Oro\Component\ChainProcessor\ProcessorBag;

class DeleteListProcessor extends RequestActionProcessor
{
    /** @var ConfigProvider */
    protected $configProvider;

    /** @var MetadataProvider */
    protected $metadataProvider;

    /**
     * @param ProcessorBag     $processorBag
     * @param string           $action
     * @param ConfigProvider   $configProvider
     * @param MetadataProvider $metadataProvider
     */
    public function __construct(
        ProcessorBag $processorBag,
        $action,
        ConfigProvider $configProvider,
        MetadataProvider $metadataProvider
    ) {
        parent::__construct($processorBag, $action);
        $this->configProvider   = $configProvider;
        $this->metadataProvider = $metadataProvider;
    }

    /**
     * {@inheritdoc}
     */
    protected function createContextObject()
    {
        return new DeleteListContext($this->configProvider, $this->metadataProvider);
    }
}

<?php

namespace Oro\Bundle\ApiBundle\Processor;

use Oro\Component\ChainProcessor\ProcessorBag;

use Oro\Bundle\ApiBundle\Provider\ConfigProvider;
use Oro\Bundle\ApiBundle\Processor\DeleteList\DeleteListContext;
use Oro\Bundle\ApiBundle\Provider\MetadataProvider;

class DeleteListProcessor extends RequestActionProcessor
{
    /** @var ConfigProvider */
    protected $configProvider;

    /** @var MetadataProvider */
    protected $metadataProvider;

    /**
     * @param ProcessorBag     $processorBag
     * @param string           $action
     * @param ConfigProvider   $configProvider
     * @param MetadataProvider $metadataProvider
     */
    public function __construct(
        ProcessorBag $processorBag,
        $action,
        ConfigProvider $configProvider,
        MetadataProvider $metadataProvider
    ) {
        parent::__construct($processorBag, $action);
        $this->configProvider   = $configProvider;
        $this->metadataProvider = $metadataProvider;
    }

    /**
     * {@inheritdoc}
     */
    protected function createContextObject()
    {
        return new DeleteListContext($this->configProvider, $this->metadataProvider);
    }
}

BAP-9940: Create controller DELETE list action
 - fix cs


<?php

namespace Tests;

use Riskihajar\Terbilang\Facades\Terbilang;

class TerbilangTest extends TestCase
{
    /** @test */
    public function it_has_facade_accessor()
    {
        $this->assertEquals(Terbilang::make('123'), $this->terbilang->make('123'));
    }
}

<?php

namespace Tests;

use Riskihajar\Terbilang\Facades\Terbilang;

class TerbilangTest extends TestCase
{
    /** @test */
    public function it_has_make_method()
    {
        $this->assertTrue(method_exists($this->terbilang, 'make'));
    }

    /** @test */
    public function it_has_short_method()
    {
        $this->assertTrue(method_exists($this->terbilang, 'short'));
    }

    /** @test */
    public function it_has_date_method()
    {
        $this->assertTrue(method_exists($this->terbilang, 'date'));
    }

    /** @test */
    public function it_has_time_method()
    {
        $this->assertTrue(method_exists($this->terbilang, 'time'));
    }

    /** @test */
    public function it_has_datetime_method()
    {
        $this->assertTrue(method_exists($this->terbilang, 'datetime'));
    }

    /** @test */
    public function it_has_period_method()
    {
        $this->assertTrue(method_exists($this->terbilang, 'period'));
    }

    /** @test */
    public function it_has_roman_method()
    {
        $this->assertTrue(method_exists($this->terbilang, 'roman'));
    }

    /** @test */
    public function it_has_facade_accessor()
    {
        $this->assertEquals(Terbilang::make('123'), $this->terbilang->make('123'));
    }
}

Add public methods existance on Terbilang class


<?php

namespace Oro\Bundle\LocaleBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use Symfony\Component\Translation\TranslatorInterface;

use Oro\Bundle\LocaleBundle\Model\LocaleSettings;

class LocaleListener implements EventSubscriberInterface
{
    private $localeSettings;

    private $translator;

    public function __construct(
        LocaleSettings $localeSettings,
        TranslatorInterface $translator
    ) {
        $this->localeSettings = $localeSettings;
        $this->translator = $translator;
    }

    public function setRequest(Request $request = null)
    {
        if (!$request) {
            return;
        }

        if (!$request->attributes->get('_locale')) {
            $request->attributes->set('_locale', $this->localeSettings->getLocale());
        }

        $this->translator->setLocale($this->localeSettings->getLanguage());
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $this->setRequest($request);
    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered before Symfony's original LocaleListener
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

<?php

namespace Oro\Bundle\LocaleBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use Symfony\Component\Translation\TranslatorInterface;

use Oro\Bundle\LocaleBundle\Model\LocaleSettings;

class LocaleListener implements EventSubscriberInterface
{
    private $localeSettings;

    private $translator;

    public function __construct(LocaleSettings $localeSettings, TranslatorInterface $translator)
    {
        $this->localeSettings = $localeSettings;
        $this->translator = $translator;
    }

    public function setRequest(Request $request = null)
    {
        if (!$request) {
            return;
        }

        if (!$request->attributes->get('_locale')) {
            $request->setLocale($this->localeSettings->getLanguage());
        }
        $this->setPhpDefaultLocale($this->localeSettings->getLocale());
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $this->setRequest($request);
    }

    public function setPhpDefaultLocale($locale)
    {
        \Locale::setDefault($locale);
    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered after Symfony's original LocaleListener
            KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
        );
    }
}

BAP-2013: Create locale kernel listener
- added listener


<?php

namespace duncan3dc\SqlClass\Where;

abstract class AbstractWhere
{
    protected $values;

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

    abstract public function getClause();

    public function getValue()
    {
        return $this->values[0];
    }

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

<?php

namespace duncan3dc\SqlClass\Where;

abstract class AbstractWhere
{
    protected $values;

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

    abstract public function getClause();

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

Remove the getValue() method as it was never used


<?php

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

if ( ! defined( 'HTML_EOL' ) ) {
	define( 'HTML_EOL', '<br>' . PHP_EOL );
}
if ( ! defined( 'STAQ_ROOT_PATH' ) ) {
	define( 'STAQ_ROOT_PATH', dirname( __DIR__ ) . '/' );
}

require_once( __DIR__ . '/util/functions.php' );
require_once( __DIR__ . '/core/Server.php' );
require_once( __DIR__ . '/core/Autoloader.php' );

<?php

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

if ( ! defined( 'HTML_EOL' ) ) {
	define( 'HTML_EOL', '<br>' . PHP_EOL );
}
if ( ! defined( 'STAQ_ROOT_PATH' ) ) {
	define( 'STAQ_ROOT_PATH', dirname( __DIR__ ) . '/' );
}

require_once( __DIR__ . '/util/functions.php' );
require_once( __DIR__ . '/core/Server.php' );
require_once( __DIR__ . '/core/Application.php' );
require_once( __DIR__ . '/core/Autoloader.php' );

Add new shorthand static methods to access to the current application


<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width" />

	<title>{{ HTML::title() }}</title>

	<?php

	$asset = Asset::container('cello.frontend');

	$asset->style('foundation', 'bundles/orchestra/vendor/foundation/stylesheets/foundation.min.css');
	$asset->script('foundation', 'bundles/orchestra/vendor/foundation/javascripts/foundation.min.js'); ?>

	{{ $asset->styles() }}
	{{ $asset->scripts() }}

{{ memorize('site.name') }}

{{ memorize('site.description') }}

	@yield('content')

<!DOCTYPE html>

	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width" />

	<title>{{ HTML::title() }}</title>

	<?php

	$asset = Asset::container('cello.frontend');

	$asset->style('foundation', 'bundles/orchestra/vendor/foundation/css/foundation.min.css');
	$asset->script('foundation', 'bundles/orchestra/vendor/foundation/js/foundation.min.js'); ?>

	{{ $asset->styles() }}
	{{ $asset->scripts() }}

{{ memorize('site.name') }}

{{ memorize('site.description') }}

	@yield('content')

Update foundation asset and fixed minor html syntax error.

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

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

class RestructurePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('subtitle')->after('title');
            $table->renameColumn('content', 'content_raw');
            $table->text('content_html')->after('content');
            $table->string('page_image')->after('content_html');
            $table->string('meta_description')->after('page_image');
            $table->boolean('is_draft')->after('meta_description');
            $table->string('layout')->after('is_draft')->default('frontend.blog.post');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('layout');
            $table->dropColumn('is_draft');
            $table->dropColumn('meta_description');
            $table->dropColumn('page_image');
            $table->dropColumn('content_html');
            $table->renameColumn('content_raw', 'content');
            $table->dropColumn('subtitle');
        });
    }
}

<?php

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

class RestructurePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('subtitle')->after('title')->default('');
            $table->renameColumn('content', 'content_raw');
            $table->text('content_html')->after('content')->default('');
            $table->string('page_image')->after('content_html')->default('');
            $table->string('meta_description')->after('page_image')->default('');
            $table->boolean('is_draft')->after('meta_description')->default(false);
            $table->string('layout')->after('is_draft')->default('frontend.blog.post');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('layout');
            $table->dropColumn('is_draft');
            $table->dropColumn('meta_description');
            $table->dropColumn('page_image');
            $table->dropColumn('content_html');
            $table->renameColumn('content_raw', 'content');
            $table->dropColumn('subtitle');
        });
    }
}

Add default values to posts table migration

Add default values to all new columns in the posts table restructuring
migration so that these migrations can be run on an sqlite database.

Fixes #22


<?php

namespace Omnipay\MultiSafepay\Message;

use Mockery as m;
use Omnipay\Tests\TestCase;
use ReflectionMethod;

class AbstractRequestTest extends TestCase
{
    /**
     * @var AbstractRequest
     */
    private $request;

    protected function setUp()
    {
        $this->request = m::mock('\Omnipay\MultiSafepay\Message\AbstractRequest[getData,sendData]');
    }

    /**
     * @covers \Omnipay\MultiSafepay\Message\AbstractRequest::getHeaders()
     */
    public function testUserAgentHeaderMustNotBeSet()
    {
        $method = new ReflectionMethod('\Omnipay\MultiSafepay\Message\AbstractRequest', 'getHeaders');
        $method->setAccessible(true);

        $headers = $method->invoke($this->request);
        $this->assertArrayHasKey('User-Agent', $headers, 'Omitting User-Agent header not allowed because then Guzzle will set it and cause 403 Forbidden on the gateway');
        $this->assertEquals('Omnipay', $headers['User-Agent'], 'User-Agent header set');
    }
}

<?php

namespace Omnipay\MultiSafepay\Message;

use Mockery as m;
use Omnipay\Tests\TestCase;
use ReflectionMethod;

class AbstractRequestTest extends TestCase
{
    /**
     * @var AbstractRequest
     */
    private $request;

    protected function setUp()
    {
        $this->request = m::mock('\Omnipay\MultiSafepay\Message\AbstractRequest')->makePartial();
    }

    /**
     * @covers \Omnipay\MultiSafepay\Message\AbstractRequest::getHeaders()
     */
    public function testUserAgentHeaderMustNotBeSet()
    {
        $method = new ReflectionMethod('\Omnipay\MultiSafepay\Message\AbstractRequest', 'getHeaders');
        $method->setAccessible(true);

        $headers = $method->invoke($this->request);
        $this->assertArrayHasKey('User-Agent', $headers, 'Omitting User-Agent header not allowed because then Guzzle will set it and cause 403 Forbidden on the gateway');
        $this->assertEquals('Omnipay', $headers['User-Agent'], 'User-Agent header set');
    }
}

Fix tests for Mockery 0.9

Fix tests for Mockery 0.9


<?php

namespace Lexik\Bundle\FormFilterBundle\Filter\Extension\Type;

use Doctrine\ORM\QueryBuilder;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Lexik\Bundle\FormFilterBundle\Filter\Expr;

/**
 * Filter type for select list.
 *
 * @author Cédric Girard <c.girard@lexik.fr>
 */
class ChoiceFilterType extends AbstractFilterType implements FilterTypeInterface
{
    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'choice';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'filter_choice';
    }

    /**
     * {@inheritdoc}
     */
    public function getTransformerId()
    {
        return 'lexik_form_filter.transformer.default';
    }

    /**
     * {@inheritdoc}
     */
    public function applyFilter(QueryBuilder $queryBuilder, Expr $expr, $field, array $values)
    {
        if (!empty($values['value'])) {
            $queryBuilder->andWhere($expr->eq($field, ':value'))
                         ->setParameter('value', $values['value']);
        }
    }
}

<?php

namespace Lexik\Bundle\FormFilterBundle\Filter\Extension\Type;

use Doctrine\ORM\QueryBuilder;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Lexik\Bundle\FormFilterBundle\Filter\Expr;

/**
 * Filter type for select list.
 *
 * @author Cédric Girard <c.girard@lexik.fr>
 */
class ChoiceFilterType extends AbstractFilterType implements FilterTypeInterface
{
    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'choice';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'filter_choice';
    }

    /**
     * {@inheritdoc}
     */
    public function getTransformerId()
    {
        return 'lexik_form_filter.transformer.default';
    }

    /**
     * {@inheritdoc}
     */
    public function applyFilter(QueryBuilder $queryBuilder, Expr $expr, $field, array $values)
    {
        if (!empty($values['value'])) {
            // alias.field -> alias_field
            $fieldName = str_replace('.', '_', $field);

            $queryBuilder->andWhere($expr->eq($field, ':' . $fieldName))
                         ->setParameter($fieldName, $values['value']);
        }
    }
}

Fix a problem with multiple choice fields in a query


<?php

require_once 'Swat/SwatFlydownOption.php';

/**
 * A class representing a divider in a flydown
 *
 * This class is for semantic purposed only. The flydown handles all the
 * displaying of dividers and regular flydown options.
 *
 * @package   Swat
 * @copyright 2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatFlydownDivider extends SwatFlydownOption
{
	/**
	 * Creates a flydown option
	 *
	 * @param mixed $value value of the option.
	 * @param string $title displayed title of the divider. This defaults to
	 *                       two em dashes.
	 */
	public function __construct($value, $title = '——')
	{
		$this->value = $value;
		$this->title = $title;
	}
}

?>

<?php

require_once 'Swat/SwatFlydownOption.php';

/**
 * A class representing a divider in a flydown
 *
 * This class is for semantic purposed only. The flydown handles all the
 * displaying of dividers and regular flydown options.
 *
 * @package   Swat
 * @copyright 2005 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatFlydownDivider extends SwatFlydownOption
{
	/**
	 * Creates a flydown option
	 *
	 * @param mixed $value value of the option.
	 * @param string $title displayed title of the divider. This defaults to
	 *                       two em dashes.
	 */
	public function __construct($value, $title = null)
	{
		if ($title === null)
			$title = str_repeat('—', 6);

		$this->value = $value;
		$this->title = $title;
	}
}

?>

Make longer line by default for divider option.

svn commit r2832


<?php
defined('C5_EXECUTE') or die(_("Access Denied."));
echo $this->controller->getOpenTag();
echo $this->controller->getTitle();
$format = (strlen($this->controller->dateFormat)?$this->controller->dateFormat:"m/d/y");
echo date($format,strtotime($this->controller->getContent()));
echo $this->controller->getCloseTag();

<?php
defined('C5_EXECUTE') or die(_("Access Denied."));
$dh = Core::make('helper/date'); /* @var $dh \Concrete\Core\Localization\Service\Date */
echo $this->controller->getOpenTag();
echo $this->controller->getTitle();
$format = (strlen($this->controller->dateFormat)?$this->controller->dateFormat:"m/d/y");
echo $dh->formatCustom($format, $this->controller->getContent());
echo $this->controller->getCloseTag();

Use date helper in date time template of page_attribute_display block

Makes use of correct locale on multilingual websites

Former-commit-id: ec2a56f5e9ae5eb51a31db1e72473270502c7084


<?php

namespace MaxBrokman\SafeQueue;

use Illuminate\Support\ServiceProvider;
use MaxBrokman\SafeQueue\Console\WorkCommand;

class DoctrineQueueProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerWorker();
    }

    /**
     * @return void
     */
    protected function registerWorker()
    {
        $this->registerWorkCommand();

        $this->app->singleton('safeQueue.worker', function ($app) {
            return new Worker($app['queue'], $app['queue.failer'], $app['events'], $app['em']);
        });
    }

    /**
     * @return void
     */
    protected function registerWorkCommand()
    {
        $this->app->singleton('command.safeQueue.work', function ($app) {
            return new WorkCommand($app['safeQueue.worker']);
        });

        $this->commands('command.safeQueue.work');
    }
}

<?php

namespace MaxBrokman\SafeQueue;

use Illuminate\Support\ServiceProvider;
use MaxBrokman\SafeQueue\Console\WorkCommand;

/
class DoctrineQueueProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerWorker();
    }

    /**
     * @return void
     */
    protected function registerWorker()
    {
        $this->registerWorkCommand();

        $this->app->singleton('safeQueue.worker', function ($app) {
            return new Worker($app['queue'], $app['queue.failer'], $app['events'], $app['em'], new Stopper());
        });
    }

    /**
     * @return void
     */
    protected function registerWorkCommand()
    {
        $this->app->singleton('command.safeQueue.work', function ($app) {
            return new WorkCommand($app['safeQueue.worker']);
        });

        $this->commands('command.safeQueue.work');
    }
}

Fix service provider not giving `Stopper` to the worker


<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2019, 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 / App / System / Module / User / Controller
 */

namespace PH7;

use PH7\Framework\Module\Various as SysMod;
use PH7\Framework\Mvc\Router\Uri;
use PH7\Framework\Url\Header;

class AccountController extends Controller
{
    public function index()
    {
        // Redirect this page to the user homepage
        if (SysMod::isEnabled('user-dashboard')) {
            $sUrl = Uri::get('user-dashboard', 'main', 'index');
        } else {
            $sUrl = Uri::get('user', 'main', 'index');
        }

        Header::redirect($sUrl);
    }

    /**
     * @param string $sMail
     * @param string $sHash
     *
     * @return void
     */
    public function activate($sMail, $sHash)
    {
        (new UserCore)->activateAccount(
            $sMail,
            $sHash,
            $this->config,
            $this->registry
        );
    }
}

<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2019, 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 / App / System / Module / User / Controller
 */

namespace PH7;

use PH7\Framework\Module\Various as SysMod;
use PH7\Framework\Mvc\Router\Uri;
use PH7\Framework\Url\Header;

class AccountController extends Controller
{
    public function index()
    {
        Header::redirect($this->getHomepageUrl());
    }

    /**
     * @param string $sMail
     * @param string $sHash
     *
     * @return void
     */
    public function activate($sMail, $sHash)
    {
        (new UserCore)->activateAccount(
            $sMail,
            $sHash,
            $this->config,
            $this->registry
        );
    }

    /**
     * Redirect this page to the user homepage.
     *
     * @return string
     */
    private function getHomepageUrl()
    {
        if (SysMod::isEnabled('user-dashboard')) {
            return Uri::get('user-dashboard', 'main', 'index');
        }

        return Uri::get('user', 'main', 'index');
    }
}

[Readability] Create clear method that returns User Homepage URL


<?php

namespace Frontend\Modules\Profiles\Tests\Engine;

use Common\WebTestCase;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Profiles\Engine\Authentication;
use Frontend\Modules\Profiles\Tests\DataFixtures\LoadProfiles;
use SpoonDatabase;

final class AuthenticationTest extends WebTestCase
{
    /** @var SpoonDatabase */
    private $database;

    public function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Frontend');
        }

        $client = self::createClient();
        $this->loadFixtures($client, [LoadProfiles::class]);

        $this->database = FrontendModel::get('database');
    }

    public function testOldSessionCleanUp()
    {
        $this->assertEquals('2', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));

        Authentication::cleanupOldSessions();

        $this->assertEquals('1', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
    }
}

<?php

namespace Frontend\Modules\Profiles\Tests\Engine;

use Common\WebTestCase;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Profiles\Engine\Authentication;
use Frontend\Modules\Profiles\Tests\DataFixtures\LoadProfiles;
use SpoonDatabase;

final class AuthenticationTest extends WebTestCase
{
    /** @var SpoonDatabase */
    private $database;

    public function setUp(): void
    {
        parent::setUp();

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Frontend');
        }

        $client = self::createClient();
        $this->loadFixtures($client, [LoadProfiles::class]);

        $this->database = FrontendModel::get('database');
    }

    public function testOldSessionCleanUp()
    {
        $this->assertEquals('2', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));

        Authentication::cleanupOldSessions();

        $this->assertEquals('1', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
    }

    public function testGettingLoginStatusForNonExistingUser()
    {
        $this->assertEquals('invalid', Authentication::getLoginStatus('non@existe.nt', 'wrong'));
    }

    public function testGettingLoginStatusForUserWithWrongPassword()
    {
        $this->assertEquals('invalid', Authentication::getLoginStatus('test-active@fork-cms.com', 'wrong'));
    }

    public function testGettingLoginStatusForActiveUserWithCorrectPassword()
    {
        $this->assertEquals('active', Authentication::getLoginStatus('test-active@fork-cms.com', 'forkcms'));
    }

    public function testGettingLoginStatusForInactiveUserWithCorrectPassword()
    {
        $this->assertEquals('inactive', Authentication::getLoginStatus('test-inactive@fork-cms.com', 'forkcms'));
    }

    public function testGettingLoginStatusForDeletedUserWithCorrectPassword()
    {
        $this->assertEquals('deleted', Authentication::getLoginStatus('test-deleted@fork-cms.com', 'forkcms'));
    }

    public function testGettingLoginStatusForBlockedUserWithCorrectPassword()
    {
        $this->assertEquals('blocked', Authentication::getLoginStatus('test-blocked@fork-cms.com', 'forkcms'));
    }
}

Test getting the login status of a profile


<?php
namespace App\Service;

use App\Entity\Award;
use App\Entity\Config;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;

class PredictionService
{
    /** @var EntityManagerInterface */
    private $em;

    /** @var Config */
    private $config;

    public function __construct(EntityManagerInterface $em, ConfigService $configService)
    {
        $this->em = $em;
        $this->config = $configService->getConfig();
    }

    public function arePredictionsLocked()
    {
        if ($this->config->isReadOnly()) {
            return true;
        }

        if (!$this->config->getStreamTime()) {
            return false;
        }

        return new DateTime('+24 hours') > $this->config->getStreamTime();
    }

    public function areResultsAvailable()
    {
        return $this->config->isPagePublic('results');
    }

    public function isAwardResultAvailable(Award $award)
    {
        return $this->areResultsAvailable();
    }
}

<?php
namespace App\Service;

use App\Entity\Award;
use App\Entity\Config;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;

class PredictionService
{
    /** @var EntityManagerInterface */
    private $em;

    /** @var Config */
    private $config;

    public function __construct(EntityManagerInterface $em, ConfigService $configService)
    {
        $this->em = $em;
        $this->config = $configService->getConfig();
    }

    public function arePredictionsLocked()
    {
        if ($this->config->isReadOnly()) {
            return true;
        }

        if (!$this->config->getStreamTime()) {
            return false;
        }

        return new DateTime('+14 days') > $this->config->getStreamTime();
    }

    public function areResultsAvailable()
    {
        return $this->config->isPagePublic('results');
    }

    public function isAwardResultAvailable(Award $award)
    {
        return $this->areResultsAvailable();
    }
}

Change prediction lock time to two weeks


<?php

namespace Dock\Cli;

use Dock\Docker\Compose\Project;
use Dock\Project\ProjectManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ResetCommand extends Command
{
    /**
     * @var ProjectManager
     */
    private $projectManager;

    /**
     * @var Project
     */
    private $project;

    /**
     * @param ProjectManager $projectManager
     * @param Project        $project
     */
    public function __construct(ProjectManager $projectManager, Project $project)
    {
        parent::__construct();

        $this->projectManager = $projectManager;
        $this->project = $project;
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('reset')
            ->setDescription('Reset the containers of the project')
            ->addArgument('container', InputArgument::IS_ARRAY, 'Component names')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $containers = $input->getArgument('container');
        $this->projectManager->reset($this->project, $containers);

        $output->writeln([
            'Container(s) successfully reset.',
        ]);
    }
}

<?php

namespace Dock\Cli;

use Dock\Docker\Compose\Project;
use Dock\Project\ProjectManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ResetCommand extends Command
{
    /**
     * @var ProjectManager
     */
    private $projectManager;

    /**
     * @var Project
     */
    private $project;

    /**
     * @param ProjectManager $projectManager
     * @param Project        $project
     */
    public function __construct(ProjectManager $projectManager, Project $project)
    {
        parent::__construct();

        $this->projectManager = $projectManager;
        $this->project = $project;
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('reset')
            ->setDescription('Reset the containers of the project')
            ->addArgument('container', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'Component names')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $containers = $input->getArgument('container');
        $this->projectManager->reset($this->project, $containers);

        $output->writeln([
            'Container(s) successfully reset.',
        ]);
    }
}

Enforce requirement for build and reset arguments


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

namespace ZendTest\Code\Generator;

use Zend\Code\Generator\AbstractMemberGenerator;
use Zend\Code\Generator\Exception\InvalidArgumentException;

class AbstractMemberGeneratorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var AbstractMemberGenerator
     */
    private $fixture;

    protected function setUp()
    {
        $this->fixture = $this->getMockForAbstractClass('Zend\Code\Generator\AbstractMemberGenerator');
    }

    public function testSetFlagsWithArray()
    {
        $this->fixture->setFlags(
            array(
                AbstractMemberGenerator::FLAG_FINAL,
                AbstractMemberGenerator::FLAG_PUBLIC,
            )
        );

        $this->assertEquals(AbstractMemberGenerator::VISIBILITY_PUBLIC, $this->fixture->getVisibility());
        $this->assertEquals(true, $this->fixture->isFinal());
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testSetDocBlockThrowsExceptionWithInvalidType()
    {
        $this->fixture->setDocBlock(new \stdClass());
    }
}

Fix errors reported by php-cs-fixer

Fix errors reported by php-cs-fixer


<?php

namespace Zeropingheroes\Lanager\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Zeropingheroes\Lanager\Http\Controllers\Controller;
use Zeropingheroes\Lanager\Http\Resources\Lan as LanResource;
use Zeropingheroes\Lanager\Lan;

class LanController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return AnonymousResourceCollection
     */
    public function index()
    {
        return LanResource::collection(Lan::orderBy('start', 'desc')->get());
    }

    /**
     * Display the specified resource.
     *
     * @param  Lan     $lan
     * @param  Request $request
     * @return LanResource
     */
    public function show(Lan $lan, Request $request)
    {
        if ($request->has('users')) {
            $lan->load('users');
        }
        if ($request->has('events')) {
            $lan->load('events');
        }
        if ($request->has('slides')) {
            $lan->load('slides');
        }

        return new LanResource($lan);
    }
}

<?php

namespace Zeropingheroes\Lanager\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Zeropingheroes\Lanager\Http\Controllers\Controller;
use Zeropingheroes\Lanager\Http\Resources\Lan as LanResource;
use Zeropingheroes\Lanager\Lan;

class LanController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return AnonymousResourceCollection
     */
    public function index()
    {
        $lans = Lan::where('published', true)
            ->orderBy('start', 'desc')
            ->get();

        return LanResource::collection($lans);
    }

    /**
     * Display the specified resource.
     *
     * @param  Lan     $lan
     * @param  Request $request
     * @return LanResource
     */
    public function show(Lan $lan, Request $request)
    {
        if (!$lan->published) {
            throw new NotFoundHttpException();
        }

        if ($request->has('users')) {
            $lan->load('users');
        }
        if ($request->has('events')) {
            $lan->load('events');
        }
        if ($request->has('slides')) {
            $lan->load('slides');
        }

        return new LanResource($lan);
    }
}

Hide unpublished LANs from API

Hide unpublished LANs from API


<?php

namespace Oro\Bundle\SecurityBundle\Cache;

class OroDataCacheManager
{
    /**
     * @var array
     */
    protected $cacheProviders = [];

    /**
     * Registers a cache provider in this manager
     *
     * @param object $cacheProvider
     */
    public function registerCacheProvider($cacheProvider)
    {
        $this->cacheProviders[] = $cacheProvider;
    }

    /**
     * Makes sure all cache providers are synchronized
     * Call this method in main process if you need to get data modified in a child process
     */
    public function sync()
    {
        foreach ($this->cacheProviders as $cacheProvider) {
            if ($cacheProvider instanceof SyncCacheInterface) {
                $cacheProvider->sync();
                var_dump($cacheProvider->getNamespace());
            }
        }
    }
}

<?php

namespace Oro\Bundle\SecurityBundle\Cache;

class OroDataCacheManager
{
    /**
     * @var array
     */
    protected $cacheProviders = [];

    /**
     * Registers a cache provider in this manager
     *
     * @param object $cacheProvider
     */
    public function registerCacheProvider($cacheProvider)
    {
        $this->cacheProviders[] = $cacheProvider;
    }

    /**
     * Makes sure all cache providers are synchronized
     * Call this method in main process if you need to get data modified in a child process
     */
    public function sync()
    {
        foreach ($this->cacheProviders as $cacheProvider) {
            if ($cacheProvider instanceof SyncCacheInterface) {
                $cacheProvider->sync();
            }
        }
    }
}

BAP-3701: Package Manager Exception during installing or updating


<?php

require_once 'Site/SitePath.php';

/**
 * @package   Site
 * @copyright 2007 silverorange
 */
class SiteArticlePath extends SitePath
{
	// {{{ public function __construct()

	/**
	 * Creates a new article path object
	 *
	 * @param SiteWebApplication $app the application this path exists in.
	 * @param integer $id the database id of the object to create the path for.
	 *                     If no database id is specified, an empty path is
	 *                     created.
	 */
	public function __construct(SiteWebApplication $app, $id = null)
	{
		if ($id !== null)
			$this->loadFromId($app, $id);
	}

	// }}}
	// {{{ protected function loadFromId()

	/**
	 * Creates a new path object
	 *
	 * @param integer $article_id.
	 */
	public function loadFromId(SiteWebApplication $app, $article_id)
	{
		foreach ($this->queryPath($app, $article_id) as $row)
			$this->addEntry(new SitePathEntry(
				$row->id, $row->parent, $row->shortname, $row->title));
	}

	// }}}
	// {{{ protected function queryPath()

	protected function queryPath($app, $article_id)
	{
		$sql = sprintf('select * from getArticlePathInfo(%s)',
			$app->db->quote($article_id, 'integer'));

		return SwatDB::query($app->db, $sql);
	}

	// }}}
}

?>

<?php

require_once 'Site/SitePath.php';

/**
 * @package   Site
 * @copyright 2007 silverorange
 */
class SiteArticlePath extends SitePath
{
	// {{{ public function __construct()

	/**
	 * Creates a new article path object
	 *
	 * @param SiteWebApplication $app the application this path exists in.
	 * @param integer $id the database id of the object to create the path for.
	 *                     If no database id is specified, an empty path is
	 *                     created.
	 */
	public function __construct(SiteWebApplication $app, $id = null)
	{
		if ($id !== null)
			$this->loadFromId($app, $id);
	}

	// }}}
	// {{{ protected function loadFromId()

	/**
	 * Creates a new path object
	 *
	 * @param integer $article_id.
	 */
	public function loadFromId(SiteWebApplication $app, $article_id)
	{
		foreach ($this->queryPath($app, $article_id) as $row)
			$this->addEntry(new SitePathEntry(
				$row->id, $row->parent, $row->shortname, $row->title));
	}

	// }}}
	// {{{ protected function queryPath()

	protected function queryPath($app, $article_id)
	{
		return SwatDB::executeStoredProc($app->db, 'getArticlePathInfo',
			$article_id);
	}

	// }}}
}

?>

Use SwatDB's abstraction so that this function will work with both PostgreSQL and MySQL.

svn commit r36046


<?php defined('SYSPATH') or die('No direct access allowed.');

return array(

	/**
	 * The file extension used for TAL view files.
	 */
	'ext' => 'php',

);

<?php defined('SYSPATH') or die('No direct access allowed.');

return array(

	/**
	 * The file extension used for TAL view files. Default is 'php'.
	 */
	'ext' => 'php',

);

Update file extension config comment.

Update file extension config comment.