<?php namespace ForeverPHP\Http;

/**
 * Permite obtener informacion del cliente
 *
 * @author      Daniel Nuñez S. <dnunez@emarva.com>
 * @since       Version 0.2.0
 */
class Host {
    /**
     * Instancia singleton de Host.
     *
     * @var \ForeverPHP\Http\Host
     */
    private static $instance;

    public function __construct() {}

    /**
     * Obtiene o crea la instacia singleton de Host
     *
     * @return \ForeverPHP\Http\Host
     */
    public static function getInstance() {
        if (is_null(static::$instance)) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    /**
     * Obtiene la IP del huesped.
     *
     * @return string
     */
    public function getIP() {
        $ip = "UNKNOWN";

        if (getenv("HTTP_CLIENT_IP")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } else if(getenv("HTTP_X_FORWARDED_FOR")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } else if(getenv("REMOTE_ADDR")) {
            $ip = getenv("REMOTE_ADDR");
        }

        return $ip;
    }

    /**
     * Obtiene el nombre del huesped.
     *
     * @return string
     */
    public function getName() {
        return gethostbyaddr(getenv('REMOTE_ADDR'));
    }

    /**
     * Obtiene informacion del navegador del huesped.
     *
     * @param  integer $lenght
     * @return string
     */
    public function getUserAgent($lenght) {
        return substr(getenv('HTTP_USER_AGENT'), 0, $lenght);
    }
}


<?php
namespace FelixOnline\Base;

use FelixOnline\Exceptions\InternalException;
use FelixOnline\Exceptions\DBConnectionException;

/**
 * App class
 */
class App implements \ArrayAccess
{
    protected static $instance = null;
    protected static $options = array();
    protected $container;

    const MODE_HTTP = 0;
    const MODE_CLI = 1;

    /**
     * Required options
     */
    protected $required = array(
        'db_name',
        'db_host',
        'db_user',
        'db_pass',
        'production'
    );

    /**
     * Constructor
     *
     * @param array $options - options array
     */
    public function __construct(
        $options = array()
    ) {
        $this->checkOptions($options);
        self::$options = $options;

        if (!isset(self::$options['app_name'])) {
            self::$options['app_name'] = 'BaseApp';
        }

        if (!isset(self::$options['app_version'])) {
            self::$options['app_version'] = '0.10pre';
        }

        if (!isset(self::$options['app_author'])) {
            self::$options['app_author'] = 'Felix Online';
        }

        unset($this->container);

        self::$instance = $this;
    }

    /**
     * Initialize app
     */
    public function run()
    {
        if (!$this->isRunningUnitTests())
        {
            $runner = new \League\BooBoo\Runner();

            if ($this->getMode() == self::MODE_HTTP) {
                $aFtr = new \League\BooBoo\Formatter\HtmlTableFormatter;
            } else {
                $aFtr = new \League\BooBoo\Formatter\CommandLineFormatter;
            }

            $null = new \League\BooBoo\Formatter\NullFormatter;

            if ($this->getOption('production')) {
                $aFtr->setErrorLimit(E_ERROR | E_USER_ERROR);
            } else {
                $aFtr->setErrorLimit(E_ERROR | E_WARNING | E_USER_ERROR | E_USER_WARNING);
            }
            $null->setErrorLimit(E_ALL);

            $runner->pushFormatter($null);
            $runner->pushFormatter($aFtr);

            if (
                !isset($this->container['sentry']) ||
                !($this->container['sentry'] instanceof \Raven_Client)
            ) {
                if (!isset(self::$options['sentry_dsn'])) {
                    $dsn = '';
                } else {
                    $dsn = self::$options['sentry_dsn'];
                }

                $app['sentry'] = new \Raven_Client($dsn);
            }

            $raven = new \League\BooBoo\Handler\RavenHandler($app['sentry']);
            $runner->pushHandler($raven);

            $runner->register();

            $this->container['booboo'] = $runner;
        } else {
            $this->container['booboo'] = null;
            $this->container['sentry'] = null;
        }

        if (
            !isset($this->container['env'])
            || is_null($this->container['env'])
        ) {
            if (
                $this->getMode() == self::MODE_HTTP ||
                $this->isRunningUnitTests()
            ) {
                try {
                    $this->getOption('base_url');
                } catch (\Exception $e) {
                    throw new InternalException('base_url must be set when running in a HTTP or Unit Test environment');
                }

                $this->container['env'] = new HttpEnvironment();
            } else {
                $this->container['env'] = new CliEnvironment();
            }
        }

        if (
            !isset($this->container['akismet']) ||
            is_null($this->container['akismet'])
        ) {
            // Initialize Akismet
            if (self::$options['production']) {
                $connector = new \Riv\Service\Akismet\Connector\Curl();
            } else {
                $connector = new \Riv\Service\Akismet\Connector\Test();
            }

            $this->container['akismet'] = new \Riv\Service\Akismet\Akismet($connector);
        }

        if (
            !isset($this->container['email']) ||
            is_null($this->container['email'])
        ) {
            // Initialize email
            if($this->isRunningUnitTests()) {
                $transport = \Swift_NullTransport::newInstance();
            } else {
                $transport = \Swift_MailTransport::newInstance(); // This is removed in swiftmailer 6, FIXME
            }

            $this->container['email'] = \Swift_Mailer::newInstance($transport);
        }

        if (
            !isset($this->container['cache']) ||
            is_null($this->container['cache'])
        ) {
            if (!(self::$options['production'])) {
                $driver = new \Stash\Driver\BlackHole();
            } else {
                if (!isset(self::$options['stash_cache_folder'])) {
                    $driver = new \Stash\Driver\FileSystem(array('path' => self::$options['stash_cache_folder']));
                } else {
                    $driver = new \Stash\Driver\FileSystem();
                }
            }

            $this->container['cache'] = new \Stash\Pool($driver);
        }

        if (
            !isset($this->container['currentuser'])
            || is_null($this->container['currentuser'])
            || !($this->container['currentuser'] instanceof AbstractCurrentUser)
        ) {
            $this->container['currentuser'] = new StubCurrentUser();
        }

        if (
            !isset($this->container['db']) ||
            !($this->container['db'] instanceof \ezSQL_mysqli)
        ) {
            if (isset(self::$options['db_port'])) {
                $port = self::$options['db_port'];
            } else {
                $port = null;
            }

            $db = new \ezSQL_mysqli();
            $status = @$db->quick_connect(
                self::$options['db_user'],
                self::$options['db_pass'],
                self::$options['db_name'],
                self::$options['db_host'],
                $port,
                'utf8'
            );

            if (!$status) {
                throw new DBConnectionException('Could not connect to database');
            }

            $db->show_errors();

            $this->container['db'] = $db;

            $this->container['db_log'] = array();
        }

        if (
            !isset($this->container['safesql']) ||
            !($this->container['safesql'] instanceof \SafeSQL_MySQLi)
        ) {
            $this->container['safesql'] = new \SafeSQL_MySQLi($this->container['db']->dbh);
        }
    }

    public function getMode()
    {
        if (php_sapi_name() == "cli") {
            return self::MODE_CLI;
        } else {
            return self::MODE_HTTP;
        }
    }

