<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB\DemoContent;

use OpenOrchestra\ModelBundle\Document\Block;
use OpenOrchestra\ModelBundle\Document\Node;
use OpenOrchestra\DisplayBundle\DisplayBlock\Strategies\TinyMCEWysiwygStrategy;
use OpenOrchestra\ModelInterface\Model\NodeInterface;
use OpenOrchestra\ModelBundle\Document\Area;

/**
 * Class NewsDataGenerator
 */
class NewsDataGenerator extends AbstractDataGenerator
{
    /**
     * @return Node
     */
    protected function generateNodeFr()
    {
        $htmlContent = <<<EOF

Actualité

Open Orchestra au SymfonyLive Paris 2015

            Le SymfonyLive est l'évènement incontournable de la communauté Symfony et Open-Source
            francophone. C'est pourquoi l'équipe Open Orchestra a décidé de soutenir l'événement en
            devenant sponsor Gold de cette édition. A cette occasion, Open Orchestra s'est dévoilé
            à la communauté à l'occasion des 10 ans de Symfony devant plus de 600 participants.

Open Orchestra sponsorise un sfPot

            Le 16 juin 2015, Open Orchestra à participé à l'organisation du SfPot Paris dans les
            locaux de la fondation Mozilla pour environ 100 développeurs Symfony.

EOF;
        $name = "Actualités";
        $language = "fr";
        $routePattern = "nos-actualites";

        return $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
    }

    /**
     * @return Node
     */
    protected function generateNodeEn()
    {
        $htmlContent = <<<EOF

News

Open Orchestra at the SymfonyLive - Paris 2015

            SymfonyLive is the most important of the French Symfony community.  For this reason, Open Orchestra 's team
            has decide to help the event and become a Gold Sponsor for the 2015 edition. It was the opportunity to reveal
            Open Orchestra to the community for the 10 years of Symfony in front of more than six hundred entrant.

Open Orchestra sponsors a sfPot

            June 16th 2015, Open Orchestra participate to the Paris SfPot organisation in the
           Mozilla foundation office for about hundred hundred 100 Symfony developers.

EOF;
        $name = "News";
        $language = "en";
        $routePattern = "page-news";

        return $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
    }

    /**
     * @return Node
     */
    protected function generateNodeDe()
    {
        $htmlContent = <<<EOF

Aktualität

Offene Orchestra in Symfony Live 2015 Paris

            Die Symfony Live ist das Schlüsselereignis von Symfony und Französisch Open-Source-Community.
            Deshalb ist das Öffnen Orchester-Team beschlossen, die Veranstaltung, indem er ein Gold Sponsor
            dieser Ausgabe unterstützen. Bei dieser Gelegenheit wurde Öffnen Orchestra an der Gemeinschaft
            anlässlich der 10 Jahre Symfony vor mehr als 600 Teilnehmern vorgestellt.

Offene Orchestra sponsert sfPot

            Der 16. Juni 2015 nahm Öffnen Orchestra in der Organisation der
             SfPot Paris auf dem Gelände der Mozilla Foundation etwa 100 Symfony-Entwickler.

EOF;
        $name = "Aktualität";
        $language = "de";
        $routePattern = "unsere-nachrichten";

        return $this->generateNodeGlobal($htmlContent, $name, $language, $routePattern);
    }

    /**
     * @param string $htmlContent
     * @param string $name
     * @param string $language
     * @param string $routePattern
     *
     * @return Node
     */
    protected function generateNodeGlobal($htmlContent, $name, $language, $routePattern)
    {
        $nodeNewsBlock = new Block();
        $nodeNewsBlock->setLabel('Wysiwyg');
        $nodeNewsBlock->setComponent(TinyMCEWysiwygStrategy::NAME);
        $nodeNewsBlock->setLanguage($language);
        $nodeNewsBlock->setAttributes(array(
            "htmlContent" => $htmlContent
        ));

        $nodeNewsBlock = $this->generateBlock($nodeNewsBlock);

        $main = new Area();
        $main->addBlock($nodeNewsBlock);

        $nodeNews = $this->createBaseNode();
        $nodeNews->setArea('main', $main);

        $nodeNews->setNodeId('fixture_page_news');
        $nodeNews->setName($name);
        $nodeNews->setVersionName($this->getVersionName($nodeNews));
        $nodeNews->setLanguage($language);
        $nodeNews->setParentId(NodeInterface::ROOT_NODE_ID);
        $nodeNews->setOrder(6);
        $nodeNews->setRoutePattern($routePattern);
        $nodeNews->setInFooter(false);
        $nodeNews->setInMenu(true);

        return $nodeNews;
    }
}


<?php
/**
 * Authors: Alex Gusev <alex@flancer64.com>
 * Since: 2019
 */

namespace Praxigento\BonusHybrid\Service\Calc\Z\Helper;

use Praxigento\BonusBase\Repo\Data\Calculation as ECalc;
use Praxigento\BonusBase\Repo\Data\Period as EPeriod;
use Praxigento\BonusBase\Repo\Data\Type\Calc as ECalcType;
use Praxigento\BonusBase\Repo\Query\Period\Calcs\Builder as QGetCalcs;
use Praxigento\BonusHybrid\Config as Cfg;
use Praxigento\BonusHybrid\Repo\Data\Downline as EBonDwnl;
use Praxigento\Core\Api\Helper\Period as HPeriod;

/**
 * Get plain downline tree for period previous for given (forecast or PV Write Off).
 */
class GetDownlinePlainPrev
{
    /** @var \Praxigento\BonusHybrid\Repo\Dao\Downline */
    private $daoBonDwnl;
    /** @var \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Praxigento\Downline\Api\Helper\Tree */
    private $hlpTree;
    /** @var \Praxigento\BonusBase\Repo\Query\Period\Calcs\Builder */
    private $qGetCalcs;

    public function __construct(
        \Praxigento\BonusHybrid\Repo\Dao\Downline $daoBonDwnl,
        \Praxigento\BonusBase\Repo\Query\Period\Calcs\Builder $qGetCalcs,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\Downline\Api\Helper\Tree $hlpTree
    ) {
        $this->daoBonDwnl = $daoBonDwnl;
        $this->qGetCalcs = $qGetCalcs;
        $this->hlpPeriod = $hlpPeriod;
        $this->hlpTree = $hlpTree;
    }

    /**
     * Get plain tree for previous period (with unq. months data).
     *
     * @param string $dateOn YYYYMMDD
     * @return EBonDwnl[]
     */
    public function exec($dateOn)
    {
        $prevCalcId = $this->getPrevTreeCalcId($dateOn);
        $tree = $this->daoBonDwnl->getByCalcId($prevCalcId);
        $result = $this->hlpTree->mapById($tree, EBonDwnl::A_CUST_REF);
        return $result;
    }

    /**
     * Get calc ID (Forecast or PV Write Off) to load plain tree for previous period for $dateOn.
     *
     * @param string $dateOn
     * @return int
     */
    private function getPrevTreeCalcId($dateOn)
    {
        /* get plain tree calc (PV_WRITE_OFF) for prev. period */
        $periodPrev = $this->hlpPeriod->getPeriodPrev($dateOn, HPeriod::TYPE_MONTH);
        $dsLast = $this->hlpPeriod->getPeriodLastDate($periodPrev);

        $query = $this->qGetCalcs->build();

        /* WHERE */
        $bndTypeForecast = 'forecast';
        $bndTypeWriteOff = 'writeOff';
        $bndEnd = 'end';
        $bndState = 'state';
        $byTypeForecast = QGetCalcs::AS_CALC_TYPE . '.' . ECalcType::A_CODE . "=:$bndTypeForecast";
        $byTypeWriteOff = QGetCalcs::AS_CALC_TYPE . '.' . ECalcType::A_CODE . "=:$bndTypeWriteOff";
        $byDateEnd = QGetCalcs::AS_PERIOD . '.' . EPeriod::A_DSTAMP_END . "=:$bndEnd";
        $byState = QGetCalcs::AS_CALC . '.' . ECalc::A_STATE . "=:$bndState";
        $where = "(($byTypeForecast) OR ($byTypeWriteOff)) AND ($byDateEnd) AND ($byState)";
        $query->where($where);

        /* ORDER BY */
        $byCalcIdDesc = QGetCalcs::AS_CALC . '.' . ECalc::A_ID . ' DESC';
        $query->order($byCalcIdDesc);

        /* EXEC QUERY */
        $bind = [
            $bndTypeForecast => Cfg::CODE_TYPE_CALC_FORECAST_PLAIN,
            $bndTypeWriteOff => Cfg::CODE_TYPE_CALC_PV_WRITE_OFF,
            $bndEnd => $dsLast,
            $bndState => Cfg::CALC_STATE_COMPLETE,
        ];
        $conn = $query->getConnection();
        $rs = $conn->fetchAll($query, $bind);
        $one = reset($rs);
        $result = $one[QGetCalcs::A_CALC_ID];

        return $result;
    }

}


<?php

/**
* Jin Framework
* Diatem
*/

namespace Jin2\Log;

/**
 * Outils de notification à travers une session
*/
class Notifier
{

  /**
   * @var string Clé pour le stockage des notifications en session
   */
  const COOKIE_NAME = 'jin_notifications';

  /**
   * @var string Statut standard pour les notifications
   */
  const STATUS_NOTICE = 'notice';

  /**
   * @var string Statut d'erreur pour les notifications
   */
  const STATUS_ERROR = 'error';

  /**
   * @var string Statut d'avertissement pour les notifications
   */
  const STATUS_WARNING = 'warning';

  /**
   * @var string Statut de succès pour les notifications
   */
  const STATUS_SUCCESS = 'success';

  /**
   * Vérifie que le stockage en session existe
  */
  protected static function checkStorage()
  {
    if( !isset($_COOKIE) || !isset($_COOKIE[self::COOKIE_NAME]) ) {
      static::clear();
    }
  }

  /**
   * Ajoute une(des) notification(s) dans la pile
   *
   * @param  mixed   $notif    Notification(s) à stocker
   * @param  string  $status   Statut de la notification (optionel, uniquement si on ajoute une seule notification)
  */
  public static function push($notif, $status = self::STATUS_NOTICE)
  {
    static::checkStorage();
    if( is_string($notif) ) {
      $notif = array(array(
        'status'  => $status,
        'message' => $notif
      ));
    }
    $notifs = unserialize($_COOKIE[self::COOKIE_NAME]);
    foreach ($notif as $object) {
      if( !isset($object['message']) || !is_string($object['message']) ) {
        continue;
      }
      if( !isset($object['status']) || !in_array($object['status'], array(self::STATUS_NOTICE, self::STATUS_ERROR, self::STATUS_WARNING, self::STATUS_SUCCESS)) ) {
        $object['status'] = self::STATUS_NOTICE;
      }
      array_push($notifs, (object)$object);
    }
    setcookie(self::COOKIE_NAME, serialize($notifs), time()+180, "/");
  }