    public function isRunningUnitTests()
    {
        try {
            return $this->getOption('unit_tests');
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Check that all required options are defined
     *
     * Throws Exception if option is not defined
     */
    private function checkOptions($options)
    {
        foreach ($this->required as $req) {
            if (!array_key_exists($req, $options)) {
                throw new \Exception('"' . $req . '" option has not been defined');
            }
        }
    }

    /**
     * Get instance
     *
     * @return instance
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            throw new \Exception('App has not been initialised yet');
        }
        return self::$instance;
    }

    /**
     * Set instance
     *
     * @param object $instance - instance object to set
     *
     * @return void
     */
    public static function setInstance($instance)
    {
        self::$instance = $instance;
    }

    /**
     * Get option
     *
     * @param string $key - option key
     *
     * @return mixed option
     */
    public function getOption($key)
    {
        if (!array_key_exists($key, self::$options)) {
            // if a default has been defined
            if (func_num_args() > 1) {
                return func_get_arg(1);
            } else {
                throw new InternalException('Option "'.$key.'" has not been set');
            }
        }
        return self::$options[$key];
    }

    public function offsetSet($offset, $value)
    {
        $this->container[$offset] = $value;
    }

    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset)
    {
        if (!isset($this->container[$offset])) {
            throw new InternalException('Key "' . $offset . '" is not set');
        }
        return $this->container[$offset];
    }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP;

use ItePHP\Core\EventManager;
use ItePHP\Core\Presenter;
use ItePHP\Core\Request;
use ItePHP\Core\HTTPRequest;
use ItePHP\Provider\Session;
use ItePHP\Core\Environment;

use ItePHP\Error\ErrorManager;

use ItePHP\Core\HTTPException;
use ItePHP\Core\CriticalErrorHandler;
use ItePHP\Core\HTTPErrorHandler;
use ItePHP\Core\HTTPDispatcher;
use ItePHP\Core\Container;
use ItePHP\Core\ConsoleErrorHandler;
use ItePHP\Core\CommandNotFoundException;
use ItePHP\Core\ConsoleDispatcher;
use ItePHP\Structure\ImportStructure;
use ItePHP\Structure\Structure;
use ItePHP\Structure\VariableStructure;
use Onus\ClassLoader;
use Onus\MetadataClass;
use Onus\MetadataMethod;
use Pactum\ConfigBuilder;
use Pactum\ConfigBuilderObject;
use Pactum\ConfigBuilderValue;
use Pactum\ConfigContainer;
use Pactum\ParserProcess;
use Pactum\Reader\XMLReader;
use Via\Action\HTTPAction;
use Via\Action\StringAction;
use Via\RouteNotFoundException;
use Via\Router;

/**
 * Main class of project
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 * @version 0.4.0
 */
class Root{

	/**
	 *
	 * @var Container
	 */
	private $container;

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

	/**
	 *
	 * @var Environment
	 */
	private $environment;

	/**
	 *
	 * @var ErrorManager
	 */
	private $errorManager;

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

	/**
	 *
	 * @param array $command
	 * @return int
	 */
	public function executeCommand($command){
		//config
		$this->errorManager=new ErrorManager();
		$this->errorManager->addHandler(new ConsoleErrorHandler());
		$classLoader=new ClassLoader();

		$this->initConfig();

		$this->container=new Container($classLoader);
		$classLoader->addInstance('container',$this->container);
		$classLoader->addInstance('environment',$this->environment);
		$classLoader->addInstance('config',$this->config);

		$this->registerEventManager($classLoader);
		$this->registerServices($classLoader);
		$this->registerEvents($classLoader);
		$this->registerCommands($classLoader);

		//command
		$sigint=1;
		$commandName=$command[0];
		array_shift($command);
		$arguments=$command;
		try{
			$dispatcher=$this->createConsoleRouter($classLoader,$arguments)->createDispatcher($commandName);
			$dispatcher->execute();
			$sigint=0;
		}
		catch(RouteNotFoundException $e){
			$this->errorManager->exception(new CommandNotFoundException($commandName));
		}
		catch(\Exception $e){
			$this->errorManager->exception($e);
		}

		return $sigint;

	}

	/**
	 *
	 * @param string $url
	 */
	public function executeRequest($url){

		//config
		$this->errorManager=new ErrorManager();
		$this->errorManager->addHandler(new CriticalErrorHandler($this->environment));
		$classLoader=new ClassLoader();

		$this->initConfig();

		$this->container=new Container($classLoader);
		$classLoader->addInstance('container',$this->container);
		$classLoader->addInstance('environment',$this->environment);
		$classLoader->addInstance('config',$this->config);

		$this->registerServices($classLoader);
		$this->registerEventManager($classLoader);
		$this->registerEvents($classLoader);
		$this->registerPresenters($classLoader);

		//request
		$session=new Session($this->environment);
		$request=new HTTPRequest($url,$session);

        $classLoader->addInstance('request',$request);

		$this->reconfigureErrorManager($classLoader,$request);

		try{
			$dispatcher=$this->createHttpRouter($classLoader,$request)
                ->createDispatcher(new \Via\Action\HTTPRequest($request->getUrl(),$request->getType()));
			$dispatcher->execute();
		}
		catch(RouteNotFoundException $e){
			$this->errorManager->exception(new HTTPException(404,$e->getMessage()));
		}
		catch(\Exception $e){
			$this->errorManager->exception($e);
		}

	}

	/**
	 *
	 * @param string $name
	 * @return object
	 */
	public function getService($name){
		return $this->$this->container->getService($name);
	}

	/**
	 * Init framework config
	 */
	private function initConfig(){
		//config structure
		$structureConfig=new ConfigBuilder();

		$xmlReader=new XMLReader($this->environment->getConfigPath().'/structure.xml');
		$structureConfig->addReader($xmlReader);

        $structureConfig->addArray('structure',new ConfigBuilderValue("string"));

		$structureContainer=$structureConfig->parse();

		$xmlReader=new XMLReader($this->environment->getConfigPath().'/'.$this->environment->getName().'.xml');
		$mainConfig=new ConfigBuilder();
        $mainConfig->addReader($xmlReader);
        $mainConfig->addFilter(function (ParserProcess $process){//import
            if($process->getType()!=='string' || $process->getPath()!=='root->import'){
                return;
            }

            $xmlReader=new XMLReader($this->environment->getConfigPath().'/'.$process->getValue());
            $process->addReader($xmlReader);

        });

        $variables=[];
        $mainConfig->addFilter(function (ParserProcess $process) use (&$variables){

            if($process->getType()!=='array' || $process->getPath()!=='root->variable') {
                return;
            }
            /**
             * @var ConfigBuilderObject $value
             */
            foreach($process->getValue() as $value){
                $variables[$value->getValue('name')]=$value->getValue('value');
            }

        });

        $mainConfig->addFilter(function (ParserProcess $process) use(&$variables){
            if(in_array($process->getType(),['string','boolean','mixed','number']) && is_string($process->getValue())){

                $value=$process->getValue();
                preg_match_all('/@\{(.+?)\}/',$process->getValue(),$matches);
                for($i=0; $i<count($matches[0]); $i++){
                    if(is_string($variables[$matches[1][$i]]) && $value!==$matches[0][$i]){
                        $value=str_replace($matches[0][$i],$variables[$matches[1][$i]],$value);
                        continue;
                    }
                    $value=$variables[$matches[1][$i]];

                }
                $process->setValue($value);

            }
        });

        //config structure
        $importStructure=new ImportStructure();
        $importStructure->doConfig($mainConfig);

        $variableStructure=new VariableStructure();
        $variableStructure->doConfig($mainConfig);

        //$xmlReader=new XMLReader($this->environment->getConfigPath().'/'.$importValue);

        foreach($structureContainer->getArray('structure') as $structureValue){
            /**
             * @var Structure $structureObj
             */
			$structureObj=new $structureValue();
			$structureObj->doConfig($mainConfig);
		}
		$this->config=$mainConfig->parse();
	}

	/**
	 *
	 * @param ClassLoader $classLoader
	 * @param Request $request
	 */
	private function reconfigureErrorManager(ClassLoader $classLoader, Request $request){
		$removeHandlers=$this->errorManager->getHandlers();

		$this->errorManager->addHandler(
			new HTTPErrorHandler(
				$classLoader,$request
			)
		);

		foreach($removeHandlers as $handler){
			$this->errorManager->removeHandler($handler);
		}

	}

	/**
	 *
	 * @param ClassLoader $classLoader
	 * @param Request $request
	 * @return Router
	 */
	private function createHttpRouter(ClassLoader $classLoader, Request $request){
		$router=new Router();
		$presenters=$this->getPresenters($classLoader);
		foreach($this->config->getArray('action') as $actionObject){
		    $this->addHttpMethodActions($router,$actionObject,$request,$presenters);
		}

		return $router;
	}

    /**
     * @param Router $router
     * @param ConfigContainer $actionNode
     * @param Request $request
     * @param Presenter[] $presenters
     */
	private function addHttpMethodActions($router,$actionNode,$request,$presenters){
        $path=$actionNode->getValue('path');
        $httpMethods=$actionNode->getValue('http-method');
	    foreach (explode(",",$httpMethods) as $httpMethod){
            $router->addAction(new HTTPAction($path,$httpMethod),
                new HTTPDispatcher($actionNode,
                    $this->container,
                    $request,
                    $this->environment,
                    $presenters
                )
            );
        }

    }

	/**
	 *
	 * @param ClassLoader $classLoader
	 * @return array
	 */
	private function getPresenters(ClassLoader $classLoader){
		$presenters=[];
		foreach($this->config->getArray('presenter') as $presenterNode){
            /**
             * @var ConfigContainer $presenterNode
             */
			$presenters[$presenterNode->getValue('name')]=$classLoader->get('presenter.'.$presenterNode->getValue('name'));
		}

		return $presenters;
	}

	/**
	 *
	 * @param ClassLoader $classLoader
	 * @param array $commandArguments
	 * @return Router
	 */
	private function createConsoleRouter(ClassLoader $classLoader, $commandArguments){
		$router=new Router();

		foreach($this->config->getArray('command') as $commandNode){
            /**
             * @var ConfigContainer $commandNode
             */
			$router->addAction(new StringAction($commandNode->getValue('name')),
				new ConsoleDispatcher($commandNode,
					$classLoader,
					$commandArguments
				)
			);
		}

		return $router;
	}

	/**
	 *
	 * @param ClassLoader $classLoader
	 */
	private function registerEventManager(ClassLoader $classLoader){
		$metadataClass=new MetadataClass('eventManager',EventManager::class);
		$classLoader->register($metadataClass);
	}

    /**
     *
     * @param ClassLoader $classLoader
     */
	private function registerEvents(ClassLoader $classLoader){
		foreach($this->config->getArray('event') as $eventNode){
            /**
             * @var ConfigContainer $eventNode
             */

			$name=$eventNode->getValue('class');
			$metadataClass=$this->getMetadataClass($name,$eventNode);
			$classLoader->register($metadataClass);

			$this->eventManagerBind($eventNode,$classLoader);
		}
	}

	/**
	 *
	 * @param ClassLoader $classLoader
	 */
	private function registerServices(ClassLoader $classLoader){
		foreach($this->config->getArray('service') as $serviceNode){
            /**
             * @var ConfigContainer $serviceNode
             */
			$metadataClass=$this->getMetadataClass('service.'.$serviceNode->getValue('name'),$serviceNode,$serviceNode->getValue('singleton')==="true");
			$classLoader->register($metadataClass);
		}
	}

	/**
	 *
	 * @param ClassLoader $classLoader
	 */
	private function registerPresenters(ClassLoader $classLoader){
		foreach($this->config->getArray('presenter') as $presenterNode){
            /**
             * @var ConfigContainer $presenterNode
             */
			$metadataClass=$this->getMetadataClass('presenter.'.$presenterNode->getValue('name'),$presenterNode);
			$classLoader->register($metadataClass);
		}
	}

	/**
	 *
	 * @param ClassLoader $classLoader
	 */
	private function registerCommands(ClassLoader $classLoader){
		foreach($this->config->getArray('command') as $commandNode){
            /**
             * @var ConfigContainer $commandNode
             */
			$metadataClass=$this->getMetadataClass('command.'.$commandNode->getValue('name'),$commandNode);
			$classLoader->register($metadataClass);
		}
	}

	/**
	 *
	 * @param ConfigContainer $eventNode
	 * @param ClassLoader $classLoader
	 */
	private function eventManagerBind(ConfigContainer $eventNode,ClassLoader $classLoader){
		$eventManager=$this->container->getEventManager();
		foreach($eventNode->getArray('bind') as $bindNode){
            /**
             * @var ConfigContainer $bindNode
             */
			$eventManager->register(
				$bindNode->getValue('name'),
				$classLoader->get($eventNode->getValue('class')),
				$bindNode->getValue('method')
			);
		}
	}

    /**
     *
     * @param string $name
     * @param ConfigContainer $classNode
     * @param bool $singleton
     * @return MetadataClass
     */
	private function getMetadataClass($name,ConfigContainer $classNode,$singleton=true){
		$metadataClass=new MetadataClass($name,$classNode->getValue('class'),$singleton);
		foreach($classNode->getArray('method') as $methodNode){
			$metadataMethod=$this->getMetadataDependencyMethod($methodNode);
			$metadataClass->register($metadataMethod);
		}

		return $metadataClass;
	}

	/**
	 *
	 * @param ConfigContainer $methodNode
	 * @return MetadataMethod
	 */
	private function getMetadataDependencyMethod(ConfigContainer $methodNode){
		$metadataMethod=new MetadataMethod($methodNode->getValue('name'));
		foreach($methodNode->getArray('argument') as $argumentNode){
            /**
             * @var ConfigContainer $argumentNode
             */
			$metadataMethod->addArgument($argumentNode->getValue('type'),$argumentNode->getValue('value'));
		}

		return $metadataMethod;
	}

}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Validator;

/**
 * Validator for date
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class DateValidator extends ValidatorAbstract{

	/**
	 * {@inheritdoc}
	 */
	public function validate($value){
		$empty=false;

		try{
			$empty=$this->getOption('empty');
		}
		catch(ValueNotFoundException $e){
			//ignore
		}

		if(!$value && $empty){
			return null;
		}

		$d = \DateTime::createFromFormat('Y-m-d', $value);
	    if($d && $d->format('Y-m-d') == $value);
	    else
			return 'Invalid date format.';

        return null;
	}

}


<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\DependencyInjection;

use HWI\Bundle\OAuthBundle\HWIOAuthBundle;
use RunetId\Client\RunetIdClient;
use Ruwork\RunetIdBundle\Basket\Handler\HandlerInterface;
use Ruwork\RunetIdBundle\Basket\Loader\LoaderInterface;
use Ruwork\RunetIdBundle\Client\RunetIdClients;
use Ruwork\RunetIdBundle\HWIOAuth\ResourceOwner;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension;
use Symfony\Component\Validator\Validation;

final class RuworkRunetIdExtension extends ConfigurableExtension
{
    /**
     * {@inheritdoc}
     */
    protected function loadInternal(array $config, ContainerBuilder $container)
    {
        $locator = new FileLocator(__DIR__.'/../Resources/config');
        $loader = new PhpFileLoader($container, $locator);
        $loader->load('services.php');

        $container->registerForAutoconfiguration(LoaderInterface::class)
            ->setPrivate(true)
            ->addTag('ruwork_runet_id.basket_loader');

        $container->registerForAutoconfiguration(HandlerInterface::class)
            ->setPrivate(true)
            ->addTag('ruwork_runet_id.basket_handler');

        $clientReferences = [];

        foreach ($config['clients'] as $name => $clientConfig) {
            $clientReferences[$name] = $this->registerClient($container, $name, $clientConfig);
        }

        $clientAlias = new Alias('ruwork_runet_id.client.'.$config['default_client'], false);
        $container->setAlias(RunetIdClient::class, $clientAlias);
        $container->setAlias('ruwork_runet_id.client._default', $clientAlias);

        if (class_exists(HWIOAuthBundle::class)) {
            foreach ($clientReferences as $name => $reference) {
                $container
                    ->register('ruwork_runet_id.oauth.'.$name, ResourceOwner::class)
                    ->setPublic(false)
                    ->setArgument('$client', $reference);
            }

            $oauthAlias = new Alias('ruwork_runet_id.oauth.'.$config['default_client'], false);
            $container->setAlias('ruwork_runet_id.oauth._default', $oauthAlias);
        }

        $container
            ->findDefinition(RunetIdClients::class)
            ->setArguments([
                '$container' => ServiceLocatorTagPass::register($container, $clientReferences),
                '$defaultName' => $config['default_client'],
            ]);

        if (!class_exists(Validation::class)) {
            $container->removeDefinition('ruwork_runet_id.validator.unique_email');
        }
    }

    private function registerClient(ContainerBuilder $container, string $name, array $config): Reference
    {
        $id = 'ruwork_runet_id.client.'.$name;

        $definition = new ChildDefinition('ruwork_runet_id.client');
        $container
            ->setDefinition($id, $definition)
            ->setArguments([
                '$key' => $config['key'],
                '$secret' => $config['secret'],
                '$apiUri' => $config['api_uri'],
                '$oauthUri' => $config['oauth_uri'],
                '$plugins' => array_map(function (string $id) {
                    return new Reference($id);
                }, $config['plugins']),
                '$httpClient' => null === $config['http_client'] ? null : new Reference('http_client'),
            ]);

        return new Reference($id);
    }
}


<?php namespace Versatile\Geo;

use OverflowException;
use RangeException;
use Versatile\Geo\Contracts\Client;

class GoogleClient implements Client
{

    const   SUCCESS             = 'OK';
    const   BAD_REQUEST         = 'INVALID_REQUEST';
    const   UNKNOWN_ADDRESS     = 'ZERO_RESULTS';
    const   REQUEST_DENIED      = 'REQUEST_DENIED';
    const   TOO_MANY_QUERIES    = 'OVER_QUERY_LIMIT';

    protected $urls = [
        'geocode' => 'http://maps.google.com/maps/api/geocode/json'
    ];

    protected $maxRepeatedRequests = 10;

    /**
     * {@inheritdoc}
     *
     * @param string $method The method to call on the "WMS" server
     * @param array $params The parameters of the method
     * @return array The result
     **/
    public function fetch($method, array $params)
    {

        $url = $this->buildRequestUrl($method, $params);

        $recursionCounter = 0;

        while ($recursionCounter <= $this->maxRepeatedRequests) {

            try {
                return $this->getResponse($url);
            } catch (OverflowException $e) {
                $recursionCounter++;
                sleep(1);
                continue;
            }

        }

    }

    protected function getResponse($url)
    {

        $response = $this->parseResponse($this->sendRequest($url));

        switch ($response['status']) {

            case self::SUCCESS:
                return $response;
            case self::UNKNOWN_ADDRESS:
                throw new RangeException();
            case self::TOO_MANY_QUERIES:
                throw new OverflowException('Too many queries, ask later');

        }

        throw new RuntimeException("Google geocoder returned " . $response['status']);

    }

    protected function buildRequestUrl($method, array $params)
    {

        $url = $this->urls[$method];

        if ($method == 'geocode') {
            $params['sensor'] = 'false';
        }

        $query = http_build_query($params);

        return $url . '?' . $query;

    }

    protected function sendRequest($url)
    {
        return file_get_contents($url);
    }