  /**
   * Récupère la dernière notification de la pile
   *
   * @return object
  */
  public static function pull()
  {
    static::checkStorage();
    $notifs = unserialize($_COOKIE[self::COOKIE_NAME]);
    $firstnotif = array_shift($notifs);
    setcookie(self::COOKIE_NAME, serialize($notifs), time()+180, "/");
    return $firstnotif;
  }

  /**
   * Récupère toutes les notifications de la pile
   *
   * @return array
  */
  public static function pullAll()
  {
    static::checkStorage();
    $notifs = unserialize($_COOKIE[self::COOKIE_NAME]);
    static::clear();
    return $notifs;
  }

  /**
   * Supprime toutes les notifications de la pile
   *
   * @return array
  */
  public static function clear()
  {
    setcookie(self::COOKIE_NAME, serialize(array()), time()+180, "/");
  }

}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Adapter;

use Dothiv\Bundle\ContentfulBundle\Item\ContentfulContentType;

class ContentfulContentTypeReader
{
    /**
     * @var string
     */
    private $spaceId;

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

    /**
     * @param object $data
     *
     * @return ContentfulContentType
     */
    public function getContentType($data)
    {
        $contentType = new ContentfulContentType();
        $contentType->setName($data->name);
        $contentType->setDisplayField($data->displayField);
        $contentType->setId($data->sys->id);
        $contentType->setRevision($data->sys->revision);
        $contentType->setSpaceId($this->spaceId);
        $contentType->setCreatedAt(new \DateTime($data->sys->createdAt));
        $contentType->setUpdatedAt(new \DateTime($data->sys->updatedAt));
        return $contentType;
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\Basket\Handler;

use RunetId\Client\Exception\RunetIdException;
use RunetId\Client\Result\Pay\ItemResult;
use Ruwork\RunetIdBundle\Basket\Basket\BasketInterface;
use Ruwork\RunetIdBundle\Basket\Basket\Client;
use Ruwork\RunetIdBundle\Basket\Options\NormalizerFactory;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class ProductHandler implements HandlerInterface
{
    /**
     * {@inheritdoc}
     */
    public function handle(array $options, BasketInterface $basket, Client $client): void
    {
        /** @var null|ItemResult $item */
        [
            'exception_handler' => $exceptionHandler,
            'item' => $item,
            'product' => $productId,
            'recover_item' => $recoverItem,
            'user' => $runetId,
        ] = $options;

        $itemProductId = null !== $item ? $item->Product->Id : null;

        if ($itemProductId === $productId) {
            return;
        }

        if (null !== $itemProductId) {
            try {
                $client
                    ->payDelete()
                    ->setOrderItemId($item->Id)
                    ->getRawResult();
            } catch (RunetIdException $exception) {
                $exceptionHandler($exception);

                return;
            }
        }

        if (null === $productId) {
            return;
        }

        try {
            $client
                ->payAdd()
                ->setOwnerRunetId($runetId)
                ->setProductId($productId)
                ->getResult();
        } catch (RunetIdException $exception) {
            if (null !== $itemProductId && $recoverItem) {
                /* @var int $itemProductId */
                $client
                    ->payAdd()
                    ->setOwnerRunetId($runetId)
                    ->setProductId($itemProductId)
                    ->getRawResult();
            }

            $exceptionHandler($exception);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setRequired([
                'user',
            ])
            ->setDefaults([
                'exception_handler' => static function (RunetIdException $exception) {
                    throw $exception;
                },
                'item' => null,
                'product' => null,
                'recover_item' => true,
            ])
            ->setAllowedTypes('exception_handler', 'callable')
            ->setAllowedTypes('item', ['null', ItemResult::class])
            ->setAllowedTypes('product', ['null', 'int', 'object'])
            ->setNormalizer('product', NormalizerFactory::createProductNormalizer())
            ->setAllowedTypes('recover_item', 'bool')
            ->setAllowedTypes('user', ['int', 'object'])
            ->setNormalizer('user', NormalizerFactory::createUserNormalizer());
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: las
 * Date: 28/06/2016
 * Time: 22:22
 */
namespace Venus\lib\Request;

class Request implements RequestInterface
{
    /**
     * get parameter
     * @param string $name
     * @param string $default
     * @return string
     */
    public function get(string $name, string $default = null)
    {
        if (isset($_POST[$name]) && $_POST[$name] != '') {
            return $_POST[$name];
        } else if ($default !== null) {
            return $default;
        } else {
            return '';
        }
    }
}


<?php namespace Versatile\Geo;

use Versatile\Geo\Contracts\Coder;
use Versatile\Geo\Contracts\Client;
use Versatile\Geo\Contracts\BoundingArea;

class GoogleCoder implements Coder
{

    protected $client;

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

    /**
     * {@inheritdoc}
     *
     * @param string|\Versatile\Geo\Contracts\Address $address
     * @param \Versatile\Geo\Contracts\BoundingArea $searchIn (optional)
     * @return \Versatile\Geo\Contracts\Coordinate
     **/
    public function geocode($address, BoundingArea $searchIn=null)
    {

        $addressString = $this->formatAddress($address);

        $params = $this->buildRequestParams($addressString);

        $response = $this->client->fetch('geocode', $params);

        return $this->buildGeoCoordinateFromResponse($response);

    }

    protected function buildGeoCoordinateFromResponse(array $response)
    {
        $latitude = $response['results'][0]['geometry']['location']['lat'];
        $longitude = $response['results'][0]['geometry']['location']['lng'];
        return new Coordinate($latitude, $longitude);
    }

    protected function buildRequestParams($address)
    {
        return ['address' => $address];
    }

    protected function formatAddress($address)
    {
        if (is_string($address)) {
            return str_replace('Str.', 'Straße', $address);
        }

        $methods = [
            'street', 'postCode', 'city', 'country'
        ];

        $parts = [];

        foreach ($methods as $method) {
            if ($res = $address->{$method}()) {
                $parts[] = $res;
            }
        }

        return implode(', ', $parts);

    }

}


<?php
namespace HtSettingsModule\Service;

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\AbstractFactoryInterface;

class SettingsAbstractFactory implements AbstractFactoryInterface
{
    const PREFIX = 'settings.';

    /**
     * {@inheritDoc}
     */
    public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        if (strpos($requestedName, static::PREFIX) === 0) {
            $options = $serviceLocator->get('HtSettingsModule\Options\ModuleOptions');
            $namespace = $this->getNamespace($requestedName);

            return $options->hasNamespace($namespace);
        }

        return false;
    }

    /**
     * {@inheritDoc}
     */
    public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
    {
        $settingsProvider = $serviceLocator->get('HtSettingsModule\Service\SettingsProvider');
        $namespace = $this->getNamespace($requestedName);

        return $settingsProvider->getSettings($namespace);
    }

    protected function getNamespace($requestedName)
    {
        return substr($requestedName, strlen(static::PREFIX));
    }
}


<?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\Context\ValueCache;

use Countable;
use TASoft\Config\Config;

class ValueCache implements ValueCacheInterface, Countable
{
    private $cache = [];

    /**
     * @inheritDoc
     */
    public function count()
    {
        $count = 0;
        foreach($this->cache as $c) {
            $count += count($c);
        }
        return $count;
    }

    /**
     * ValueCache constructor.
     * @param Config|NULL $cache
     */
    public function __construct(Config $cache = NULL)
    {
        $this->cache = $cache ?: new Config([]);
    }

    /**
     * @inheritDoc
     */
    public function postValue($value, string $name, string $domain = "")
    {
        $dom = $this->_getDomain($domain);
        $dom[$name] = $value;
    }

    /**
     * @inheritDoc
     */
    public function fetchValue(string $name, string $domain = "")
    {
        $dom = $this->_getDomain($domain);
        return $dom[$name] ?? NULL;
    }

    /**
     * @inheritDoc
     */
    public function fetchValues(string $domain = "")
    {
        /** @var Config $dom */
        $dom = $this->_getDomain($domain);
        return $dom->getAll();
    }

    /**
     * Fetches all values
     * @return array
     */
    public function fetchAll() {
        $list = [];
        foreach($this->cache as $domain => $values) {
            foreach($values as $key => $value)
                $list[ sprintf("%s.%s", $domain!='<NULL>' ? $domain : '', $key) ] = $value;
        }
        return $list;
    }

    /**
     * @param $domain
     * @return mixed|null
     * @internal
     */
    private function _getDomain($domain) {
        if(!$domain) {
            if(!isset($this->cache['<NULL>']))
                $this->cache['<NULL>'] = new Config([]);
            return $this->cache['<NULL>'];
        }

        if(!isset($this->cache[$domain]))
            $this->cache[$domain] = new Config([]);
        return $this->cache[$domain];
    }
}


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

use Boekkooi\Bundle\AMQP\CommandMessage;
use Boekkooi\Bundle\AMQP\CommandConfiguration;
use Boekkooi\Bundle\AMQP\Exception\CommandTransformationException;
use Boekkooi\Tactician\AMQP\Transformer\CommandTransformer as CommandTransformerInterface;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
use Symfony\Component\Serializer\SerializerInterface;

class CommandTransformer implements CommandTransformerInterface
{
    /**
     * @var SerializerInterface
     */
    private $serializer;
    /**
     * @var string
     */
    private $format;
    /**
     * @var string
     */
    private $commandHeaderName;

    /**
     * @var CommandConfiguration[]
     */
    private $commands = [];

    /**
     * Constructor
     *
     * @param SerializerInterface $serializer
     * @param string $format The default serialize format
     * @param string $commandHeaderName The name of the amqp header to identify the command
     */
    public function __construct(SerializerInterface $serializer, $format, $commandHeaderName = 'x-symfony-command')
    {
        $this->serializer = $serializer;
        $this->format = $format;
        $this->commandHeaderName = $commandHeaderName;
    }

    /**
     * Register a command configuration.
     *
     * @param CommandConfiguration $command
     */
    public function registerCommand(CommandConfiguration $command)
    {
        $this->commands[$command->getClass()] = $command;
    }

    /**
     * Register a set of command configurations.
     *
     * @param CommandConfiguration[] $commands
     */
    public function registerCommands($commands)
    {
        foreach ($commands as $command) {
            $this->registerCommand($command);
        }
    }

    /**
     * Returns a Message instance representation of a command
     *
     * @param mixed $command The command to transform
     * @return CommandMessage
     */
    public function transformCommandToMessage($command)
    {
        if (!is_object($command)) {
            throw CommandTransformationException::expectedObject($command);
        }
        if (!isset($this->commands[get_class($command)])) {
            throw CommandTransformationException::unknownCommand($command, array_keys($this->commands));
        }
        if ($this->serializer instanceof EncoderInterface && !$this->serializer->supportsEncoding($this->format)) {
            throw CommandTransformationException::unsupportedFormat($command, $this->format);
        }

        $info = $this->commands[get_class($command)];

        return new CommandMessage(
            $info->getVhost(),
            $info->getExchange(),
            $this->serializer->serialize($command, $this->format),
            $info->getRoutingKey(),
            $info->getFlags(),
            $this->resolveMessageAttributes($command, $info)
        );
    }

    /**
     * @param object $command
     * @param CommandConfiguration $config
     * @return array
     */
    private function resolveMessageAttributes($command, CommandConfiguration $config)
    {
        $defaultAttributes = [
            'content_type' => 'application/' . strtolower($this->format),
            'headers' => [
                $this->commandHeaderName => get_class($command)
            ]
        ];
        if (empty($config->getAttributes())) {
            return $defaultAttributes;
        }

        $attributes = array_merge($defaultAttributes, $config->getAttributes());
        if (!isset($attributes['headers'][$this->commandHeaderName])) {
            $attributes['headers'][$this->commandHeaderName] = $defaultAttributes['headers'][$this->commandHeaderName];
        }

        return $attributes;
    }
}


<?php

namespace dee\composer;

use Composer\Package\PackageInterface;
use Composer\Util\Filesystem;
use Composer\Script\CommandEvent;
use Composer\Script\ScriptEvents;
use Composer\EventDispatcher\EventSubscriberInterface;

/**
 * Configure
 *
 * @author Misbahul D Munir <misbahuldmunir@gmail.com>
 * @since 1.0
 */
class Installer implements EventSubscriberInterface
{
    const PACKAGE_FILE = 'deesoft/root_package.php';
    const EXTRA_SYMLINK = 'symlinks';
    const EXTRA_PERMISSION = 'permission';
    const EXTENSION_FILE = 'yiisoft/extensions.php';
    const EXTRA_BOOTSTRAP = 'bootstrap';

    protected $baseDir;
    protected $vendorDir;

    protected function setRootPackage(PackageInterface $package)
    {
        $info = [
            'name' => $package->getName(),
            'version' => $package->getVersion(),
        ];

        $alias = $this->generatePackagetAlias($package);
        if (!empty($alias)) {
            $info['alias'] = $alias;
        }
        $extra = $package->getExtra();

        if (isset($extra[self::EXTRA_BOOTSTRAP])) {
            $info['bootstrap'] = $extra[self::EXTRA_BOOTSTRAP];
        }
        $this->savePackage($info);
    }

    protected function generatePackagetAlias(PackageInterface $package)
    {
        $fs = new Filesystem;
        $autoload = $package->getAutoload();
        $baseDir = $this->baseDir;

        $aliases = [];

        if (!empty($autoload['psr-0'])) {
            foreach ($autoload['psr-0'] as $name => $path) {
                $name = str_replace('\\', '/', trim($name, '\\'));
                if (!$fs->isAbsolutePath($path)) {
                    $path = $baseDir . '/' . $path;
                }
                $path = $fs->normalizePath($path);
                if (strpos($path . '/', $baseDir . '/') === 0) {
                    $aliases["@$name"] = '<base-dir>' . substr($path, strlen($baseDir)) . '/' . $name;
                } else {
                    $aliases["@$name"] = $path . '/' . $name;
                }
            }
        }

        if (!empty($autoload['psr-4'])) {
            foreach ($autoload['psr-4'] as $name => $path) {
                $name = str_replace('\\', '/', trim($name, '\\'));
                if (!$fs->isAbsolutePath($path)) {
                    $path = $baseDir . '/' . $path;
                }
                $path = $fs->normalizePath($path);
                if (strpos($path . '/', $baseDir . '/') === 0) {
                    $aliases["@$name"] = '<base-dir>' . substr($path, strlen($baseDir));
                } else {
                    $aliases["@$name"] = $path;
                }
            }
        }

        return $aliases;
    }

    protected function savePackage($info)
    {
        $file = $this->vendorDir . '/' . self::PACKAGE_FILE;
        if (!file_exists(dirname($file))) {
            mkdir(dirname($file), 0777, true);
        }
        $baseDir = $this->baseDir;
        if (strpos($this->vendorDir . '/', $baseDir . '/') === 0) {
            $child = substr($this->vendorDir, strlen($baseDir));
            if (strpos($child, '..') === false) {
                $c = substr_count($child, '/');
                $dir = 'dirname(__DIR__)';
                for ($i = 0; $i < $c; $i++) {
                    $dir = "dirname($dir)";
                }
            } else {
                $dir = var_export($this->baseDir, true);
            }
        } else {
            $dir = var_export($this->baseDir, true);
        }
        $array = var_export($info, true);
        $array = str_replace("'<base-dir>", '$baseDir . \'', $array);
        file_put_contents($file, "<?php\n\n\$baseDir = $dir;\n\nreturn $array;");
        // invalidate opcache of extensions.php if exists
        if (function_exists('opcache_invalidate')) {
            opcache_invalidate($file, true);
        }
    }

    public static function generateSymlink(array $links)
    {
        foreach ($links as $dest => $src) {
            echo "symlink('$src', '$dest')...";
            if (!is_dir($dest) && !is_file($dest)) {
                symlink($src, $dest);
                echo "done.\n";
            } else {
                echo "file destination exists.\n";
            }
        }
    }

    /**
     * Sets the correct permission for the files and directories listed in the extra section.
     * @param array $paths the paths (keys) and the corresponding permission octal strings (values)
     */
    public static function setPermission(array $paths)
    {
        foreach ($paths as $path => $permission) {
            echo "chmod('$path', $permission)...";
            if (is_dir($path) || is_file($path)) {
                chmod($path, octdec($permission));
                echo "done.\n";
            } else {
                echo "file not found.\n";
            }
        }
    }

    protected function loadExtensions()
    {
        $file = $this->vendorDir . '/' . self::EXTENSION_FILE;
        if (!is_file($file)) {
            return [];
        }
        // invalidate opcache of extensions.php if exists
        if (function_exists('opcache_invalidate')) {
            opcache_invalidate($file, true);
        }
        $extensions = require($file);

        $vendorDir = str_replace('\\', '/', $this->vendorDir);
        $n = strlen($vendorDir);

        foreach ($extensions as &$extension) {
            if (isset($extension['alias'])) {
                foreach ($extension['alias'] as $alias => $path) {
                    $path = str_replace('\\', '/', $path);
                    if (strpos($path . '/', $vendorDir . '/') === 0) {
                        $extension['alias'][$alias] = '<vendor-dir>' . substr($path, $n);
                    }
                }
            }
        }

        return $extensions;
    }

    protected function saveExtensions(array $extensions)
    {
        $file = $this->vendorDir . '/' . self::EXTENSION_FILE;
        if (!file_exists(dirname($file))) {
            mkdir(dirname($file), 0777, true);
        }
        $array = str_replace("'<vendor-dir>", '$vendorDir . \'', var_export($extensions, true));
        file_put_contents($file, "<?php\n\n\$vendorDir = dirname(__DIR__);\n\nreturn $array;\n");
        // invalidate opcache of extensions.php if exists
        if (function_exists('opcache_invalidate')) {
            opcache_invalidate($file, true);
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            ScriptEvents::POST_INSTALL_CMD => 'apply',
            ScriptEvents::POST_UPDATE_CMD => 'apply'
        );
    }

    public function apply(CommandEvent $event)
    {
        $composer = $event->getComposer();
        $fs = new Filesystem;

        $this->baseDir = $fs->normalizePath(realpath(getcwd()));
        $this->vendorDir = rtrim($composer->getConfig()->get('vendor-dir'), '/');

        $rootPackage = $composer->getPackage();
        $this->setRootPackage($rootPackage, $event);

        if ($event->getName() === ScriptEvents::POST_INSTALL_CMD) {
            $extra = $rootPackage->getExtra();
            if (isset($extra[self::EXTRA_PERMISSION])) {
                static::setPermission($extra[self::EXTRA_PERMISSION]);
            }
            if (isset($extra[self::EXTRA_SYMLINK])) {
                static::generateSymlink($extra[self::EXTRA_SYMLINK]);
            }
        }

        $extensions = $this->loadExtensions();
        $packages = $composer->getRepositoryManager()->getLocalRepository()->findPackages('deesoft/yii2-composer');
        if (!empty($packages)) {
            /* @var $package PackageInterface */
            $package = reset($packages);
            $extensions[$package->getName()] = [
                'name' => $package->getName(),
                'version' => $package->getVersion(),
                'alias' => [
                    '@dee/composer' => '<vendor-dir>/deesoft/yii2-composer'
                ],
                'bootstrap' => 'dee\\composer\\Bootstrap',
            ];
        } else {
            unset($extensions['deesoft/yii2-composer']);
        }
        $this->saveExtensions($extensions);
    }
}


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use OpenOrchestra\ModelBundle\Document\SiteAlias;
use OpenOrchestra\ModelInterface\Model\SchemeableInterface;
use OpenOrchestra\ModelInterface\Model\SiteInterface;

/**
 * Class AbstractLoadSiteData
 */
abstract class AbstractLoadSiteData extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * @param string $domainName
     * @param string $language
     * @param bool   $main
     * @param string $prefix
     *
     * @return SiteAlias
     */
    protected function generateSiteAlias($domainName, $language, $main = false, $prefix = null)
    {
        $siteAlias = new SiteAlias();
        $siteAlias->setDomain($domainName);
        $siteAlias->setLanguage($language);
        $siteAlias->setMain($main);
        $siteAlias->setPrefix($prefix);
        $siteAlias->setScheme(SchemeableInterface::SCHEME_HTTP);

        return $siteAlias;
    }

    /**
     * @param array         $sitesNames
     * @param array         $sitesLanguages
     * @param SiteInterface $site
     * @param array         $prefixes
     */
    protected function addSitesAliases(array $sitesNames, array $sitesLanguages, $site, array $prefixes = array())
    {
        $master = true;
        foreach ($sitesNames as $siteName ) {
            foreach ($sitesLanguages as $siteLanguage) {
                $prefix = (isset ($prefixes[$siteLanguage]))?$prefixes[$siteLanguage]:null;
                $site->addAlias($this->generateSiteAlias($siteName, $siteLanguage, $master, $prefix));
                $master = false;
            }
        }
    }
}


<?php declare(strict_types=1);
/**
 * Injector for controller methods
 *
 * This class is responsible for injecting a variable number of URL path arguments
 *
 * PHP version 7.0
 *
 * @category   CodeCollab
 * @package    Router
 * @author     Pieter Hordijk <info@pieterhordijk.com>
 * @copyright  Copyright (c) 2015 Pieter Hordijk <https://github.com/PeeHaa>
 * @license    See the LICENSE file
 * @version    1.0.0
 */
namespace CodeCollab\Router;

use Auryn\Injector as Auryn;
use CodeCollab\Http\Response\Response;

/**
 * Injector for controller methods
 *
 * @category   CodeCollab
 * @package    Router
 * @author     Pieter Hordijk <info@pieterhordijk.com>
 */
class Injector
{
    /**
     * @var \Auryn\Injector Instance of an auryn injector
     */
    private $injector;

    /**
     * Creates instance
     *
     * @param \Auryn\Injector $injector Instance of an auryn injector
     */
    public function __construct(Auryn $injector)
    {
        $this->injector = $injector;
    }

    /**
     * Resolves dependencies for and executes a callback
     *
     * @param callable $callback The callback to execute
     * @param array    $vars     The variables to inject
     *
     * @return mixed The return value of the callback
     */
    public function execute(callable $callback, array $vars): Response
    {
        $arguments = $this->resolveDependencies($callback, $vars);

        return call_user_func_array($callback, $arguments);
    }

    /**
     * Resolves dependencies for a callback
     *
     * @param callable $callback The callback to execute
     * @param array    $vars     The variables to inject for string arguments (URL path variables)
     *
     * @return array List of resolved dependencies
     */
    private function resolveDependencies(callable $callback, array $vars): array
    {
        $method = new \ReflectionMethod($callback[0], $callback[1]);

        $dependencies = [];

        foreach ($method->getParameters() as $parameter) {
            if ($parameter->getClass() === null && !count($vars)) {
                break;
            }

            if ($parameter->getClass() === null && count($vars)) {
                $dependencies[] = array_shift($vars);

                continue;
            }

            $dependencies[] = $this->injector->make($parameter->getClass()->name);
        }

        return $dependencies;
    }
}


<?php
namespace eMacros\Runtime\Collection;

use eMacros\Applicable;
use eMacros\Scope;
use eMacros\GenericList;
use eMacros\Symbol;

class ArrayPop implements Applicable {
	/**
	 * Pops and returns the last value of an array
	 * Usage: (Array::pop _arr)
	 * Returns: mixed
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		if (count($arguments) == 0) throw new \BadFunctionCallException("ArrayPop: No target specified.");
		$target = $arguments[0];
		if (!($target instanceof Symbol))
			throw new \InvalidArgumentException(sprintf("ArrayPop: Expected symbol as first argument but %s was found instead.", substr(strtolower(strstr(get_class($arguments[0]), '\\')), 1)));
		$ref = $target->symbol;
		if (is_array($scope->symbols[$ref])) return array_pop($scope->symbols[$ref]);
		elseif ($scope->symbols[$ref] instanceof \ArrayObject) {
			$arr = $scope->symbols[$ref]->getArrayCopy();
			$value = array_pop($arr);
			if (count($scope->symbols[$ref]->getArrayCopy()) != 0)
				$scope->symbols[$ref]->exchangeArray($arr);
			return $value;
		}

		throw new \InvalidArgumentException(sprintf("ArrayPop: Expected array as first argument but %s was found instead.", gettype($scope->symbols[$ref])));
	}
}
?>


<?php
namespace eMacros\Runtime\Logical;

use eMacros\Applicable;
use eMacros\Scope;
use eMacros\GenericList;

class LogicalAnd implements Applicable {
	/**
	 * Applies a logical AND to all operands
	 * Usage: (and true true) (and true true false)
	 * Returns: boolean
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
    public function apply(Scope $scope, GenericList $operands) {
    	if (count($operands) == 0) throw new \BadFunctionCallException("And: No parameters found.");

        foreach ($operands as $expr) {
            if (!$value = $expr->evaluate($scope)) return $value;
        }

        return $value;
    }
}


<?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/georadius
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class GEORADIUS extends RedisCommand
{
    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return 'GEORADIUS';
    }

    /**
     * {@inheritdoc}
     */
    public function setArguments(array $arguments)
    {
        if ($arguments && is_array(end($arguments))) {
            $options = array_change_key_case(array_pop($arguments), CASE_UPPER);

            if (isset($options['WITHCOORD']) && $options['WITHCOORD'] == true) {
                $arguments[] = 'WITHCOORD';
            }

            if (isset($options['WITHDIST']) && $options['WITHDIST'] == true) {
                $arguments[] = 'WITHDIST';
            }

            if (isset($options['WITHHASH']) && $options['WITHHASH'] == true) {
                $arguments[] = 'WITHHASH';
            }

            if (isset($options['COUNT'])) {
                $arguments[] = 'COUNT';
                $arguments[] = $options['COUNT'];
            }

            if (isset($options['SORT'])) {
                $arguments[] = strtoupper($options['SORT']);
            }

            if (isset($options['STORE'])) {
                $arguments[] = 'STORE';
                $arguments[] = $options['STORE'];
            }

            if (isset($options['STOREDIST'])) {
                $arguments[] = 'STOREDIST';
                $arguments[] = $options['STOREDIST'];
            }
        }

        parent::setArguments($arguments);
    }
}


<?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\Content\BlockManager;

use JMS\Serializer\SerializerInterface;
use RedKiteCms\Content\Block\BlockFactoryInterface;
use RedKiteCms\FilesystemEntity\FilesystemEntity;
use RedKiteCms\Tools\FilesystemTools;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class BlockManager is the base object assigned to handle a block
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\BlockManager
 */
abstract class BlockManager extends FilesystemEntity
{
    /**
     * @type bool
     */
    protected $optionsResolved = false;
    /**
     * @type \RedKiteCms\Content\Block\BlockFactoryInterface
     */
    protected $blockFactory;

    /**
     * @param \JMS\Serializer\SerializerInterface                $serializer
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver
     */
    public function __construct(SerializerInterface $serializer, OptionsResolver $resolver)
    {
        parent::__construct($serializer, $resolver);

        $this->filesystem = new Filesystem();
    }

    /**
     * Defines the common required options by a block manager
     *
     * @param array $options
     */
    protected function resolveOptions(array $options)
    {
        if ($this->optionsResolved) {
            return;
        }

        $this->optionsResolver->clear();
        $this->optionsResolver->setRequired(
            array(
                'blockname',
            )
        );

        parent::resolveOptions($options);
        $this->optionsResolved = true;
    }

    /**
     * Creates the contributor folder
     *
     * @param string $sourceDir
     * @param array $options
     * @param string $username
     */
    protected function createContributorDir($sourceDir, array $options, $username)
    {
        if (null === $username) {
            return;
        }

        $this->init($sourceDir, $options, $username);
        if (is_dir($this->contributorDir)) {
            return;
        }

        $this->filesystem->copy($this->productionDir . '/slot.json', $this->contributorDir . '/slot.json', true);
        $this->filesystem->mirror($this->productionDir . '/blocks', $this->contributorDir . '/blocks');
    }

    /**
     * Adds a default block to the given slot
     *
     * @param string $dir
     * @param array $options
     *
     * @return string
     */
    protected function addBlockToSlot($dir, array $options)
    {
        $slot = $this->getSlotDefinition($dir);
        $blocks = $slot["blocks"];
        $blockName = $options["blockname"];
        $position = $options["position"];
        array_splice($blocks, $position, 0, $blockName);

        $slot["next"] = str_replace('block', '', $blockName) + 1;
        $slot["blocks"] = $blocks;

        $this->saveSlotDefinition($dir, $slot);

        return $blockName;
    }

    /**
     * Fetches the slot definition
     *
     * @param string $dir
     *
     * @return array
     */
    protected function getSlotDefinition($dir)
    {
        $slotsFilename = $this->getSlotDefinitionFile($dir);

        return json_decode(FilesystemTools::readFile($slotsFilename), true);
    }

    /**
     * Gets the slot file
     *
     * @param string $dir
     *
     * @return string
     */
    protected function getSlotDefinitionFile($dir)
    {
        return sprintf('%s/slot.json', $dir);
    }

    /**
     * Saves the slot definition
     *
     * @param string $dir
     * @param array $slot
     */
    protected function saveSlotDefinition($dir, array $slot)
    {
        $slotsFilename = $this->getSlotDefinitionFile($dir);

        FilesystemTools::writeFile($slotsFilename, json_encode($slot), $this->filesystem);
    }

    /**
     * Removes a block from the slot files and returns back the block name
     *
     * @param array $options
     * @param string $targetDir
     *
     * @return string
     */
    protected function removeBlockFromSlotFile(array $options, $targetDir = null)
    {
        $targetDir = $this->workDirectory($targetDir);

        $slot = $this->getSlotDefinition($targetDir);
        $blockName = $options["blockname"];

        $tmp = array_flip($slot["blocks"]);
        unset($tmp[$blockName]);
        $slot["blocks"] = array_keys($tmp);

        $this->saveSlotDefinition($targetDir, $slot);

        return $blockName;
    }
}


<?php
/**
 * Created by Marcin.
 * Date: 22.10.2017
 * Time: 23:01
 */

namespace mrcnpdlk\Monolog;

class Helper
{
    /**
     * @param $var
     *
     * @return string
     */
    public static function logSuffix($var)
    {
        ob_start();

        if (is_string($var)) {
            echo $var;
        } else {
            var_export($var);
        }

        return sprintf('%s%s%s%s%s%s',
            str_repeat("-=", 15),
            PHP_EOL,
            ob_get_clean(),
            PHP_EOL,
            str_repeat("=-", 15),
            PHP_EOL
        );
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Repository;

use OpenOrchestra\ModelInterface\Model\ReadBlockInterface;
use OpenOrchestra\ModelInterface\Repository\BlockRepositoryInterface;
use OpenOrchestra\Pagination\Configuration\PaginateFinderConfiguration;
use OpenOrchestra\Repository\AbstractAggregateRepository;
use Solution\MongoAggregation\Pipeline\Stage;

/**
 * Class BlockRepository
 */
class BlockRepository extends AbstractAggregateRepository implements BlockRepositoryInterface
{
    /**
     * @param string $id
     *
     * @return null|\OpenOrchestra\ModelInterface\Model\ReadBlockInterface
     */
    public function findById($id) {
        return $this->find(new \MongoId($id));
    }

    /**
     * @param string $component
     * @param string $siteId
     * @param string $language
     *
     * @return array
     */
    public function findTransverseBlock($component, $siteId, $language)
    {
        $qa = $this->createAggregationQueryBuilderWithSiteIdAndLanguage($siteId, $language, true);

        $qa->match(array(
            'component' => $component
        ));

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

    /**
     * @param string $code
     * @param string $language
     * @param string $siteId
     *
     * @return ReadBlockInterface|null
     */
    public function findOneTransverseBlockByCode($code, $language, $siteId)
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array(
            'code' => $code,
            'language' => $language,
            'siteId' => $siteId,
            'transverse' => true
        ));

        return $this->singleHydrateAggregateQuery($qa);

    }

    /**
     * @param string                      $siteId
     * @param string                      $language
     * @param PaginateFinderConfiguration $configuration
     * @param boolean                     $transverse
     *
     * @return array
     */
    public function findForPaginateBySiteIdAndLanguage(
        PaginateFinderConfiguration $configuration,
        $siteId,
        $language,
        $transverse
    ) {
        $qa = $this->createAggregationQueryBuilderWithSiteIdAndLanguage($siteId, $language, $transverse);
        $this->filterSearch($configuration, $qa);

        $order = $configuration->getOrder();
        if (!empty($order)) {
            $qa->sort($order);
        }

        $qa->skip($configuration->getSkip());
        $qa->limit($configuration->getLimit());

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

    /**
     * @param string                      $siteId
     * @param string                      $language
     * @param PaginateFinderConfiguration $configuration
     * @param boolean                     $transverse
     *
     * @return int
     */
    public function countWithFilterBySiteIdAndLanguage(
        PaginateFinderConfiguration $configuration,
        $siteId,
        $language,
        $transverse
    ) {
        $qa = $this->createAggregationQueryBuilderWithSiteIdAndLanguage($siteId, $language, $transverse);
        $this->filterSearch($configuration, $qa);

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

    /**
     * @param string  $siteId
     * @param string  $language
     * @param boolean $transverse
     *
     * @return int
     */
    public function countBySiteIdAndLanguage($siteId, $language, $transverse)
    {
        $qa = $this->createAggregationQueryBuilderWithSiteIdAndLanguage($siteId, $language, $transverse);

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

    /**
     * @param PaginateFinderConfiguration $configuration
     * @param Stage                       $qa
     *
     * @return array
     */
    protected function filterSearch(PaginateFinderConfiguration $configuration, Stage $qa)
    {
        $filter = array();
        $label = $configuration->getSearchIndex('label');
        if (null !== $label && $label !== '') {
            $filter['label'] = new \MongoRegex('/.*'.$label.'.*/i');
        }

        $components = $configuration->getSearchIndex('components');
        if (null !== $components && is_array($components) && !empty($components)) {
            $filter['component'] =  array('$in' => $components);
        }

        if (!empty($filter)) {
            $qa->match($filter);
        }

        return $qa;
    }

    /**
     * @param string  $siteId
     * @param string  $language
     * @param boolean $transverse
     *
     * @return Stage
     */
    protected function createAggregationQueryBuilderWithSiteIdAndLanguage($siteId, $language, $transverse)
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array(
            'siteId' => $siteId,
            'language' => $language,
            'transverse' => $transverse
        ));

        return $qa;
    }
}


<?php

namespace Reliv\Mustache\Resolver;

use Phly\Mustache\Resolver\ResolverInterface;

/**
 * @author James Jervis - https://github.com/jerv13
 */
class StringResolver implements ResolverInterface
{
    const DEFAULT_NAMESPACE = '__DEFAULT__';

    /**
     * @var array
     */
    protected $templates
        = [
            self::DEFAULT_NAMESPACE => '<!-- TEMPLATE MISSING -->'
        ];

    /**
     * @param array $templates
     */
    public function __construct(
        array $templates = []
    ) {
        $this->addTemplates($templates);
    }

    /**
     * @param array $templates
     *
     * @return void
     */
    public function addTemplates(array $templates)
    {
        foreach ($templates as $name => $html) {
            $this->addTemplate($name, $html);
        }
    }

    /**
     * @param string $name
     * @param string $html
     *
     * @return void
     */
    public function addTemplate(string $name, string $html)
    {
        $this->templates[$name] = $html;
    }

    /**
     * @param string $name
     *
     * @return string
     */
    public function getTemplate(string $name)
    {
        if ($this->hasTemplate($name)) {
            return $this->templates[$name];
        }

        return $this->templates[self::DEFAULT_NAMESPACE];
    }

    /**
     * @param string $name
     *
     * @return bool
     */
    public function hasTemplate(string $name)
    {
        return array_key_exists($name, $this->templates);
    }

    /**
     * Resolve a template name
     *
     * Resolve a template name to mustache content or a set of tokens.
     *
     * @param  string $template
     *
     * @return string|array
     */
    public function resolve($template)
    {
        return $this->getTemplate($template);
    }
}


<?php

namespace Ken\View\TwigEngine;

use Twig_Environment;
use Twig_Loader_Filesystem;
use Twig_SimpleFunction;
use Ken\View\BaseEngine;

/**
 * @author Juliardi <ardi93@gmail.com>
 */
class TwigEngine extends BaseEngine
{
    /**
     * @var Twig_Environment
     */
    protected $engine;

    /**
     * @var \Ken\TwigEngine\FunctionGenerator
     */
    protected $functionGenerator;

    public function __construct($config)
    {
        parent::__construct($config);
        if (!isset($config['functionGenerator'])) {
            $config['functionGenerator'] = __NAMESPACE__.'\FunctionGenerator';
        }
        $this->initFunctionGenerator($config['functionGenerator']);
        $this->initEngine();
    }

    /**
     * Inits custom function generator.
     */
    protected function initFunctionGenerator($generatorClass)
    {
        $this->functionGenerator = $generatorClass::build();
    }

    /**
     * {@inheritdoc}
     */
    protected function initEngine()
    {
        $loader = new Twig_Loader_Filesystem($this->viewPath);

        if (!empty($this->cachePath)) {
            $this->engine = new Twig_Environment($loader, array(
                'cache' => $this->cachePath,
            ));
        } else {
            $this->engine = new Twig_Environment($loader);
        }

        $this->registerCustomFunctions();
    }

    /**
     * Registers custom functions.
     */
    protected function registerCustomFunctions()
    {
        $functionList = $this->functionGenerator->getFunctionList();

        foreach ($functionList as $function) {
            if (isset($function['name']) && isset($function['callable'])) {
                $twigFunction = new Twig_SimpleFunction($function['name'], $function['callable']);
                $this->engine->addFunction($twigFunction);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function render($view, array $params = [])
    {
        $view = $this->suffixExtension($view);

        echo $this->engine->render($view, $params);
    }

    /**
     * {@inheritdoc}
     */
    protected function getFileExtension()
    {
        return 'twig';
    }
}


<?php

namespace Mediawiki\Db\Service;

use FluentPDO;
use Mediawiki\DataModel\User;
use MediaWiki\Services\UserGetter;
use PDO;

/**
 * @author Bene* < benestar.wikimedia@gmail.com >
 */
class DatabaseUserGetter implements UserGetter {

	/**
	 * @var FluentPDO
	 */
	private $db;

	/**
	 * @param PDO $db
	 */
	public function __construct( PDO $db ) {
		$this->db = new FluentPDO( $db );
	}

	/**
	 * @param string $userName
	 *
	 * @return User
	 */
	public function getUser( $userName ) {
		$users = $this->getUsers( array( $userName ) );
		return count( $users ) ? $user[0] : null;
	}

	/**
	 * @param string[] $userNames
	 *
	 * @return User[]
	 */
	public function getUsers( array $userNames ) {
		$query = $this->db->from( 'user' )
			->select( 'user_id', 'user_name', 'user_editcount', 'user_registration', 'ug_group' )
			->leftJoin( 'user_groups ON user_id = ug_user' )
			->where( 'user_name', $userNames );

		$users = array();
		$rows = $query->fetchAll();

		$userGroups = $this->getGroupsPerUser( $rows );

		foreach ( $rows as $row ) {
			$users[] = $this->getUserFromRow( $row, $userGroups[$row['user_id']] );
		}

		return $users;
	}

	private function getGroupsPerUser( array $rows ) {
		$userGroups = array();

		foreach ( $rows as $row ) {
			$userGroups[$row['user_id']][] = $row['ug_group'];
		}

		return $userGroups;
	}

	private function getUserFromRow( array $row, array $groups ) {
		return new User(
			$row['user_name'],
			$row['user_id'],
			$row['user_editcount'],
			$row['user_registration'],
			array( 'groups' => $groups ),
			array(),
			''
		);
	}

}


<?php
/*
 * This file is a part of Solve framework.
 *
 * @author Alexandr Viniychuk <alexandr.viniychuk@icloud.com>
 * @copyright 2009-2014, Alexandr Viniychuk
 * created: 05.01.14 10:19
 */

namespace Solve\Slot;

use Solve\Slot\Blocks\BaseBlock;
use Solve\Storage\ArrayStorage;
use Solve\Utils\Inflector;

/**
 * Class Compiler
 * @package Solve\Slot
 *
 * Class Compiler is used to ...
 *
 * @version 1.0
 * @author Alexandr Viniychuk <alexandr.viniychuk@icloud.com>
 */
class Compiler {

    /**
     * @var ArrayStorage tokens found stack
     */
    private $_tokenStack;

    /**
     * @var ArrayStorage registered blocks
     */
    private $_blocks;

    /**
     * @var array used for syntax check
     */
    private $_expectations = array();

    /**
     * @var ArrayStorage
     */
    private $_config = array(
        'commentStart' => '{#',
        'commentEnd'   => '#}',

        'tokenStart'   => '{{',
        'tokenEnd'     => '}}',

        'blockClose'   => 'end',
    );

    private $_escapingStrategy = 'html';
    /**
     * @var Slot instance of SLOT class
     */
    private $_slotInstance;

    private $_hashesQuoted  = array();
    private $_hashScopeChar = '@';
    private $_literalsCache = array();

    /**
     * @var array methods that available as system modifiers
     */
    private $_predefinedMethods = array(
        'empty', 'is_null', 'isset', 'var_dump'
    );

    /**
     * @param Slot $slot
     */
    public function __construct(Slot $slot = null) {
        $this->_config = new ArrayStorage((array)$this->_config);

        $this->_tokenStack   = new ArrayStorage();
        $this->_blocks       = new ArrayStorage();
        $this->_slotInstance = $slot;
    }

    /**
     * Set config value partially of completely
     * @param $name
     * @param $value
     * @return $this
     */
    public function setConfig($name, $value) {
        if (is_null($name)) {
            $this->_config = new ArrayStorage($value);
        } else {
            $this->_config->setDeepValue($name, $value);
        }
        return $this;
    }

    /**
     * Register functional block for compiler. Each block should be represented with Class
     * @param $blockTag
     * @param $info
     */
    public function registerBlock($blockTag, $info) {
        $this->_blocks[$blockTag] = $info;
    }

    /**
     * @param $source
     * @return mixed
     */
    public function stripComments($source) {
        $source = preg_replace('/' . $this->_config['commentStart'] . '.*' . $this->_config['commentEnd'] . '/sU', '', $source);
        return $source;
    }

    public function saveLiterals($source) {
        $literalTokenStart = '#' . $this->_config['tokenStart'] . '\s*literal\s*' . $this->_config['tokenEnd'] . '#';
        $literalTokenEnd   = '#' . $this->_config['tokenStart'] . '\s*literalend\s*' . $this->_config['tokenEnd'] . '#';

        $starts = array();
        preg_match_all($literalTokenStart, $source, $starts, PREG_OFFSET_CAPTURE);
        if (!empty($starts[0])) {
            $result = '';
            $ends = array();
            preg_match_all($literalTokenEnd, $source, $ends, PREG_OFFSET_CAPTURE, $starts[0][0][1]);
            if (count($starts[0]) !== count($ends[0])) {
                throw new \Exception('Invalid {{ literal }} tags count');
            }
            $literalsIndex = count($this->_literalsCache);
            $previousEndIndex = 0;
            foreach ($starts[0] as $index => $location) {

                $result .= substr($source, $previousEndIndex, $location[1] - $previousEndIndex) . '__LITERAL'.$literalsIndex.'__';
                $contentStartPosition = $location[1] + strlen($location[0]);
                $this->_literalsCache[$literalsIndex] = array(
                    'start' => $location[1],
                    'end'   => $ends[0][$index][1] + strlen($ends[0][$index][0]),
                    'content' => substr($source, $contentStartPosition, $ends[0][$index][1] - $contentStartPosition)
                );
                $previousEndIndex = $this->_literalsCache[$literalsIndex]['end'];
                $literalsIndex++;
            }
            $source = $result . substr($source, $previousEndIndex);
        }
        return $source;
    }

    public function restoreLiterals($source) {
        if (empty($this->_literalsCache)) return $source;

        $source = preg_replace_callback('#__LITERAL(\d+)__#', array($this, 'onRestoreLiterals'), $source);
        return $source;
    }

    private function onRestoreLiterals($matches) {
        if (array_key_exists($matches[1], $this->_literalsCache)) {
            $content = $this->_literalsCache[$matches[1]];
            unset($this->_literalsCache[$matches[1]]);
            return $content['content'];
        } else {
            return "";
        }
    }

    /**
     * @param string $expression
     * @return string result
     */
    public function compileExpression($expression) {
        $expression    = trim($expression);
        $quotedPattern = "#(?:(?:\"(?:\\\\\"|[^\"])+\")|(?:'(?:\\'|[^'])+'))#isU";
//        $matches = array();
//        preg_match_all($quotedPattern, $expression, $matches);
        $expression = preg_replace_callback($quotedPattern, array($this, '_quotesRegexpCallback'), $expression);

        $expression = $this->_processUnquotedExpression($expression);
        $expression = str_replace(array_keys($this->_hashesQuoted), $this->_hashesQuoted, $expression);
        $expression = str_replace('~', '.', $expression);
        return $expression;
    }

    private function _processUnquotedExpression($expression) {
        $isSimpleExpression = true;
        $highLevelHash      = array();

        $squareBracePattern = '#\[[^\s]+\]#ism';
        $braced             = array();
        preg_match_all($squareBracePattern, $expression, $braced);
        if (!empty($braced[0])) {
            foreach ($braced[0] as $item) {
                $hash                 = $this->getHash($item);
                $highLevelHash[$hash] = '[' . $this->_processUnquotedExpression(substr($item, 1, -1)) . ']';
                $expression           = str_replace($item, $hash, $expression);
            }
        }

        $simpleBracePattern = '#\((([^()]+|(?R))*)\)#ism';
        $braced             = array();
        preg_match_all($simpleBracePattern, $expression, $braced);
        if (!empty($braced[0])) {
            foreach ($braced[0] as $item) {
                if ($item == '()') continue;

                $hash                 = $this->getHash($item);
                $highLevelHash[$hash] = '(' . $this->_processUnquotedExpression(substr($item, 1, -1)) . ')';
                $expression           = str_replace($item, $hash, $expression);
            }
        }

        if (strpos($expression, ' ') !== false) {
            $spacedParts  = array();
            $spacePattern = '#"(?:\\\\.|[^\\\\"])*"|\S+#';
            preg_match_all($spacePattern, $expression, $spacedParts);
            if (!empty($spacedParts[0])) {
                $expression = '';
                foreach ($spacedParts[0] as $item) {
                    $expression .= ' ' . $this->_processUnquotedExpression($item);
                }
                $expression         = substr($expression, 1);
                $isSimpleExpression = false;
            }
        }

        if (strpos($expression, '..') !== false) {
            $rangeRegexp = '#(?P<range>(["\'._\w\d]+)\.\.(["\'._\w\d]+))#isu';
            $ranges      = array();
            preg_match_all($rangeRegexp, $expression, $ranges);
            foreach ($ranges['range'] as $range) {
                $rangeParts           = explode('..', $range);
                $compiledRange        = 'range(' . $this->compileExpression($rangeParts[0]) . ', ' . $this->compileExpression($rangeParts[1]) . ')';
                $hash                 = $this->getHash($range);
                $highLevelHash[$hash] = $compiledRange;
                $expression           = str_replace($range, $hash, $expression);
            }
        }

        if ($isSimpleExpression) {
            $modifiersInfo = $this->_processModifiers($expression);
            $expression    = $modifiersInfo[0];
            if (strpos($expression, '.') !== false) {
                $pointPattern = '#\.#';
                $pointedParts = preg_split($pointPattern, $expression, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
                $expression   = array_shift($pointedParts);
                foreach ($pointedParts as $part) {
                    if ($this->checkForSimpleString($part)) {
                        $value = '[\'' . $part . '\']';
                    } else {
                        $value = '[' . $this->_processUnquotedExpression($part) . ']';
                    }
                    $hash                 = $this->getHash($value);
                    $highLevelHash[$hash] = $value;
                    $expression .= $hash;
                }
            }
            $varPattern = '#' . $this->_hashScopeChar . '\w+' . $this->_hashScopeChar . '|(->)?\w+(\|[_\w\d:]+)?#is';
            $expression = preg_replace_callback($varPattern, array($this, '_varRegexpCallback'), $expression);
            if (!empty($modifiersInfo[1])) {
                $expression = $modifiersInfo[1] . $expression . $modifiersInfo[2];
            }
        }

        $highLevelHash = array_reverse($highLevelHash);
        $expression    = str_replace(array_keys($highLevelHash), $highLevelHash, $expression);
        return $expression;
    }

    public function checkForSimpleString($expression) {
        $matches = array();
        preg_match('#[_\w]{1}[_\w\d]*#', $expression, $matches);
        return $matches[0] === $expression;
    }

    /**
     * Preg match replace callback
     * @param $pregMatchResult
     * @return string
     */
    private function _varRegexpCallback($pregMatchResult) {
        $var = $pregMatchResult[0];
        if (($var[0] == $this->_hashScopeChar) && ($var[strlen($var) - 1] == $this->_hashScopeChar)) {
            return $var;
        }
        if (is_numeric($var) || $var === "true" || $var === "false") {
            return $var;
        }
        if (!empty($pregMatchResult[1]) && ($pregMatchResult[1] == '->')) {
            return $var;
        }
        $info = $this->_processModifiers($var);

        return $info[1] . '$__lv[\'' . $info[0] . '\']' . $info[2];
    }

    /**
     * Preg match replace callback
     * @param $pregMatchResult
     * @return string
     */
    private function _quotesRegexpCallback($pregMatchResult) {
        $hash                       = $this->getHash($pregMatchResult[0]);
        $this->_hashesQuoted[$hash] = $pregMatchResult[0];
        return $hash;
    }

    private function getHash($string) {
        return $this->_hashScopeChar . md5($string) . $this->_hashScopeChar;
    }

    /**
     * Main compilartor function
     * @param $source
     * @return mixed
     */
    public function compileSource($source) {
        $source = $this->stripComments($source);
        $source = $this->saveLiterals($source);

        $result = preg_replace_callback('#' . $this->_config['tokenStart'] . '(.*)' . $this->_config['tokenEnd'] . '#smU', array($this, 'onTokenFound'), $source);
        $result = $this->restoreLiterals($result);
        return $result;
    }

    /**
     * Since it called step by step we can create context for each tag
     * @param $token
     * @return string
     */
    private function onTokenFound($token) {
        if (is_array($token)) $token = array_pop($token);
        $token = trim($token);

        $tokenParts = explode(' ', $token);
        $tag        = array_shift($tokenParts);
        $params     = implode(' ', $tokenParts);

        if ($this->_blocks->has($tag)) {
            if ($this->_blocks->getDeepValue($tag . '/runtime')) {
                $res = '<?php $this->_compiler->invokeBlock(\'' . $tag . '\', ' . $this->compileExpression($params) . '); ?>';
            } else {
                $res = $this->onBlockTagOpen($tag, $params);
            }
        } elseif (substr($tag, 0, strlen($this->_config['blockClose'])) == $this->_config['blockClose']) {
            $tag = substr($tag, strlen($this->_config['blockClose']));
            $res = $this->onBlockTagClose($tag, $params);
        } else {
            $res = $this->onVarEchoToken($token, $params);
        }
        return $res;
    }

    /**
     * Add modifier surrounding for expression
     * @param $expression
     * @return array
     * @throws \Exception
     */
    private function _processModifiers($expression) {
        $mStart  = '';
        $mEnd    = '';
        $rawEcho = false;

        /** process modifiers */
        if (strpos($expression, '|') !== false && strpos($expression, '||') === false) {
            $modifiers  = explode('|', $expression);
            $expression = array_shift($modifiers);
            foreach ($modifiers as $modifier) {
                $params = array();
                if (strpos($modifier, ':') !== false) {
                    $params   = explode(':', $modifier);
                    $modifier = array_shift($params);
                }
                if ($modifier == 'raw') {
                    $rawEcho = true;
                    continue;
                }

                if ($this->isCallable($modifier)) {
                    $mStart = $modifier . '(' . $mStart;
                    if ($modifier !== 'raw') {
                        foreach ($params as $param) {
                            $mEnd .= ', ' . $this->compileExpression($param);
                        }
                    }
                    $mEnd .= ')';
                } else {
                    throw new \Exception('SLOT compiler error: undefined modifier ' . $modifier);
                }
            }
        }

        return array(
            $expression,
            $mStart,
            $mEnd,
            $rawEcho
        );
    }

    private function onVarEchoToken($token) {
        $res = '<?php ';

        $varExpression = $this->compileExpression($token);
        $varValue      = $varExpression;
        $isFunctional  = preg_match('#[-+*/\(|]+#', $varValue);
        $isRaw         = strpos($token, 'raw') !== false;
        /** process 01.vars escaping strategies */
        if ($this->getEscapingStrategy() == 'html' && $isRaw && !$isFunctional) {
            if (strpos($varExpression, 'htmlentities') === false) {
                $varValue = 'htmlentities(' . $varValue . ', ENT_COMPAT, "UTF-8")';
            }
        }

        if (!$isRaw && ($isFunctional || (strpos($varValue, '$') === false))) {
            $res .= 'echo ' . $varValue;
        } elseif ($isRaw) {
            if (strpos($token, 'raw:bool') !== false) {
                $res .= 'echo ' . $varValue . '? "true" : "false"';
            } else {
                $res .= 'echo ' . $varValue;
            }
        } else {
            $res .= 'echo isset(' . $varExpression . ') ? ' . $varValue . ': ""';
        }
        $res .= '; ?>';
        return $res;
    }

    public function invokeBlock($tag, $params) {
        echo $this->onBlockTagOpen($tag, $params);
    }

    /**
     * @param $tag
     * @param $token
     * @return string
     */
    private function onBlockTagOpen($tag, $token) {
        if ($this->_blocks->getDeepValue($tag . '/paired')) {
            $this->_expectations[] = $tag;
        }
        /**
         * @var BaseBlock $blockObject
         */
        $blockObject         = $this->getBlockObject($tag, $token);
        $this->_tokenStack[] = $blockObject;

        return $blockObject->processBlockStart();
    }

    /**
     * @param $tag
     * @param $token
     * @return string
     * @throws \Exception
     */
    private function onBlockTagClose($tag, $token) {
        if ($this->_blocks->getDeepValue($tag . '/paired')) {
            if (!empty($this->_expectations)) {
                $expected = $this->_expectations[count($this->_expectations) - 1];
                if ($expected != $tag) {
                    throw new \Exception('Error parsing template: Unexpected tag "' . $tag . '", expected: "' . $expected . '"');
                } else {
                    array_pop($this->_expectations);
                }
            }
        } else {
            throw new \Exception('Error parsing template: Unexpected closing tag');
        }

        $blockObject = $this->getBlockObject($tag, $token);

        return $blockObject->processBlockEnd();
    }

    /**
     * @param $tag\
     * @param $token
     * @return BaseBlock
     */
    private function getBlockObject($tag, $token) {
        $namespace      = isset($this->_blocks[$tag]['namespace']) ? $this->_blocks[$tag]['namespace'] : '\Solve\Slot\Blocks\\';
        $blockClassName = $namespace . Inflector::camelize($tag . 'Block');
        /**
         * @var BaseBlock $blockObject
         */
        $blockObject = new $blockClassName($token, $this);
        return $blockObject;
    }

    private function isCallable($callable) {
        return in_array($callable, $this->_predefinedMethods) || $callable[0] === '!' || is_callable($callable);
    }

    /**
     * @param string $escapingStrategy
     */
    public function setEscapingStrategy($escapingStrategy) {
        $this->_escapingStrategy = $escapingStrategy;
    }

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

    /**
     * Set Slot instance
     * @param Slot $slot
     */
    public function setSlot(Slot $slot) {
        $this->_slotInstance = $slot;
    }

    /**
     * Get Slot instance
     * @return Slot
     */
    public function getSlot() {
        return $this->_slotInstance;
    }

    public function parseSpacedArguments($string) {
        $string       = trim($string);
        $spacedParts  = array();
        $spacePattern = '#"(?:\\\\.|[^\\\\"])*"|\S+#';
        preg_match_all($spacePattern, $string, $spacedParts);

        return $spacedParts[0];
    }

}


<?php

namespace Esockets\Socket;

use Esockets\Base\Exception\ConnectionException;
use Esockets\Debug\Log;

/**
 * Общий обработчик ошибок, возникающих при работе с сокетами.
 * Выполняет две функции: определение деструктивной степени ошибки,
 * и выброс исключения @see ConnectionException в случае возникновения серьезной ошибки.
 *
 * Для каждого объекта с подключением создается собственный объект handler-а...
 */
final class SocketErrorHandler
{
    /** Константы внутренних ошибок. */
    const ERROR_NOTHING = 0;    // нет ошибки
    const ERROR_AGAIN = 1;      // ошибка, просьба повторить операцию
    const ERROR_SKIP = 2;       // ошибка, просьба пропустить операцию
    const ERROR_DISCONNECTED = 4;      // фатальная ошибка
    const ERROR_UNKNOWN = 8;    // неизвестная необрабатываемая ошибка
    /** Список известных ошибок для настройки обработчика */
    const ERRORS_KNOW = [
        'SOCKET_EWOULDBLOCK' => self::ERROR_NOTHING,
        'SOCKET_EMSGSIZE' => self::ERROR_NOTHING,
        'SOCKET_EAGAIN' => self::ERROR_AGAIN,
        'SOCKET_TRY_AGAIN' => self::ERROR_AGAIN,
        'SOCKET_EPIPE' => self::ERROR_DISCONNECTED,
        'SOCKET_ENOTCONN' => self::ERROR_DISCONNECTED,
        'SOCKET_ECONNABORTED' => self::ERROR_DISCONNECTED,
        'SOCKET_ECONNRESET' => self::ERROR_DISCONNECTED,
    ];
    /**
     * @var array Известные и обрабатываемые ошибки сокетов
     */
    protected static $catchableErrors = [];
    private $socket;

    /**
     * @param null $socket
     *
     * @throws ConnectionException
     */
    public function __construct($socket = null)
    {
        if (null !== $socket) {
            if (!is_resource($socket)) {
                throw new ConnectionException('Socket don\'t is resource');
            } elseif (get_resource_type($socket) !== 'Socket') {
                throw new ConnectionException('Unknown resource type: ' . get_resource_type($socket));
            }
        }
        $this->socket = $socket;
        $this->checkConstants();
    }

    /**
     * Функция проверяет, установлены ли некоторые константы обрабатываемых ошибок сокетов.
     */
    protected function checkConstants()
    {
        if (!defined('SOCKET_ENOENT')) {
            define('SOCKET_ENOENT', 2);
        }
        if (!empty(self::$catchableErrors)) return;
        foreach (self::ERRORS_KNOW as $const => $selfType) {
            if (defined($const)) {
                self::$catchableErrors[constant($const)] = $selfType;
            }
        }
    }

    /**
     * @param $socket
     *
     * @throws ConnectionException
     */
    public function setSocket($socket)
    {
        if (!is_resource($socket)) {
            throw new ConnectionException('Socket don\'t is resource');
        } elseif (get_resource_type($socket) !== 'Socket') {
            throw new ConnectionException('Unknown resource type: ' . get_resource_type($socket));
        }
        $this->socket = $socket;
    }

    /**
     * Функция возвращает одну из констант self::ERROR_*
     * Параметр $operation - номер операции; 1 = запись, 0 = чтение.
     *
     * @param int $operation
     *
     * @return int
     */
    public function getErrorLevel(int $operation): int
    {
        if (!is_resource($this->socket) || !get_resource_type($this->socket) === 'Socket') {
            $errno = SOCKET_EPIPE;
        } else {
            $errno = socket_last_error($this->socket);
        }
        if ($errno === 0) {
            return self::ERROR_NOTHING;
        } elseif (isset(self::$catchableErrors[$errno])) {
            if (
                self::$catchableErrors[$errno] !== self::ERROR_NOTHING
                && self::$catchableErrors[$errno] !== self::ERROR_AGAIN // for unix-like systems
            ) {
                Log::log(sprintf(
                    'Socket catch error %s at %s: %d',
                    socket_strerror($errno),
                    $operation ? 'WRITING' : 'READING',
                    $errno
                ));
            }
            return self::$catchableErrors[$errno];
        } else {
            Log::log(sprintf('Unknown socket error %d: %s', $errno, socket_strerror($errno)));
            return self::ERROR_UNKNOWN;
        }
    }

    /**
     * @throws ConnectionException
     */
    public function handleError()
    {
        if (is_resource($this->socket)) {
            $error = socket_last_error($this->socket);
        } else {
            $error = socket_last_error();
        }
        $errorMessage = socket_strerror($error);
        if (PHP_OS === 'WINNT') {
            $errorMessage = mb_convert_encoding($errorMessage, 'utf-8', 'windows-1251');
        }
        switch ($error) {
            case 0:
            case SOCKET_EWOULDBLOCK: // операции на незаблокированном сокет
            case SOCKET_EMSGSIZE:
            case SOCKET_ECONNRESET:
                // ничего не делаем.
                break;
            case SOCKET_EADDRINUSE: // если адрес используется,
            case SOCKET_ECONNREFUSED: // соединиться со слушающим сокетом не удалось
            case SOCKET_ENOENT: // если отсутствует файл сокета,
                throw new ConnectionException($errorMessage, ConnectionException::ERROR_FAIL_CONNECT);
            // break
            default: // в иных случаях кидаем исключение
                throw new ConnectionException(
                    'Unknown connection error ' . $error . ': ' . $errorMessage,
                    ConnectionException::ERROR_UNKNOWN
                );
        }
    }
}


<?php namespace ForeverPHP\Filesystem;

/**
 * Permite administrar el sistema de archivos.
 *
 * @author      Daniel Nuñez S. <dnunez@emarva.com>
 * @since       Version 0.3.0
 */
class FileNotFoundException extends \Exception {}

/*
 * Se debe poder trabajar con diferentes sistemas de archivos.
 * Como: local, google drive, amazon s3, dropbox
 */

class Filesystem {
    /**
     * Determina si un archivo existe.
     *
     * @param  string $path
     * @return bool
     */
    public function exists($path) {
        return file_exists($path);
    }

    /**
     * Obtiene el contenido del archivo.
     *
     * @param  string  $path
     * @return string
     *
     * @throws \ForeverPHP\Filesystem\FileNotFoundException
     */
    public function get($path) {
        if ($this->isFile($path)) {
            return file_get_contents($path);
        }

        throw new FileNotFoundException("File does not exist at path {$path}");
    }

    /**
     * Escribir el contenido a un archivo.
     *
     * @param  string  $path
     * @param  string  $contents
     * @param  bool    $lock
     * @return int
     */
    public function put($path, $contents, $lock = false) {
        return file_put_contents($path, $contents, $lock ? LOCK_EX : 0);
    }

    /**
     * Elimina un archivo de la ruta determinada.
     *
     * @param  string|array $paths
     * @return bool
     */
    public function delete($paths) {
        $paths = is_array($paths) ? $paths : func_get_args();

        $return = true;

        foreach ($paths as $path) {
            try {
                if (!@unlink($path)) {
                    $return = false;
                }
            } catch (ErrorException $e) {
                $return = false;
            }
        }

        return $return;
    }

    /**
     * Mueve un archivo a una nueva ubicación.
     *
     * @param  string $path
     * @param  string $target
     * @return bool
     */
    public function move($path, $target) {
        return rename($path, $target);
    }

    /**
     * Copia un archivo a una nueva ubicación.
     *
     * @param  string  $path
     * @param  string  $target
     * @return bool
     */
    public function copy($path, $target) {
        return copy($path, $target);
    }

    /**
     * Extrae el nombre del archivo de una ruta de archivo.
     *
     * @param  string  $path
     * @return string
     */
    public function name($path) {
        return pathinfo($path, PATHINFO_FILENAME);
    }

    /**
     * Extrae la extensión del archivo de una ruta de archivo.
     *
     * @param  string  $path
     * @return string
     */
    public function extension($path) {
        return pathinfo($path, PATHINFO_EXTENSION);
    }

    /**
     * Obtiene el tipo de archivo de un archivo determinado.
     *
     * @param  string  $path
     * @return string
     */
    public function type($path) {
        return filetype($path);
    }

    /**
     * Obtiene el tipo MIME de un archivo determinado.
     *
     * @param  string  $path
     * @return string|false
     */
    public function mimeType($path) {
        return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $path);
    }

    /**
     * Obtiene el tamaño del archivo dado.
     *
     * @param  string  $path
     * @return int
     */
    public function size($path) {
        return filesize($path);
    }

    /**
     * Determina si la ruta dada es un directorio.
     *
     * @param  string  $directory
     * @return bool
     */
    public function isDirectory($directory) {
        return is_dir($directory);
    }
    /**
     * Determina si la ruta dada se puede escribir.
     *
     * @param  string  $path
     * @return bool
     */
    public function isWritable($path) {
        return is_writable($path);
    }

    /**
     * Determina si la ruta dada es un archivo.
     *
     * @param  string  $file
     * @return bool
     */
    public function isFile($file) {
        return is_file($file);
    }

    /*public function prueba() {
        echo "prueba fachada.".'
';
    }

    public function prueba1($p1) {
        echo "prueba fachada.".$p1.'
';
    }

    public function prueba2($p1, $p2) {
        echo "prueba fachada.".$p1.$p2.'
';
    }

    public function prueba3($p1, $p2, $p3) {
        echo "prueba fachada.".$p1.$p2.$p3.'
';
    }

    public function prueba4($p1, $p2, $p3, $p4) {
        echo "prueba fachada.".$p1.$p2.$p3.$p4.'
';
    }

    public function pruebaMas($p1, $p2, $p3, $p4, $p5) {
        echo "prueba fachada.".$p1.$p2.$p3.$p4.$p5.'
';
    }

    public function pruebaMas2($p1, $p2, $p3, $p4, $p5, $p6, $p7) {
        echo "prueba fachada.".$p1.$p2.$p3.$p4.$p5.$p6.$p7.'
';
    }*/

    /**
     * Crea un nuevo directorio.
     *
     * @param  string  $path
     * @param  string  $permissions
     * @param  boolean $recursive
     * @return boolean
     */
    public function makeDirectory($path, $mode = 0755, $recursive = false) {
        if (!file_exists($path)) {
            return mkdir($path, $mode, $recursive);
        }

        return true;
    }
}


<?php

namespace Bridge\HttpApi\Worker;

use Bridge\HttpApi\Serializer\PathDenormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;
use Transfer\Worker\WorkerInterface;

class SerializationWorker implements WorkerInterface
{
    /**
     * @var array
     */
    private $deserialization;

    /**
     * @var array
     */
    private $source;

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

    /**
     * {@inheritdoc}
     */
    public function handle($object)
    {
        if (isset($this->deserialization['serializer'])) {
            $serializer = $this->deserialization['serializer'];
        } else {
            $serializer = $this->getDefaultSerializer();
        }

        $object = $serializer->deserialize(
            $object,
            $this->deserialization['type'],
            $this->source['format']
        );

        return $object;
    }

    private function getDefaultSerializer()
    {
        $normalizers = array();

        $normalizers[] = new GetSetMethodNormalizer();

        if (isset($this->deserialization['path'])) {
            $normalizers[] = new PathDenormalizer($this->deserialization['path']);
        }

        $normalizers[] = new ArrayDenormalizer();

        $encoders = array(new JsonEncoder());

        $serializer = new Serializer($normalizers, $encoders);

        return $serializer;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\DependencyInjection;

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

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class OpenOrchestraModelExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $immutableProperties = array_merge($config['content_immutable_properties'], array('linkedToSite', 'deleted'));
        $container->setParameter('open_orchestra_model.content.immutable_properties', $immutableProperties);

        foreach ($config['fixtures_interface'] as $command => $content) {
            $container->setParameter('open_orchestra_model.fixtures_interface.' . $command, $content);
        }
        $container->setParameter('open_orchestra_model.fixtures.command', array_keys($config['fixtures_interface']));
        foreach ($config['document'] as $class => $content) {
            if (is_array($content)) {
                $container->setParameter('open_orchestra_model.document.' . $class . '.class', $content['class']);
                if (array_key_exists('repository', $content)) {
                    $definition = new Definition($content['repository'], array($content['class']));
                    $definition->setFactory(array(new Reference('doctrine.odm.mongodb.document_manager'), 'getRepository'));
                    $definition->addMethodCall('setAggregationQueryBuilder', array(
                        new Reference('doctrine_mongodb.odm.default_aggregation_query')
                    ));
                    if (method_exists($content['repository'],'setFilterTypeManager')) {
                        $definition->addMethodCall('setFilterTypeManager', array(
                            new Reference('open_orchestra_pagination.filter_type.manager')
                        ));
                    }
                    $container->setDefinition('open_orchestra_model.repository.' . $class, $definition);
                }
            }
        }

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('listener.yml');
        $loader->load('validator.yml');
        $loader->load('manager.yml');
        $loader->load('form.yml');
        $loader->load('transformer.yml');
        $loader->load('helper.yml');
        $loader->load('health_check.yml');
    }
}


<?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\Bridge\Routing;

use RedKiteCms\Bridge\Routing\RoutingGenerator;
use RedKiteCms\Configuration\ConfigurationHandler;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\Router;

/**
 * This object instantiates a new routing for the backend environment
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Bridge\Routing
 */
class RoutingBackend extends RoutingBase
{
    /**
     * {@inheritdoc}
     */
    protected $routesFile = 'routes-backend.yml';

    /**
     * {@inheritdoc}
     */
    public function generateWebsiteRoutes(RoutingGenerator $routingGenerator, $user = null)
    {
        $routingGenerator
            ->pattern('/backend')
            ->frontController('Controller\Cms\BackendController::showAction')
            ->contributor($user)
            ->generate($this->router)
        ;
    }
}


<?php
/**
 * This file is part of the Bruery Platform.
 *
 * (c) Viktore Zara <viktore.zara@gmail.com>
 * (c) Mell Zamora <mellzamora@outlook.com>
 *
 * Copyright (c) 2016. For the full copyright and license information, please view the LICENSE  file that was distributed with this source code.
 */

namespace Bruery\AdminBundle\Controller;

use Sonata\AdminBundle\Controller\HelperController as BaseHelperController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyPath;

class HelperController extends BaseHelperController
{
    /**
     * @param Request $request
     *
     * @return Response
     */
    public function setObjectFieldValueAction(Request $request)
    {
        $field = $request->get('field');
        $code = $request->get('code');
        $objectId = $request->get('objectId');
        $value = $request->get('value');
        $context = $request->get('_context');

        $admin = $this->pool->getInstance($code);
        $admin->setRequest($request);

        // alter should be done by using a post method
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('status' => 'KO', 'message' => 'Expected a XmlHttpRequest request header'));
        }

        if ($request->getMethod() != 'POST') {
            return new JsonResponse(array('status' => 'KO', 'message' => 'Expected a POST Request'));
        }

        $rootObject = $object = $admin->getObject($objectId);

        if (!$object) {
            return new JsonResponse(array('status' => 'KO', 'message' => 'Object does not exist'));
        }

        // check user permission
        if (false === $admin->isGranted('EDIT', $object)) {
            return new JsonResponse(array('status' => 'KO', 'message' => 'Invalid permissions'));
        }

        if ($context == 'list') {
            $fieldDescription = $admin->getListFieldDescription($field);
        } else {
            return new JsonResponse(array('status' => 'KO', 'message' => 'Invalid context'));
        }

        if (!$fieldDescription) {
            return new JsonResponse(array('status' => 'KO', 'message' => 'The field does not exist'));
        }

        if (!$fieldDescription->getOption('editable')) {
            return new JsonResponse(array('status' => 'KO', 'message' => 'The field cannot be edit, editable option must be set to true'));
        }

        $propertyAccessor = PropertyAccess::createPropertyAccessor();
        $propertyPath = new PropertyPath($field);

        // If property path has more than 1 element, take the last object in order to validate it
        if ($propertyPath->getLength() > 1) {
            $object = $propertyAccessor->getValue($object, $propertyPath->getParent());

            $elements = $propertyPath->getElements();
            $field = end($elements);
            $propertyPath = new PropertyPath($field);
        }

        // Handle date type has setter expect a DateTime object
        if ('' !== $value && $fieldDescription->getType() == 'date') {
            $value = new \DateTime($value);
        }

        if ('' !== $value && $fieldDescription->getType() == 'datetime') {
            $value = new \DateTime($value);
        }

        $propertyAccessor->setValue($object, $propertyPath, '' !== $value ? $value : null);

        $violations = $this->validator->validate($object);

        if (count($violations)) {
            $messages = array();

            foreach ($violations as $violation) {
                $messages[] = $violation->getMessage();
            }

            return new JsonResponse(array('status' => 'KO', 'message' => implode("\n", $messages)));
        }

        $admin->update($object);

        // render the widget
        // todo : fix this, the twig environment variable is not set inside the extension ...
        $extension = $this->twig->getExtension('sonata_admin');
        $extension->initRuntime($this->twig);

        $content = $extension->renderListElement($this->twig, $rootObject, $fieldDescription);

        return new JsonResponse(array('status' => 'OK', 'content' => $content));
    }
}