    protected function parseResponse($jsonResponse)
    {
        return json_decode($jsonResponse, true);
    }

}


<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Predis\Command\Redis;

use Predis\Command\Command as RedisCommand;

/**
 * @link http://redis.io/commands/info
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class INFO extends RedisCommand
{
    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return 'INFO';
    }

    /**
     * {@inheritdoc}
     */
    public function parseResponse($data)
    {
        if (empty($data) || !$lines = preg_split('/\r?\n/', $data)) {
            return array();
        }

        if (strpos($lines[0], '#') === 0) {
            return $this->parseNewResponseFormat($lines);
        } else {
            return $this->parseOldResponseFormat($lines);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function parseNewResponseFormat($lines)
    {
        $info = array();
        $current = null;

        foreach ($lines as $row) {
            if ($row === '') {
                continue;
            }

            if (preg_match('/^# (\w+)$/', $row, $matches)) {
                $info[$matches[1]] = array();
                $current = &$info[$matches[1]];
                continue;
            }

            list($k, $v) = $this->parseRow($row);
            $current[$k] = $v;
        }

        return $info;
    }

    /**
     * {@inheritdoc}
     */
    public function parseOldResponseFormat($lines)
    {
        $info = array();

        foreach ($lines as $row) {
            if (strpos($row, ':') === false) {
                continue;
            }

            list($k, $v) = $this->parseRow($row);
            $info[$k] = $v;
        }

        return $info;
    }

    /**
     * Parses a single row of the response and returns the key-value pair.
     *
     * @param string $row Single row of the response.
     *
     * @return array
     */
    protected function parseRow($row)
    {
        list($k, $v) = explode(':', $row, 2);

        if (preg_match('/^db\d+$/', $k)) {
            $v = $this->parseDatabaseStats($v);
        }

        return array($k, $v);
    }

    /**
     * Extracts the statistics of each logical DB from the string buffer.
     *
     * @param string $str Response buffer.
     *
     * @return array
     */
    protected function parseDatabaseStats($str)
    {
        $db = array();

        foreach (explode(',', $str) as $dbvar) {
            list($dbvk, $dbvv) = explode('=', $dbvar);
            $db[trim($dbvk)] = $dbvv;
        }

        return $db;
    }
}


<?php
/**
 * @package WP_Enqueue_Util
 */

class WP_Enqueue_Options {

    /* Properties
    ---------------------------------------------------------------------------------- */

    /* Data
    ---------------------------------------------- */

    /**
     * The data to pass to JavaScript.
     *
     * This is accessable via the `$localization_name` in the global JavaScript namespace.
     *
     * @var mixed
     */
    private $data;

    /**
     * Get accessor method for data property.
     *
     * @return mixed
     */
    public function get_data() {

        return $this->data;

    }

    /**
     * Set accessor method for data property.
     *
     * @param mixed $value
     */
    public function set_data( $value ) {

        $this->data = $value;

    }

    /* Dependencies
    ---------------------------------------------- */

    /**
     * Scripts that need to be loaded before the script being enqueued.
     *
     * @var array
     */
    private $dependencies;

    /**
     * Get accessor method for dependencies property.
     *
     * @return array
     */
    public function get_dependencies() {

        return $this->dependencies;

    }

    /**
     * Set accessor method for dependencies property.
     *
     * @param array $value
     */
    public function set_dependencies( $value ) {

        $this->dependencies = $value;

    }

    /* Filename
    ---------------------------------------------- */

    /**
     * Filename of the file to enqueue.
     *
     * @var string
     */
    private $filename;

    /**
     * Get accessor method for filename property.
     *
     * @return string
     */
    public function get_filename() {

        return $this->filename;

    }

    /**
     * Set accessor method for filename property.
     *
     * @param string $value
     */
    public function set_filename( $value ) {

        $this->filename = $value;

    }

    /* Filename Debug
    ---------------------------------------------- */

    /**
     * Filename of the file to enqueue when debugging.
     *
     * @var string
     */
    private $filename_debug;

    /**
     * Get accessor method for filename debug property.
     *
     * @return string
     */
    public function get_filename_debug() {

        return $this->filename_debug;

    }

    /**
     * Set accessor method for filename property.
     *
     * @param string $value
     */
    public function set_filename_debug( $value ) {

        $this->filename_debug = $value;

    }

    /* Handle
    ---------------------------------------------- */

    /**
     * The handle the file should be enqueued with.
     *
     * @var string
     */
    private $handle;

    /**
     * Get accessor method for handle property.
     *
     * @return string
     */
    public function get_handle() {

        return $this->handle;

    }

    /**
     * Set accessor method for handle property.
     *
     * @param string $value
     */
    public function set_handle( $value ) {

        $this->handle = $value;

    }

    /* In Footer
    ---------------------------------------------- */

    /**
     * Whether the script should be enqueued in the head or footer.
     *
     * @var boolean
     */
    private $in_footer;

    /**
     * Get accessor method for in footer property.
     *
     * @return string
     */
    public function get_in_footer() {

        return $this->in_footer;

    }

    /**
     * Set accessor method for in footer property.
     *
     * @param boolean $value
     */
    public function set_in_footer( $value ) {

        $this->in_footer = $value;

    }

    /* Localization
    ---------------------------------------------- */

    /**
     * Convenience accessor for setting all localization properties.
     *
     * @param string $localization_name The global localization name to use in JavaScript.
     * @param mixed $data The data to pass to JavaScript.
     */
    public function set_localization( $localization_name, $data ) {

        $this->localization_name = $localization_name;
        $this->data = $data;

    }

    /* Localization Name
    ---------------------------------------------- */

    /**
     * The global localization name to use in JavaScript.
     *
     * @var string
     */
    private $localization_name;

    /**
     * Get accessor method for localization name property.
     *
     * @return string
     */
    public function get_localization_name() {

        return $this->localization_name;

    }

    /**
     * Set accessor method for handle property.
     *
     * @param string $value
     */
    public function set_localization_name( $value ) {

        $this->localization_name = $value;

    }

    /* Media
    ---------------------------------------------- */

    /**
     * Media for which the styles are for.
     *
     * @var string
     */
    private $media = 'all';

    /**
     * Get accessor method for media property.
     *
     * @return string
     */
    public function get_media() {

        return $this->media;

    }

    /**
     * Set accessor method for media property.
     *
     * @param string $value
     */
    public function set_media( $value ) {

        $this->media = $value;

    }

    /* Relative Path
    ---------------------------------------------- */

    /**
     * The relative path from `$directory_path` to `$filename`.
     *
     * @var string
     */
    private $relative_path;

    /**
     * Get accessor method for relative path property.
     *
     * @return string
     */
    public function get_relative_path() {

        return $this->relative_path;

    }

    /**
     * Set accessor method for relative path property.
     *
     * @param string $value
     */
    public function set_relative_path( $value ) {

        $this->relative_path = $value;

    }

    /* Version
    ---------------------------------------------- */

    /**
     * Version of the script to load, for cache busting.
     *
     * @var string
     */
    private $version;

    /**
     * Get accessor method for version property.
     *
     * @return string
     */
    public function get_version() {

        return $this->version;

    }

    /**
     * Set accessor method for version property.
     *
     * @param string $value
     */
    public function set_version( $value ) {

        $this->version = $value;

    }

    /* Constructor
    ---------------------------------------------------------------------------------- */

    /**
     * Initialize class.
     *
     * @param string $handle File handle.
     * @param string $relative_path Relative path to file.
     * @param string $filename Filename to load.
     * @param string $filename_debug Filename to load when debugging.
     * @param array $dependencies File dependencies
     * @param string $version File version.
     * @param boolean $in_footer Whether to load the file in the head or the footer.
     */
    function __construct( $handle, $relative_path, $filename, $filename_debug, $dependencies = array(), $version = '', $in_footer = false ) {

        $this->handle = $handle;
        $this->relative_path = $relative_path;
        $this->filename = $filename;
        $this->filename_debug = $filename_debug;
        $this->dependencies = $dependencies;
        $this->version = $version;
        $this->in_footer = $in_footer;

    }

    /* Helpers
    ---------------------------------------------------------------------------------- */

    /**
     * Determines if the enqueued options have required properties.
     *
     * @return boolean If the enqueued options have required properties.
     */
    public function have_required_properties() {

        return (
            ! empty( $this->handle )
            && ! empty( $this->relative_path )
            && ! empty( $this->filename )
        );

    }
}


<?php
/**
 * BSD 3-Clause License
 *
 * Copyright (c) 2019, TASoft Applications
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *  Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 *  Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

namespace Skyline\Compiler\Project\Attribute;

/**
 * Class AttributeCollection
 * @package Skyline\Compiler\Project\Attribute
 */
class AttributeCollection extends Attribute implements AttributeCollectionInterface
{
    private $attributes = [];

    /**
     * @return AttributeInterface[]
     */
    public function getAttributes(): array
    {
        return $this->attributes;
    }

    /**
     * @param string $name
     * @return AttributeInterface|null
     */
    public function getAttribute(string $name): ?AttributeInterface {
        return $this->attributes[$name] ?? NULL;
    }

    /**
     * Returns true, if an attribute exists
     *
     * @param string $name
     * @return bool
     */
    public function hasAttribute(string $name): bool {
        return isset($this->attributes[$name]);
    }

    /**
     * Adds an attribute to the list
     * Existing attributes are replaced.
     *
     * @param AttributeInterface $attribute
     */
    public function addAttribute(AttributeInterface $attribute) {
        if(isset($this->attributes[$attribute->getName()]))
            trigger_error("Attribute " . $attribute->getName() . " already exists", E_USER_NOTICE);

        $this->attributes[ $attribute->getName() ] = $attribute;
    }

    /**
     * Set new attributes
     * @param array $attributes
     */
    public function setAttributes(array $attributes) {
        foreach($attributes as $key => $attribute) {
            if(!($attribute instanceof AttributeInterface)) {
                if(is_array($attribute)) {
                    $attr = new AttributeCollection($key);
                    $attr->setAttributes($attribute);
                    $attribute = $attr;
                } else {
                    $attribute = new Attribute($key, $attribute);
                }
            }

            $this->attributes[ $attribute->getName() ] = $attribute;
        }
    }

    /**
     * Removes an attribute from collection
     *
     * @param string $attributeName
     */
    public function removeAttribute(string $attributeName) {
        if(isset($this->attributes[$attributeName]))
            unset($this->attributes[$attributeName]);
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\dataInterface\connectors\file;

use canis\helpers\ArrayHelper;
use Yii;

/**
 * DataSource data source for the file connectors.
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class DataSource extends \cascade\components\dataInterface\connectors\generic\DataSource
{
    /**
     * @inheritdoc
     */
    public $lazyForeign = false;
    /**
     * @inheritdoc
     */
    public $fieldMapClass = 'cascade\components\dataInterface\connectors\file\FieldMap';
    /**
     * @inheritdoc
     */
    public $dataItemClass = 'cascade\components\dataInterface\connectors\file\DataItem';
    /**
     * @inheritdoc
     */
    public $searchClass = 'cascade\components\dataInterface\connectors\file\Search';

    /**
     * @var string class name for foreign models
     */
    public $foreignModelClass = 'cascade\components\dataInterface\connectors\file\Model';

    /**
     * @var Source the file source for this connector
     */
    protected $_fileSource;

    /**
     * Set file source.
     *
     * @param Source|bool $value file source or false if not found
     */
    public function setFileSource($value)
    {
        if (isset($this->module->sourceFiles[$value])) {
            $this->_fileSource = $this->module->sourceFiles[$value];
        } else {
            $this->_fileSource = false;
        }
    }

    /**
     * Get file source.
     *
     * @return Source|bool the file source object or false if not found
     */
    public function getFileSource()
    {
        return $this->_fileSource;
    }

    /**
     * Get foreign data model.
     *
     * @param int|string $key the foreign model's primary key
     *
     * @return Model|false the foreign model or false if not found
     */
    public function getForeignDataModel($key)
    {
        return false;
    }

    /**
     * Get unmapped foreign keys.
     *
     * @return array the foreign keys that haven't been mapped
     */
    public function getUnmappedForeignKeys()
    {
        $mappedForeign = ArrayHelper::getColumn($this->_map, 'foreignKey');
        $u = array_diff(array_keys($this->foreignModel->meta->schema->columns), $mappedForeign);
        unset($u[$this->foreignPrimaryKeyName]);

        return $u;
    }

    /**
     * Load the data items from the file source.
     *
     * @return bool|null False on fail, null on success (@todo change this to true)
     */
    protected function loadForeignDataItems()
    {
        if (!$this->fileSource) {
            \d("boom");

            return false;
        }
        $foreignModelClass = $this->foreignModelClass;

        $lines = $this->fileSource->getLines($this->lazyForeign);
        $lineCount = 0;
        foreach ($lines as $id => $line) {
            if ($this->lazyForeign) {
                $this->createForeignDataItem(null, ['deferredModel' => $line]);
            } else {
                $model = $this->createModel($line->id, $line->attributes);
                $this->createForeignDataItem($model, ['deferredModel' => $line]);
            }
            $lineCount++;
        }
        $this->task->addInfo("Processed {$lineCount} lines from {$this->fileSource->id}");
    }

    /**
     * Create the model.
     *
     * @param string|int         $id         the primary key for the model
     * @param array $attributes attrribute for the model
     *
     * @return Model the foreign model
     */
    public function createModel($id, $attributes)
    {
        return Yii::createObject(['class' => $this->foreignModelClass, 'tableName' => $this->fileSource->id, 'interface' => $this->module, 'id' => $id, 'attributes' => $attributes]);
    }
}


<?php

namespace Colorium\Stateful\Provider;

use Colorium\Tools\ArrayDot;

class Repository extends Native
{

    /**
     * Check if value exists in session
     *
     * @param string $key
     * @return bool
     */
    public function has($key)
    {
        return ArrayDot::has($_SESSION[$this->root], $key);
    }

    /**
     * Get value in session
     *
     * @param string $key
     * @param mixed $fallback
     * @return mixed
     */
    public function get($key, $fallback = null)
    {
        return ArrayDot::get($_SESSION[$this->root], $key, $fallback);
    }

    /**
     * Set value in session
     *
     * @param string $key
     * @param mixed $value
     */
    public function set($key, $value)
    {
        ArrayDot::set($_SESSION[$this->root], $key, $value);
    }

    /**
     * Clear value in session
     *
     * @param string $key
     * @return bool
     */
    public function drop($key)
    {
        return ArrayDot::drop($_SESSION[$this->root], $key);
    }

}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Validator;

/**
 * Validator for number
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class BooleanValidator extends ValidatorAbstract{

	/**
	 * {@inheritdoc}
	 */
	public function validate($value){
		$empty=false;

		try{
			$empty=$this->getOption('empty');
		}
		catch(ValueNotFoundException $e){
			//ignore
		}

		if((!$value || $value=='false') && $empty){
			return null;
		}

		if(!in_array($value, array('true','on',true))){
			return "Invalid value.";
		}

		return null;
	}
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Core;

/**
 * Manager for events.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class EventManager{

	/**
	 * Environment.
	 *
	 * @var object[][] $events
	 */
	private $events=[];

	/**
	 * Register event.
	 *
	 * @param string $event event name
	 * @param object $obj
	 * @param string $methodName
	 */
	public function register($event,$obj,$methodName){
		$this->events+=[
			$event=>[
			]
		];
		$this->events[$event][]=[
			'object'=>$obj,
			'methodName'=>$methodName,
			];
	}

    /**
     * Execute event.
     *
     * @param $eventName
     * @param object $infoClass container with event info eg.: \ItePHP\Core\ExecutePresenterEvent
     * @internal param string $event event name
     */
	public function fire($eventName,$infoClass=null){
		if(isset($this->events[$eventName])){
			foreach($this->events[$eventName] as $bind=>$data){
				call_user_func_array([$data['object'], $data['methodName']], [$infoClass]);
			}
		}
		//FIXME throw exception?
	}

}


<?php

namespace Alc\Guzzle;

use Alc\HttpHeaders\HttpHeaders;

class GuzzleHelper
{
    protected $httpHeaders;

    protected $client;

    protected $options = array();

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->httpHeaders = new HttpHeaders();
        $this->setOptions($this->getDefaultOptions());
        $this->useChrome();
    }

    /**
     * Get default options
     *
     * @return array options
     */
    public function getDefaultOptions()
    {
        $options = array(
            'connect_timeout' => 15,
            'timeout' => 30,
        );

        return $options;
    }

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

    /**
     * Merge options
     *
     * @param array options
     */
    public function mergeOptions($options)
    {
        $this->setOptions(array_merge($this->getOptions(), $options));
    }

    /**
     * Get options
     *
     * @return array options
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Get new Client
     *
     * @return Client client
     */
    public function getNewClient()
    {
        $options = $this->getOptions();

        return new \GuzzleHttp\Client($options);
    }

    /**
     * Get Client
     *
     * @return Client client
     */
    public function getClient()
    {
        if ($this->client) {
            return $this->client;
        }

        return $this->client = $this->getNewClient();
    }

    /**
     * Reset Client
     *
     * @return Client client
     */
    public function resetClient()
    {
        $this->client = null;
    }

    /**
     * Use HTTP headers
     *
     * @param string name
     */
    public function useHeaders($name)
    {
        $headers = $this->httpHeaders->getHeaders($name);

        $this->mergeOptions(array('headers' => $headers));
    }

    /**
     * Use Chrome HTTP headers
     */
    public function useChrome()
    {
        $headers = $this->httpHeaders->getChrome();

        $this->mergeOptions(array('headers' => $headers));
    }

    /**
     * Use Firefox HTTP headers
     */
    public function useFirefox()
    {
        $headers = $this->httpHeaders->getFirefox();

        $this->mergeOptions(array('headers' => $headers));
    }

    /**
     * Perform GET request
     *
     * @param string url
     * @param array data
     *
     * @return string content
     */
    public function get($url, $data = array())
    {
        $client = $this->getClient();

        return $client->request('GET', $url, array('query' => $data));
    }

    /**
     * Perform POST request
     *
     * @param string url
     * @param array data
     *
     * @return string content
     */
    public function post($url, $data = array())
    {
        $client = $this->getClient();

        return $client->request('POST', $url, array('form_params' => $data));
    }
}


<?php
/**
 * CoolMS2 User Module (http://www.coolms.com/)
 *
 * @link      http://github.com/coolms/user for the canonical source repository
 * @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
 * @license   http://www.coolms.com/license/new-bsd New BSD License
 * @author    Dmitry Popov <d.popov@altgraphic.com>
 */

namespace CmsUser\Factory;

use Zend\ServiceManager\FactoryInterface,
    Zend\ServiceManager\ServiceLocatorInterface,
    Zend\Crypt\Password\Bcrypt,
    CmsUser\Options\PasswordOptionsInterface,
    CmsUser\Options\ModuleOptions;

class CryptoPasswordServiceFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     *
     * @return Bcrypt
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /* @var $options PasswordOptionsInterface */
        $options = $serviceLocator->get(ModuleOptions::class);
        return new Bcrypt(['cost' => $options->getPasswordCost()]);
    }
}


<?php

/**
 * Representation of date and time.
 *
 * @link https://php.net/manual/en/class.datetime.php DateTime
 */
class Benri_Util_DateTime extends DateTime
{
    /**
     * The format of the output date string.
     *
     * Valid formats are explained in
     * [Date and Time Formats](https://php.net/manual/en/datetime.formats.php).
     *
     * @var string
     */
    private $_format = parent::ISO8601;

    /**
    * Returns date formatted according to given format.
    *
    * If `$format` is `null`, it'll use `Benri_Util_DateTime::$_format`.
    *
    * @param string $format Format accepted by
    *  [date()](https://php.net/manual/en/function.date.php#refsect1-function.date-parameters)
    * @return string
    * @see Benri_Util_DateTime::setFormat() Benri_Util_DateTime::setFormat()
    */
    public function format($format = null)
    {
        if (null === $format) {
            $format = $this->_format;
        }

        return parent::format($format);
    }

    /**
     * Getter for `Benri_Util_DateTime::$_format` property.
     *
     * @return string
     */
    public function getFormat()
    {
        return $this->_format;
    }

    /**
     * Convert number of seconds into a DateInterval object.
     *
     * @param int $seconds Number of seconds to parse
     * @return DateInterval
     * @see DateInterval https://php.net/DateInterval
     */
    public static function secondsToInterval($seconds)
    {
        $epoch = new static('@0');

        return $epoch->diff(new static("@$seconds"));
    }

    /**
    * Setter for `Benri_Util_DateTime::$_format`.
    *
    * @param string $format Format accepted by
    *  [date()](https://php.net/manual/en/function.date.php#refsect1-function.date-parameters)
    * @return Benri_Util_DateTime
    */
    public function setFormat($format)
    {
        $this->_format = $format;

        return $this;
    }

    /**
    * Returns new Benri_Util_DateTime object.
    *
    * @param string $time A date/time string
    *   Format accepted by
    *   [date()](https://php.net/manual/en/function.date.php#refsect1-function.date-parameters).
    * @param DateTimeZone $timezone A
    *   [DateTimeZone](https://php.net/manual/en/class.datetimezone.php)
    *   object representing the timezone
    * @return Benri_Util_DateTime A new Benri_Util_DateTime instance
    * @see Benri_Util_DateTime::format() Benri_Util_DateTime::format()
    */
    public function __construct($time = 'now', DateTimeZone $timezone = null)
    {
        // PHP 5.6
        if (!$timezone) {
            $timezone = new DateTimeZone('UTC');
        }

        if (preg_match('/[\d+]{10}/', $time)) {
            $time = "@{$time}";
        }

        parent::__construct($time, $timezone);
    }

    /**
     * @return string
     * @see Benri_Util_DateTime::format() Benri_Util_DateTime::format()
     */
    public function __toString()
    {
        return $this->format();
    }
}


<?php
namespace DasRed\Translation\Command\Executor\Translation;

use Zend\Console\ColorInterface;
use DasRed\Translation\Command\Executor\TranslationAbstract;

class Duplicates extends TranslationAbstract
{

	/*
	 * (non-PHPdoc)
	 * @see \DasRed\Translation\Command\ExecutorAbstract::execute()
	 */
	public function execute()
	{
		$entries = [];
		$path = rtrim(str_replace('\\', '/', $this->getArguments()[0]), '/') . '/';

		try
		{
			$directory = new \RecursiveDirectoryIterator($path);
			$iterator = new \RecursiveIteratorIterator($directory);
			$regex = new \RegexIterator($iterator, '/^.+\.php$/i', \RecursiveRegexIterator::GET_MATCH);

			foreach ($regex as $matches)
			{
				$file = str_replace('\\', '/', $matches[0]);
				$translations = require $matches[0];

				foreach ($translations as $key => $content)
				{
					if (array_key_exists($content, $entries) === false)
					{
						$entries[$content] = [];
					}

					$entries[$content][] = [
						'file' => str_replace([$path, '.php'], '', $file),
						'key' => $key
					];
				}
			}

			$entries = array_filter($entries, function($files)
			{
				return count($files) > 1;
			});

			foreach ($entries as $content => $files)
			{
				for ($i = 1; $i < count($files); $i++)
				{
					$this->write($files[0], $files[$i]);
				}
			}

			$this->getConsole()->writeLine('Done.', ColorInterface::BLACK, ColorInterface::LIGHT_GREEN);
		}
		catch (\Exception $exception)
		{
			$this->getConsole()->writeLine('Can not search for duplicates. Maybe the path is wrong.', ColorInterface::LIGHT_YELLOW, ColorInterface::LIGHT_RED);
			return false;
		}

		return true;
	}

	/*
	 * (non-PHPdoc)
	 * @see \DasRed\Translation\Command\ExecutorAbstract::validateArguments()
	 */
	protected function validateArguments($arguments)
	{
		if (count($arguments) !== 1)
		{
			return false;
		}

		return parent::validateArguments($arguments);
	}

	/**
	 *
	 * @param array $fileA
	 * @param array $fileB
	 * @return self
	 */
	protected function write(array $fileA, array $fileB)
	{
		$this->getConsole()->write($fileA['file'], ColorInterface::GREEN);
		$this->getConsole()->write('.');
		$this->getConsole()->write($fileA['key'], ColorInterface::LIGHT_GREEN);
		$this->getConsole()->write(' <-> ');
		$this->getConsole()->write($fileB['file'], ColorInterface::RED);
		$this->getConsole()->write('.');
		$this->getConsole()->writeLine($fileB['key'], ColorInterface::LIGHT_RED);

		return $this;
	}
}


<?php

namespace Ronanchilvers\Silex\Provider;

use Silex\Application;
use Silex\ServiceProviderInterface;
use Symfony\Component\Yaml\Parser as YamlParser;

/**
 * Simple class to provide a config service parsed from a YAML file.
 *
 * @author Ronan Chilvers <ronan@d3r.com>
 */
class YamlConfigServiceProvider implements ServiceProviderInterface
{
    /**
     * The yml filename to parse.
     *
     * @var string
     */
    protected $filename;

    /**
     * Class constructor.
     *
     * @param string $filename
     *
     * @author Ronan Chilvers <ronan@d3r.com>
     */
    public function __construct($filename)
    {
        $this->filename = $filename;
    }

    /**
     * Register this provider.
     *
     * @param Silex\Application $app
     *
     * @author Ronan Chilvers <ronan@d3r.com>
     */
    public function register(Application $app)
    {
        if (is_null($this->filename)) {
            throw new \RuntimeException('You must provide a valid config filename');
        }
        if (!file_exists($this->filename)) {
            throw new \RuntimeException(sprintf('Config path \'%s\' is not valid', $this->filename));
        }
        if (!is_readable($this->filename)) {
            throw new \RuntimeException(sprintf('Config path \'%s\' is not readable', $this->filename));
        }
        $parser = new YamlParser();
        $config = $parser->parse(file_get_contents($this->filename));
        if (is_array($config) && !empty($config)) {
            if (isset($app['config']) && is_array($app['config'])) {
                $config = array_replace_recursive($app['config'], $config);
            }
            $app['config'] = $config;
        }
    }

    /**
     * Boot the provider.
     *
     * @param Silex\Application $app
     *
     * @author Ronan Chilvers <ronan@d3r.com>
     */
    public function boot(Application $app)
    {
    }
}


<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Device.php.
 *
 * @author    soone <66812590@qq.com>
 * @copyright 2016 soone <66812590@qq.com>
 */

namespace EasyWeChat\Device;

use EasyWeChat\Core\AbstractAPI;
use EasyWeChat\Core\AccessToken;

/**
 * Class Device.
 */
class Device extends AbstractAPI
{
    protected $deviceType;
    protected $productId;
    protected $config;

    const API_TRANS_MSG = 'https://api.weixin.qq.com/device/transmsg';
    const API_CREATE = 'https://api.weixin.qq.com/device/create_qrcode';
    const API_DEV_STAT = 'https://api.weixin.qq.com/device/get_stat';
    const API_DEV_AUTH = 'https://api.weixin.qq.com/device/authorize_device';
    const API_DEV_GET_QRCODE = 'https://api.weixin.qq.com/device/getqrcode';
    const API_DEV_VERIFY_QRCODE = 'https://api.weixin.qq.com/device/verify_qrcode';
    const API_DEV_BIND = 'https://api.weixin.qq.com/device/bind';
    const API_DEV_UNBIND = 'https://api.weixin.qq.com/device/unbind';
    const API_DEV_COMPEL_BIND = 'https://api.weixin.qq.com/device/compel_bind';
    const API_DEV_COMPEL_UNBIND = 'https://api.weixin.qq.com/device/compel_unbind';
    const API_DEV_GET_OPENID = 'https://api.weixin.qq.com/device/get_openid';
    const API_USER_DEV_BIND = 'https://api.weixin.qq.com/device/get_bind_device';

    public function __construct(AccessToken $accessToken, $config)
    {
        parent::setAccessToken($accessToken);
        $this->config = $config;
        $this->deviceType = $this->config['device_type'];
        $this->productId = $this->config['product_id'];
    }

    public function setProductId($productId)
    {
        $this->productId = $productId;

        return $this;
    }

    /**
     * Send message to device.
     *
     * @param int $sceneValue
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function sendToDevice($deviceId, $openId, $content)
    {
        $params = [
            'device_type' => $this->deviceType,
            'device_id' => $deviceId,
            'open_id' => $openId,
            'content' => base64_encode($content),
        ];

        return $this->parseJSON('json', [self::API_TRANS_MSG, $params]);
    }

    public function getDeviceQrcode(array $deviceIds)
    {
        $params = [
            'device_num' => count($deviceIds),
            'device_id_list' => $deviceIds,
        ];

        return $this->parseJSON('json', [self::API_CREATE, $params]);
    }

    public function authorizeDevice(array $deviceInfos, $opType = 0)
    {
        $params = [
            'device_num' => count($deviceInfos),
            'device_list' => $this->getDeviceList($deviceInfos),
            'op_type' => $opType,
            'product_id' => $this->productId,
        ];

        return $this->parseJSON('json', [self::API_DEV_AUTH, $params]);
    }

    protected function getDeviceList($deviceInfos)
    {
        $res = [];
        foreach ($deviceInfos as $dInfo) {
            $data = [
                'id' => $dInfo['deviceId'],
                'mac' => $dInfo['mac'],
                'connect_protocol' => $this->config['connect_protocol'],
                'auth_key' => $this->config['auth_key'],
                'close_strategy' => $this->config['close_strategy'],
                'conn_strategy' => $this->config['conn_strategy'],
                'crypt_method' => $this->config['crypt_method'],
                'auth_ver' => $this->config['auth_ver'],
                'manu_mac_pos' => $this->config['manu_mac_pos'],
                'ser_mac_pos' => $this->config['ser_mac_pos'],
            ];

            !empty($this->config['ble_simple_protocol']) ? $data['ble_simple_protocol'] = $this->config['ble_simple_protocol'] : '';

            $res[] = $data;
        }

        return $res;
    }

    public function createDeviceId()
    {
        $params = [
            'product_id' => $this->productId,
        ];

        return $this->parseJSON('get', [self::API_DEV_GET_QRCODE, $params]);
    }

    public function bind($openId, $deviceId, $ticket)
    {
        $params = [
            'ticket' => $ticket,
            'device_id' => $deviceId,
            'openid' => $openId,
        ];

        return $this->parseJSON('json', [self::API_DEV_BIND, $params]);
    }

    public function unbind($openId, $deviceId, $ticket)
    {
        $params = [
            'ticket' => $ticket,
            'device_id' => $deviceId,
            'openid' => $openId,
        ];

        return $this->parseJSON('json', [self::API_DEV_UNBIND, $params]);
    }

    public function compelBind($openId, $deviceId)
    {
        $params = [
            'device_id' => $deviceId,
            'openid' => $openId,
        ];

        return $this->parseJSON('json', [self::API_DEV_COMPEL_BIND, $params]);
    }

    public function compelUnbind($openId, $deviceId)
    {
        $params = [
            'device_id' => $deviceId,
            'openid' => $openId,
        ];

        return $this->parseJSON('json', [self::API_DEV_COMPEL_UNBIND, $params]);
    }

    public function getDeviceStatus($deviceId)
    {
        $params = [
            'device_id' => $deviceId,
        ];

        return $this->parseJSON('get', [self::API_DEV_STAT, $params]);
    }

    public function verifyQrcode($ticket)
    {
        $params = [
            'ticket' => $ticket,
        ];

        return $this->parseJSON('post', [self::API_DEV_VERIFY_QRCODE, $params]);
    }

    public function getOpenid($deviceId)
    {
        $params = [
            'device_type' => $this->deviceType,
            'device_id' => $deviceId,
        ];

        return $this->parseJSON('get', [self::API_DEV_GET_OPENID, $params]);
    }

    public function getDeviceidByOpenid($openid)
    {
        $params = [
            'openid' => $openid,
        ];

        return $this->parseJSON('get', [self::API_USER_DEV_BIND, $params]);
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\FilesystemEntity;

use JMS\Serializer\SerializerInterface;
use RedKiteCms\Tools\FilesystemTools;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class FilesystemEntity defines the base methods for a filesystem entity
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\FilesystemEntity
 */
abstract class FilesystemEntity implements FilesystemEntityInterface
{
    /**
     * @type \JMS\Serializer\SerializerInterface
     */
    protected $serializer;
    /**
     * @type \Symfony\Component\OptionsResolver\OptionsResolver
     */
    protected $optionsResolver;
    /**
     * @type string
     */
    protected $workMode;
    /**
     * @type string
     */
    protected $productionDir;
    /**
     * @type string
     */
    protected $contributorDir;
    /**
     * @type array
     */
    protected $options = array();

    /**
     * @param \JMS\Serializer\SerializerInterface $serializer
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $optionsResolver
     */
    public function __construct(SerializerInterface $serializer, OptionsResolver $optionsResolver)
    {
        $this->serializer = $serializer;
        $this->optionsResolver = $optionsResolver;
    }

    /**
     * {@inheritdoc}
     */
    public function init($sourceDir, array $options, $username = null)
    {
        $this->resolveOptions($options);
        $this->options = $options;

        $path = $this->getBaseDir($sourceDir);
        if (null === $path) {
            return $this;
        }

        $this->workMode = "contributor";
        $this->productionDir = $this->initProductionDir($path);
        if (null === $username) {
            $this->workMode = "production";

            return $this;
        }

        $this->contributorDir = $this->workDir = $this->initContributorDir($path, $username);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getProductionDir()
    {
        return $this->productionDir;
    }

    /**
     * {@inheritdoc}
     */
    public function getContributorDir()
    {
        return $this->contributorDir;
    }

    /**
     * {@inheritdoc}
     */
    public function getArchiveDir($targetDir = null)
    {
        $targetDir = $this->workDirectory($targetDir);

        return $targetDir . '/archive';
    }

    /**
     * {@inheritdoc}
     */
    public function getDirInUse()
    {
        switch ($this->workMode) {
            case "contributor":
                return $this->contributorDir;

            case "production":
                return $this->productionDir;

            default:
                return null;
        }
    }

    /**
     * Configures the base options for the resolver
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver
     */
    protected function resolveOptions(array $options)
    {
        $this->optionsResolver->setRequired(
            array(
                'page',
                'language',
                'slot',
                'country',
            )
        );

        $this->optionsResolver->resolve($options);
    }

    /**
     * Returns the work directory
     * @param null|string$targetDir
     *
     * @return null|string
     */
    protected function workDirectory($targetDir)
    {
        if (null === $targetDir) {
            $targetDir = $this->getDirInUse();
        }

        return $targetDir;
    }

    private function getBaseDir($sourceDir)
    {
        return FilesystemTools::slotDir($sourceDir, $this->options);
    }

    private function initProductionDir($baseDir)
    {
        return $baseDir . '/active';
    }

    private function initContributorDir($baseDir, $username)
    {
        if (null === $username) {
            return null;
        }

        return $baseDir . '/contributors/' . $username;
    }
}


<?php
namespace Boekkooi\Bundle\AMQP\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from your app/config files
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode    = $treeBuilder->root('boekkooi_amqp');

        $this->addConnections($rootNode);
        $this->addVHosts($rootNode);
        $this->addCommands($rootNode);
        $this->addPublisher($rootNode);

        $this->addTactician($rootNode);

        return $treeBuilder;
    }

    protected function addConnections(ArrayNodeDefinition $node)
    {
        $integerNormalizer = function ($val) { return strval(intval($val)) === $val ? intval($val) : $val; };

        $node
            ->children()
                ->arrayNode('connections')
                    ->useAttributeAsKey('name')
                    ->canBeUnset()
                    ->prototype('array')
                        ->addDefaultsIfNotSet()
                        ->children()
                            ->scalarNode('host')->defaultValue('localhost')->end()
                            ->integerNode('port')
                                ->beforeNormalization()
                                    ->ifString()
                                    ->then($integerNormalizer)
                                ->end()
                                ->defaultValue(5672)
                            ->end()
                            ->arrayNode('timeout')
                                ->addDefaultsIfNotSet()
                                ->beforeNormalization()
                                    ->ifTrue(function ($v) { return is_int($v); })
                                    ->then(function ($v) { return array('read' => $v, 'write' => $v, 'connect' => $v); })
                                ->end()
                                ->children()
                                    ->integerNode('read')
                                        ->beforeNormalization()
                                            ->ifString()
                                            ->then($integerNormalizer)
                                        ->end()
                                        ->defaultValue(10)
                                    ->end()
                                    ->integerNode('write')
                                        ->beforeNormalization()
                                            ->ifString()
                                            ->then($integerNormalizer)
                                        ->end()
                                        ->defaultValue(10)
                                    ->end()
                                    ->integerNode('connect')
                                        ->beforeNormalization()
                                            ->ifString()
                                            ->then($integerNormalizer)
                                        ->end()
                                        ->defaultValue(10)
                                    ->end()
                                ->end()
                            ->end()
                            ->scalarNode('login')->defaultValue('guest')->end()
                            ->scalarNode('password')->defaultValue('guest')->end()
                        ->end()
                    ->end()
                ->end()
            ->end();
    }

    protected function addVHosts(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('vhosts')
                    ->useAttributeAsKey('name')
                    ->canBeUnset()
                    ->prototype('array')
                        ->children()
                            ->scalarNode('path')->info('The actual vhost')->isRequired()->end()
                            ->scalarNode('connection')->defaultValue('default')->end()

                            ->arrayNode('exchanges')
                                ->useAttributeAsKey('name')
                                ->canBeUnset()
                                ->prototype('array')
                                    ->addDefaultsIfNotSet()
                                    ->children()
                                        ->enumNode('type')
                                            ->values(array('direct', 'fanout', 'headers', 'topic'))
                                            ->isRequired()
                                        ->end()
                                        ->booleanNode('passive')->defaultFalse()->end()
                                        ->booleanNode('durable')->defaultTrue()->end()
                                        ->arrayNode('arguments')
                                            ->defaultValue(array())
                                            ->prototype('variable')->end()
                                        ->end()
                                    ->end()
                                ->end()
                            ->end()

                            ->arrayNode('queues')
                                ->useAttributeAsKey('name')
                                ->canBeUnset()
                                ->prototype('array')
                                    ->addDefaultsIfNotSet()
                                    ->children()
                                        ->booleanNode('passive')->defaultFalse()->end()
                                        ->booleanNode('durable')->defaultTrue()->end()
                                        ->booleanNode('exclusive')->defaultFalse()->end()
                                        ->booleanNode('auto_delete')->defaultFalse()->end()

                                        ->arrayNode('arguments')
                                            ->defaultValue(array())
                                            ->prototype('variable')->end()
                                        ->end()

                                        ->arrayNode('binds')
                                            ->isRequired()
                                            ->requiresAtLeastOneElement()
                                            ->useAttributeAsKey('exchange')
                                            ->prototype('array')
                                                ->addDefaultsIfNotSet()
                                                ->children()
                                                    ->scalarNode('routing_key')->defaultValue(null)->end()
                                                    ->arrayNode('arguments')
                                                        ->defaultValue(array())
                                                        ->prototype('variable')->end()
                                                    ->end()
                                                ->end()
                                            ->end()
                                        ->end()
                                    ->end()
                                ->end()
                            ->end()

                        ->end()
                    ->end()
                ->end()
            ->end();
    }

    protected function addCommands(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('commands')
                    ->useAttributeAsKey('class')
                    ->canBeUnset()
                    ->prototype('array')
                        ->addDefaultsIfNotSet()
                        ->children()
                            ->scalarNode('vhost')->isRequired()->cannotBeEmpty()->end()
                            ->scalarNode('exchange')->isRequired()->cannotBeEmpty()->end()
                            ->scalarNode('routing_key')->defaultValue(null)->end()

                            ->booleanNode('rpc')
                                ->info('the command is expected to return a response')
                                ->defaultFalse()
                            ->end()
                            ->booleanNode('mandatory')
                                ->info('the command must be routed to a valid queue')
                                ->defaultTrue()
                            ->end()
                            ->booleanNode('immediate')
                                ->info('mark the command for immediate processing')
                                ->defaultFalse()
                            ->end()

                            ->arrayNode('attributes')
                                ->defaultValue(array())
                                ->prototype('variable')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end();
    }

    private function addTactician(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->scalarNode('command_bus')
                    ->info('The tactician command bus to use for queue consumption')
                    ->defaultValue('tactician.commandbus')
                ->end()
                ->scalarNode('envelope_transformer')->defaultValue('boekkooi.amqp.tactician.envelope_transformer')->end()
                ->scalarNode('command_transformer')->defaultValue('boekkooi.amqp.tactician.command_transformer')->end()
                ->scalarNode('response_transformer')->defaultValue('boekkooi.amqp.tactician.response_transformer')->end()
                ->scalarNode('serializer')->defaultValue('boekkooi.amqp.tactician.serializer')->end()
                ->scalarNode('serializer_format')->defaultValue('json')->end()
            ->end();
    }

    private function addPublisher(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('publisher')
                    ->addDefaultsIfNotSet()
                    ->canBeUnset()
                    ->children()
                        ->arrayNode('transaction')
                            ->defaultValue(array())
                            ->prototype('scalar')
                        ->end()
                    ->end()
                ->end()
            ->end();
    }
}


<?php
namespace core\manage\logic;

use cms\Logic;

class JobLogic extends Logic
{

    /**
     * 队列列表
     *
     * @return array
     */
    public function getJobQueue()
    {
        $list = $this->model->group('queue')->select();
        $list || $list = [];

        $result = [];
        foreach ($list as $vo) {
            $result[] = [
                'name' => $vo['queue'],
                'value' => $vo['queue']
            ];
        }
        return $result;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Repository;

use Doctrine\Common\Collections\Collection;
use OpenOrchestra\ModelInterface\Model\RouteDocumentInterface;
use OpenOrchestra\ModelInterface\Repository\RouteDocumentRepositoryInterface;
use OpenOrchestra\Repository\AbstractAggregateRepository;

/**
 * Class RouteDocumentRepository
 */
class RouteDocumentRepository extends AbstractAggregateRepository implements RouteDocumentRepositoryInterface
{
    /**
     * @param string $name
     *
     * @return RouteDocumentInterface
     */
    public function findOneByName($name)
    {
        return $this->findOneBy(array('name' => $name));
    }

    /**
     * @param string $redirectionId
     *
     * @return RouteDocumentInterface
     */
    public function removeByRedirectionId($redirectionId)
    {
        $this->createQueryBuilder()
            ->remove()
            ->field('name')->equals(new \MongoRegex('/.*_' . $redirectionId . '/'))
            ->getQuery()
            ->execute();
    }

    /**
     * @param string $pathInfo
     *
     * @return Collection
     */
    public function findByPathInfo($pathInfo)
    {
        $workingPattern = explode('/', trim($pathInfo, '/'));

        $qa = $this->createAggregationQuery('r');

        $filter = array();
        $i = 0;
        while ($i <= 10) {
            if (array_key_exists($i, $workingPattern)) {
                $filter['token' . $i] = new \MongoRegex('/^' . $workingPattern[$i] . '$|\*/');
            } else {
                $filter['token' . $i] = null;
            }
            $i++;
        }

        $qa->match($filter);
        $qa->sort(array('weight' => 1));

        return $this->hydrateAggregateQuery($qa);
    }

    /**
     * @param array  $nodeIds
     * @param string $siteId
     * @param string $language
     */
    public function removeByNodeIdsSiteIdAndLanguage(array $nodeIds, $siteId, $language)
    {
        $this->createQueryBuilder()
            ->remove()
            ->field('siteId')->equals($siteId)
            ->field('language')->equals($language)
            ->field('nodeId')->in($nodeIds)
            ->getQuery()
            ->execute();
    }

    /**
     * @param string $siteId
     */
    public function removeBySiteId($siteId)
    {
        $this->createQueryBuilder()
             ->remove()
             ->field('siteId')->equals($siteId)
             ->getQuery()
             ->execute();
    }
}