<?php

namespace Esockets\Socket;

use Esockets\Base\AbstractAddress;
use Esockets\Base\AbstractClient;
use Esockets\Base\AbstractConnectionResource;
use Esockets\Base\BlockingInterface;
use Esockets\Base\CallbackEventListener;
use Esockets\Base\Event;
use Esockets\Base\Exception\ConnectionException;

abstract class AbstractSocketClient extends AbstractClient implements BlockingInterface
{
    use SocketTrait;

    /** Интервал времени ожидания между попытками при чтении/записи. */
    const SOCKET_WAIT = 10;

    /** Константы операций ввода/вывода. */
    const OP_READ = 0;
    const OP_WRITE = 1;

    protected $socketDomain;
    protected $socket;
    protected $connected = false;
    protected $connectionResource;
    /**
     * @var Ipv4Address|UnixAddress
     */
    protected $serverAddress;
    protected $clientAddress;

    protected $errorHandler;
    protected $eventConnect;
    protected $eventDisconnect;

    protected $receivedBytes = 0;
    protected $receivedPackets = 0;
    protected $transmittedBytes = 0;
    protected $transmittedPackets = 0;

    protected $blocked = true;

    /**
     * Приватный конструктор.
     *
     * @param int $socketDomain
     * @param SocketErrorHandler $errorHandler
     * @param AbstractConnectionResource|null $connectionResource
     *
     * @throws ConnectionException
     */
    final private function __construct(
        int $socketDomain,
        SocketErrorHandler $errorHandler,
        AbstractConnectionResource $connectionResource = null
    )
    {
        $this->socketDomain = $socketDomain;
        $this->errorHandler = $errorHandler;

        $this->eventConnect = new Event();
        $this->eventDisconnect = new Event();

        if (null === $connectionResource) {
            $this->createSocket();
        } else {
            if (get_class($this) === UdpClient::class && !$connectionResource instanceof VirtualUdpConnection) {
                throw new \InvalidArgumentException(
                    'Unknown connection: ' . get_class($connectionResource) . '; this is not supported.'
                );
            }
            $this->connectionResource = $connectionResource;
            $this->socket = $connectionResource->getResource();
            $this->connected = true;
            $this->errorHandler->setSocket($this->socket);
            if (method_exists($connectionResource, 'getPeerAddress')) {
                $this->serverAddress = $connectionResource->getPeerAddress();
            } else {
                $address = $port = null;
                if (!socket_getpeername($this->socket, $address, $port)) {
                    $this->errorHandler->handleError();
                }
                if ($this->isUnixAddress()) {
                    $this->serverAddress = new UnixAddress($address);
                } else {
                    $this->serverAddress = new Ipv4Address($address, $port);
                }
            }
        }
        if (get_class($this) === TcpClient::class) {
            socket_set_option($this->socket, SOL_SOCKET, SO_KEEPALIVE, 1);
            socket_set_option($this->socket, SOL_TCP, TCP_NODELAY, 1);
        }
    }

    /**
     * Создаёт сокет.
     *
     * @throws ConnectionException
     */
    protected function createSocket()
    {
        $this->receivedBytes = 0;
        $this->receivedPackets = 0;
        $this->transmittedBytes = 0;
        $this->transmittedPackets = 0;
        switch (get_class($this)) {
            case TcpClient::class:
                $type = SOCK_STREAM;
                $protocol = SOL_TCP;
                break;
            case UdpClient::class:
                $type = SOCK_DGRAM;
                $protocol = SOL_UDP;
                break;
            default:
                throw new \LogicException('Other protocols not supported.');
        }
        if (!($this->socket = socket_create($this->socketDomain, $type, $protocol))) {
            $this->errorHandler->handleError();
        } else {
            $this->errorHandler->setSocket($this->socket);
        }
        $this->connectionResource = new SocketConnectionResource($this->socket);
    }

    /**
     * Создаёт объект с подготовленным для подключения сокетом.
     *
     * @param int $socketDomain
     * @param SocketErrorHandler $errorHandler
     *
     * @return AbstractSocketClient
     *
     * @throws ConnectionException
     */
    public static function createEmpty(int $socketDomain, SocketErrorHandler $errorHandler): self
    {
        return new static($socketDomain, $errorHandler);
    }

    /**
     * Создает объект с подключенным сокетом.
     *
     * @param int $socketDomain
     * @param SocketErrorHandler $errorHandler
     * @param AbstractConnectionResource $connectionResource
     *
     * @return AbstractSocketClient
     *
     * @throws ConnectionException|\LogicException
     */
    public static function createConnected(
        int $socketDomain,
        SocketErrorHandler $errorHandler,
        AbstractConnectionResource $connectionResource = null
    ): self
    {
        return new static($socketDomain, $errorHandler, $connectionResource);
    }

    /**
     * @inheritdoc
     */
    public function getPeerAddress(): AbstractAddress
    {
        if (null === $this->serverAddress || !($this->serverAddress instanceof AbstractAddress)) {
            $address = $port = null;
            socket_getpeername($this->socket, $address, $port);
            if ($this->isUnixAddress() === AF_UNIX) {
                $this->serverAddress = new UnixAddress($address);
            } else {
                $this->serverAddress = new Ipv4Address($address, $port);
            }
        }
        return $this->serverAddress;
    }

    /**
     * @inheritdoc
     */
    public function getClientAddress(): AbstractAddress
    {
        if (null === $this->clientAddress || !($this->clientAddress instanceof AbstractAddress)) {
            $address = $port = null;
            socket_getsockname($this->socket, $address, $port);
            if ($this->isUnixAddress() === AF_UNIX) {
                $this->clientAddress = new UnixAddress($address);
            } else {
                $this->clientAddress = new Ipv4Address($address, $port);
            }
        }
        return $this->clientAddress;
    }

    /**
     * @inheritdoc
     */
    public function getConnectionResource(): AbstractConnectionResource
    {
        return $this->connectionResource;
    }

    /**
     * @inheritdoc
     */
    public function reconnect(): bool
    {
        $this->disconnect();
        try {
            $this->connect($this->serverAddress);
        } catch (ConnectionException $e) {
            return false;
        }

        return true;
    }

    /**
     * @inheritdoc
     */
    public function disconnect(): void
    {
        if (!$this->connected || !is_resource($this->socket) || get_resource_type($this->socket) !== 'Socket') {
            return;
        }
        $this->connected = false;
        $this->eventDisconnect->call();
        $this->block(); // блокируем сокет перед его закрытием
        socket_shutdown($this->socket);
        socket_close($this->socket);
    }

    public function ready(): bool
    {
        $read = [$this->socket];
        $write = $except = [];

        return socket_select($read, $write, $except, 0, 0);
    }

    /**
     * @inheritdoc
     */
    public function onConnect(callable $callback): CallbackEventListener
    {
        return $this->eventConnect->attachCallbackListener($callback);
    }

    /**
     * @inheritdoc
     */
    public function isConnected(): bool
    {
        return $this->connected;
    }

    /**
     * @inheritdoc
     */
    public function onDisconnect(callable $callback): CallbackEventListener
    {
        return $this->eventDisconnect->attachCallbackListener($callback);
    }

    /**
     * @inheritdoc
     */
    public function block(): void
    {
        $this->blocked = true;
        socket_set_block($this->socket);
    }

    /**
     * @inheritdoc
     */
    public function unblock(): void
    {
        $this->blocked = false;
        socket_set_nonblock($this->socket);
    }

    /**
     * @inheritdoc
     */
    public function isBlocked(): bool
    {
        return $this->blocked;
    }

    /**
     * @inheritdoc
     */
    public function getReceivedBytesCount(): int
    {
        return $this->receivedBytes;
    }

    /**
     * @inheritdoc
     */
    public function getReceivedPacketCount(): int
    {
        return $this->receivedPackets;
    }

    /**
     * @inheritdoc
     */
    public function getTransmittedBytesCount(): int
    {
        return $this->transmittedBytes;
    }

    /**
     * @inheritdoc
     */
    public function getTransmittedPacketCount(): int
    {
        return $this->transmittedPackets;
    }

    final private function __clone()
    {
        return null;
    }

    final private function __sleep()
    {
        ;
    }
}


<?php

declare(strict_types=1);

namespace PHPSess\Storage;

use PHPSess\Exception\SessionNotFoundException;
use PHPSess\Interfaces\StorageInterface;

/**
 * Uses an array to mock the session data. May be useful in tests.
 *
 * @package PHPSess\Storage
 * @author  Ayrton Fidelis <ayrton.vargas33@gmail.com>
 */
class MockStorage implements StorageInterface
{

    /**
     * @var array[] $files The array that stores all the session data.
     */
    private static $files = [];

    /**
     * @var string[] $lock The session identifiers that are locked.
     */
    public static $lockedIdentifiers = [];

    /**
     * Saves the encrypted session data to the storage.
     *
     * @param  string $sessionIdentifier The string used to identify the session data.
     * @param  string $sessionData       The encrypted session data.
     * @return void
     */
    public function save(string $sessionIdentifier, string $sessionData): void
    {
        self::$files[$sessionIdentifier] = [
            'data' => $sessionData,
            'time' => microtime(true)
        ];
    }

    /**
     * Fetches the encrypted session data based on the session identifier.
     *
     * @throws \PHPSess\Exception\SessionNotFoundException
     * @param  string $sessionIdentifier The session identifier
     * @return string The encrypted session data
     */
    public function get(string $sessionIdentifier): string
    {
        if (!$this->sessionExists($sessionIdentifier)) {
            throw new SessionNotFoundException();
        }

        return self::$files[$sessionIdentifier]['data'];
    }

    /**
     * Asks the drive to lock the session storage
     *
     * @param string $sessionIdentifier The session identifier to be locked
     * @return bool
     */
    public function lock(string $sessionIdentifier): bool
    {
        if (in_array($sessionIdentifier, self::$lockedIdentifiers)) {
            return true;
        }

        self::$lockedIdentifiers[] = $sessionIdentifier;

        return true;
    }

    /**
     * Asks the drive to unlock the session storage
     *
     * @param string $sessionIdentifier The session identifier to be unlocked
     * @return void
     */
    public function unlock(string $sessionIdentifier): void
    {
        $index = array_search($sessionIdentifier, self::$lockedIdentifiers);

        if ($index !== false) {
            unset(self::$lockedIdentifiers[$index]);
        }
    }

    /**
     * Checks if a session with the given identifier exists in the storage.
     *
     * @param  string $sessionIdentifier The session identifier.
     * @return boolean Whether the session exists or not.
     */
    public function sessionExists(string $sessionIdentifier): bool
    {
        return isset(self::$files[$sessionIdentifier]);
    }

    /**
     * Remove this session from the storage.
     *
     * @throws \PHPSess\Exception\SessionNotFoundException
     * @param  string $sessionIdentifier The session identifier.
     * @return void
     */
    public function destroy(string $sessionIdentifier): void
    {
        if (!isset(self::$files[$sessionIdentifier])) {
            throw new SessionNotFoundException();
        }

        unset(self::$files[$sessionIdentifier]);
    }

    /**
     * Removes the session older than the specified time from the storage.
     *
     * @param  int $maxLife The maximum time (in microseconds) that a session file must be kept.
     * @return void
     */
    public function clearOld(int $maxLife): void
    {
        $limit = microtime(true) - $maxLife / 1000000;

        foreach (self::$files as &$file) {
            if ($file['time'] <= $limit) {
                $file = null;
            }
        }

        self::$files = array_filter(self::$files);
    }
}


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

namespace cascade\components\types;

use cascade\components\db\behaviors\SearchTerm;
use cascade\components\db\fields\Base as BaseField;
use cascade\components\web\form\Segment as FormSegment;
use cascade\models\Relation;
use canis\caching\Cacher;
use canis\helpers\ArrayHelper;
use canis\helpers\Html;
use Yii;
use yii\helpers\Inflector;

trait ActiveRecordTrait
{
    use SearchTerm;

    public $baseFieldClass = 'cascade\components\db\fields\Base';
    public $artificialFieldClass = 'cascade\components\db\fields\Artificial';
    public $modelFieldClass = 'cascade\components\db\fields\Model';
    public $relationFieldClass = 'cascade\components\db\fields\Relation';
    public $relationTaxonomyFieldClass = 'cascade\components\db\fields\RelationTaxonomy';
    public $taxonomyFieldClass = 'cascade\components\db\fields\Taxonomy';
    public $formSegmentClass = 'cascade\components\web\form\Segment';
    public $columnSchemaClass = 'yii\\db\\ColumnSchema';

    public $foreignWeight = .7;

    public $defaultCustomColumnSchema = [
        'allowNull' => false,
        'type' => 'string',
        'phpType' => 'string',
        'dbType' => 'string',
        'isPrimaryKey' => false,
    ];

    protected $_fields;
    protected $_parentModel;
    protected $_defaultOrder;

    public function behaviors()
    {
        return [
            'Registry' => [
                'class' => 'canis\db\behaviors\Registry',
            ],
            'Relatable' => [
                'class' => 'cascade\components\db\behaviors\Relatable',
            ],
            'Taxonomy' => [
                'class' => 'cascade\components\db\behaviors\ActiveTaxonomy',
            ],
            'ActiveAccess' => [
                'class' => 'cascade\components\db\behaviors\ActiveAccess',
            ],
            'Roleable' => [
                'class' => 'cascade\components\db\behaviors\Roleable',
            ],
            'Ownable' => [
                'class' => 'cascade\components\db\behaviors\Ownable',
            ],
            'Familiarity' => [
                'class' => 'cascade\components\db\behaviors\Familiarity',
            ],
            'Auditable' => [
                'class' => 'cascade\components\db\behaviors\auditable\Auditable',
            ],
            'RelatedObjects' => [
                'class' => 'cascade\components\db\behaviors\RelatedObjects',
            ],
        ];
    }

    public function doHandleRelationAuditEvents()
    {
        if ($this->objectType->hasDashboard) {
            return false;
        }
        return true;
    }

    public static function queryBehaviors()
    {
        return array_merge(parent::queryBehaviors(),
            [
                'Taxonomy' => [
                    'class' => 'cascade\components\db\behaviors\QueryTaxonomy',
                ],
            ]
        );
    }

    public function hasIcon()
    {
        return false;
    }

    public function getIcon()
    {
        if (!$this->objectType) {
            return;
        }

        return [
            'class' => $this->objectType->icon,
        ];
    }

    public function getHumanType()
    {
        if (isset($this->objectType) && $this->objectType->title) {
            return $this->objectType->title->singular;
        }

        return;
    }

    public function formName()
    {
        $parentFormName = parent::formName();
        if (isset($this->_parentModel)) {
            $parentModelClass = get_class($this->_parentModel);

            return $this->_parentModel->formName() . $this->_parentModel->tabularPrefix . '[relatedObjects][' . $parentFormName . ']';
        }

        return $parentFormName;
    }

    public function setParentModel($parentModel)
    {
        $this->_parentModel = $parentModel;
    }

    public function isForeignField($field)
    {
        return parent::isForeignField($field) && strpos($field, ':') !== false;
    }

    public static function searchForeign($term, $field, $params = [])
    {
        $defaultParams = ['foreignWeight' => .8, 'foreignLimit' => 5, 'ignore' => []];
        $params = array_merge($defaultParams, $params);
        $modelClass = get_called_class();
        $model = new $modelClass();

        $package = [];
        $parts = explode(':', $field);
        if (count($parts) < 2) {
            return $package;
        }

        $relationshipType = $parts[0];
        if (!in_array($relationshipType, ['child', 'children', 'descendants', 'parent', 'parents', 'ancestors'])) {
            return;
        }

        $searchFields = static::searchFields();
        $companionName = $parts[1];
        $fieldName = isset($parts[2]) ? $parts[2] : 'descriptor';
        $myTypeItem = $model->objectTypeItem;
        $weightField = $parts[0] . 'SearchWeight';
        $companionTypeItem = Yii::$app->collectors['types']->getOne($companionName);
        if (!$companionTypeItem || !$myTypeItem || !($companionType = $companionTypeItem->object) || !($myType = $myTypeItem->object)) {
            return;
        }

        if ($companionType->{$weightField} && $companionType->{$weightField} !== true) {
            $searchWeight = (float) $companionType->{$weightField};
        } else {
            $searchWeight = $params['foreignWeight'];
        }
        if (in_array($relationshipType, ['child', 'children', 'descendants'])) {
            // I'm the parent
            $relationship = Relationship::has($myTypeItem, $companionTypeItem) ? Relationship::getOne($myTypeItem, $companionTypeItem) : false;
            $seek = 'queryParentObjects';
        } else {
            $relationship = Relationship::has($companionTypeItem, $myTypeItem) ? Relationship::getOne($companionTypeItem, $myTypeItem) : false;
            $seek = 'queryChildObjects';
        }
        if (!$relationship) {
            return $package;
        }
        $newParams = [];
        $newParams['skipForeign'] = true;
        $newParams['limit'] = $params['foreignLimit'];
        $newParams['action'] = isset($params['action']) ? $params['action'] : null;
        $results = $companionType->search($term, $newParams);
        foreach ($results as $result) {
            if (empty($result->object)) {
                continue;
            }
            foreach ($result->object->$seek($myType->primaryModel)->setAction($newParams['action'])->all() as $object) {
                $foreignResult = self::createSearchResult($object, $searchFields, $result->score * $searchWeight);
                if (!$foreignResult) {
                    continue;
                }
                $package[$object->primaryKey] = $foreignResult;
                $package[$object->primaryKey]->mergeTerms([$result->object->descriptor]);
                $package[$object->primaryKey]->addSubdescriptorValue($result->object->descriptor);
            }
        }

        return $package;
    }

    public function isForeignObjectInContext($object, $context = null)
    {
        if (empty($context) || !is_array($context)) {
            return false;
        }
        if (isset($context['object'])) {
            $objectTest = $context['object'];
            if (is_object($objectTest)) {
                $objectTest = $objectTest->primaryKey;
            }
            if ($objectTest === $object->primaryKey) {
                return true;
            }
        }

        return false;
    }

    public function getLocalFieldValue($field, $options = [], $context = null, $formatted = true)
    {
        if (isset($this->{$field})) {
            if ($formatted) {
                $field = $this->getField($field);
                if (!$field) {
                    return;
                }

                return $field->formattedValue;
            }

            return $this->{$field};
        }

        return;
    }

    public function getForeignField($field, $options = [], $context = null)
    {
        $origFieldName = $field;
        $relationOptions = isset($options['relationOptions']) ? $options['relationOptions'] : [];
        $objectOptions = isset($options['objectOptions']) ? $options['objectOptions'] : [];
        $parts = explode(':', $field);
        $relationshipType = $parts[0];
        if (!in_array($relationshipType, ['child', 'children', 'descendants', 'parent', 'parents', 'ancestors'])) {
            if ($field === 'parent:Account') {
                \d(['hmmm']);
                exit;
            }

            return;
        }

        $myTypeItem = $this->objectTypeItem;
        $companionName = $parts[1];
        if (!is_array($context)) {
            $context = [];
        }
        if (!isset($context['relation'])) {
            $context['relation'] = [];
        }
        $fieldName = 'descriptor';
        if (!empty($parts[2])) {
            $fieldName = $parts[2];
            $parts[2] = '';
        }
        $fields = $this->getFields();
        $fieldCheck = implode(':', $parts);

        if (in_array($fieldCheck, $context['relation']) && empty($options['relationOptions']['taxonomy'])) {
            return;
        }
        if ($companionName === '_') {
            if (in_array($parts[0], ['parent', 'parents', 'ancestors'])) {
                $loopRelations = $myTypeItem->parents;
                $loopRelations = ArrayHelper::getColumn($loopRelations, 'parent');
            } else {
                $loopRelations = $myTypeItem->children;
                $loopRelations = ArrayHelper::getColumn($loopRelations, 'child');
            }
            ArrayHelper::multisort($loopRelations, 'priority', SORT_ASC);
            foreach ($loopRelations as $relatedType) {
                $fieldName = $relationshipType . ':' . $relatedType->systemId;
                if (isset($parts[2])) {
                    $fieldName .= ':' . $parts[2];
                }
                $fieldValue = $this->getForeignField($fieldName, $options, $context);
                if (!empty($fieldValue)) {
                    return $fieldValue;
                }
            }

            return;
        }
        $companionTypeItem = Yii::$app->collectors['types']->getOne($companionName);
        if (!$companionTypeItem || !$myTypeItem || !($companionType = $companionTypeItem->object) || !($myType = $myTypeItem->object)) {
            return;
        }
        if (in_array($relationshipType, ['child', 'children', 'descendants'])) {
            // I'm the parent
            $relationship = Relationship::has($myTypeItem, $companionTypeItem) ? Relationship::getOne($myTypeItem, $companionTypeItem) : false;
        } else {
            $relationship = Relationship::has($companionTypeItem, $myTypeItem) ? Relationship::getOne($companionTypeItem, $myTypeItem) : false;
        }
        if (!$relationship) {
            return;
        }
        $cacheKey = [__FUNCTION__, $this->primaryKey, $fieldCheck, $relationshipType, $relationOptions, $objectOptions];
        $result = false; // Cacher::get($cacheKey);
        if ($result === false) {
            if (isset($fields[$fieldCheck])) {
                $field = $fields[$fieldCheck];
                if (isset($field->attributes['taxonomy_id'])) {
                    $relationOptions['taxonomy'] = $field->attributes['taxonomy_id'];
                }
                $relationOptions['where'] = !empty($field->attributes) ? $field->attributes : null;
                unset($relationOptions['where']['taxonomy_id']);
                if (empty($relationOptions['where'])) {
                    unset($relationOptions['where']);
                }
            }
            $cacheDependencies = [];
            $cacheDependencies[] = $this->getRelationCacheDependency($this->primaryKey);
            $result = $this->{$relationshipType}($companionType->primaryModel, $relationOptions, $objectOptions);
            if (empty($result)) {
                $result = null;
            } else {
                $cacheDependencies[] = $result->getObjectCacheDependency();
            }
            Cacher::set($cacheKey, $result, 0, Cacher::chainedDependency($cacheDependencies));
        }
        if (empty($result)) {
            return;
        }
        if (is_array($result)) {
            $fields = [];
            foreach ($result as $object) {
                if ($this->isForeignObjectInContext($object, $context)) {
                    continue;
                }
                $field = $object->getField($fieldName);
                if (empty($field)) {
                    continue;
                }
                $companionType->loadFieldLink($field, $object);
                $fields[] = $field;
            }
            if (empty($fields)) {
                return;
            }

            return $fields;
        } else {
            if ($this->isForeignObjectInContext($result, $context)) {
                return;
            }
            $field = $result->getField($fieldName);
            if (empty($field)) {
                return;
            }
            $companionType->loadFieldLink($field, $result);

            return $field;
        }

        return;
    }

    public function getObjectCacheDependency()
    {
        return Cacher::groupDependency(['Object', $this->primaryKey], 'object');
    }

    public function getForeignFieldValue($fieldName, $options = [], $context = null, $formatted = true)
    {
        $field = $this->getForeignField($fieldName, $options, $context);
        if (!empty($field)) {
            if (is_array($field)) {
                $rich = [];
                $plain = [];
                foreach ($field as $object) {
                    $valuePackage = $object->valuePackage;
                    if (!empty($valuePackage) && !empty($valuePackage['rich']) && !empty($valuePackage['plain'])) {
                        $rich[] = $valuePackage['rich'];
                        $plain[] = $valuePackage['plain'];
                    }
                }

                return ['rich' => implode(', ', $rich), 'plain' => implode(', ', $plain)];
            } else {
                return $field->valuePackage;
            }
        }

        return;
    }

    public static function searchFields()
    {
        $modelClass = get_called_class();
        $model = new $modelClass();

        $fields = [];
        if (!is_null($model->descriptorField)) {
            if (is_array($model->descriptorField)) {
                $fields[] = $model->descriptorField;
            } else {
                $fields[] = [$model->descriptorField];
            }
        }
        $attributes = $model->attributes();
        foreach ($fields as $key => $fieldList) {
            if (!is_array($fieldList)) {
                \d($fields);
                exit;
            }
            foreach ($fieldList as $fieldKey => $field) {
                if (!in_array($field, $attributes)) {
                    unset($fields[$key][$fieldKey]);
                }
                if (empty($fields[$key])) {
                    unset($fields[$key]);
                }
            }
        }
        // $fields = array_intersect($fields, );
        if (($moduleItem = $model->getObjectTypeItem())) {
            foreach ($moduleItem->children as $key => $relationship) {
                if ($relationship->child->childSearchWeight) {
                    $fields[] = 'child:' . $key;
                }
            }
            foreach ($moduleItem->parents as $key => $relationship) {
                if ($relationship->parent->parentSearchWeight) {
                    $fields[] = 'parent:' . $key;
                }
            }
        }

        return $fields;
    }

    public static function prepareObjectTerms($object, $fields)
    {
        $terms = [];
        foreach ($fields as $fieldList) {
            if (!is_array($fieldList)) {
                $fieldList = [$fieldList];
            }
            foreach ($fieldList as $field) {
                if (strpos(':', $field) === false) {
                    continue;
                }
                if (!empty($object->{$field})) {
                    $terms[] = $object->{$field};
                }
            }
        }

        return $terms;
    }

    public static function parseSearchFields($fields)
    {
        $result = ['local' => [], 'foreign' => []];
        foreach ($fields as $fieldKey => $fieldList) {
            if (!is_array($fieldList)) {
                $fieldList = [$fieldList];
            }
            foreach ($fieldList as $field) {
                if (strpos($field, ':') === false) {
                    $destination = 'local';
                } else {
                    $destination = 'foreign';
                }
                if (!isset($result[$destination][$fieldKey])) {
                    $result[$destination][$fieldKey] = [];
                }
                $result[$destination][$fieldKey][] = $field;
            }
        }
        $result['local'] = array_values($result['local']);
        $result['foreign'] = array_values($result['foreign']);

        return $result;
    }

    public function isEmptyObject()
    {
        $default = $this->defaultValues;
        foreach ($this->attributes as $key => $value) {
            if ($this->isAttributeChanged($key)
                && !empty($value)
                && (!isset($default[$key]) || $value == $default[$key])
            ) {
                return false;
            }
        }

        return true;
    }

    public function getDefaultValues()
    {
        return [];
    }

    public function loadDefaultValues($skipIfSet = true)
    {
        $fields = $this->getFields();
        $defaultValues = $this->getDefaultValues();
        foreach ($defaultValues as $k => $v) {
            if ($this->isForeignField($k)) {
                if (isset($fields[$k])) {
                    $fieldParts = explode(':', $k);
                    if (in_array($fieldParts[0], ['child', 'children', 'descendants'])) {
                        $fields[$k]->model->child_object_id = $v;
                    } else {
                        $fields[$k]->model->parent_object_id = $v;
                    }
                }
            } else {
                if ($v !== null && (!$skipIfSet || $this->{$k} === null)) {
                    $this->{$k} = $v;
                }
            }
        }
        parent::loadDefaultValues($skipIfSet);
    }

    public function getPackage($urlAction = 'view')
    {
        $p = parent::getPackage($urlAction);
        $p['type'] = $this->objectTypeItem->systemId;
        if ($this->hasIcon()) {
            $p['icon'] = $this->getIcon();
        }

        return $p;
    }

    public function getUrl($action = 'view', $base = [], $pathLink = true)
    {
        $url = ['/object/' . $action, 'id' => $this->primaryKey];
        $url = array_merge($url, $base);
        if ($action === 'view'
                && $pathLink === true
                && isset(Yii::$app->request->object)
                && Yii::$app->request->object->primaryKey !== $this->primaryKey) {
            $url['p'] = Yii::$app->request->object->primaryKey;
        }

        return $url;
    }

    public function getViewLink()
    {
        if ($this->can('read')) {
            return Html::a($this->descriptor, $this->getUrl('view'));
        } else {
            return $this->descriptor;
        }
    }

    public function allowRogue(Relation $relation = null)
    {
        $relationship = false;
        if (is_null($relation)) {
            $relation = false;
        } else {
            $relationship = $relation->relationship;
        }

        if ($relationship && $relationship->isHasOne()) {
            return false;
        }
        if ($relation && isset($relation->childObject) && isset($relation->childObject->objectType) && $relation->childObject->objectType->uniparental) {
            return false;
        }
        if ($this->objectType->hasDashboard) {
            return true;
        }
        if ($this->getBehavior('Relatable') !== null && count($this->parentIds) > 1) {
            return true;
        }

        return false;
    }

    /**
     * @param unknown $name
     * @param unknown $settings (optional)
     *
     * @return unknown
     */
    public function form($settings = [])
    {
        Yii::beginProfile(__CLASS__ . ':' . __FUNCTION__);
        $settings['class'] = $this->formSegmentClass;
        $settings['model'] = $this;
        if (!isset($settings['settings'])) {
            $settings['settings'] = [];
        }
        $form = Yii::createObject($settings);
        // $form = new FormSegment($this, $name, $settings);
        Yii::endProfile(__CLASS__ . ':' . __FUNCTION__);

        return $form;
    }

    /**
     * @return unknown
     */
    public function additionalFields()
    {
        return [
            '_moduleHandler' => [],
        ];
    }

    /**
     * @return unknown
     */
    public function getAdditionalAttributes()
    {
        $add = [];
        $af = $this->additionalFields();
        foreach (array_keys($af) as $field) {
            if (isset($this->{$field})) {
                $add[$field] = $this->{$field};
            }
        }

        return $add;
    }

    public function getRequiredFields($owner = null)
    {
        $fields = $this->getFields($owner);
        $required = [];
        foreach ($fields as $key => $field) {
            if (!$field->human) {
                continue;
            }
            if ($field->required) {
                $required[$key] = $field;
            }
        }

        return $required;
    }

    public function getHeaderDetails()
    {
        return [];
    }

    public function getFieldLocation($location, $owner = null, $allFields = null)
    {
        if (is_null($allFields)) {
            $allFields = $this->getFields($owner);
        }
        $fields = [];
        foreach ($allFields as $key => $field) {
            if (in_array($location, $field->locations)) {
                $fields[] = $field;
            }
        }

        return $fields;
    }

    public function getDetailFields($owner = null, $fields = null)
    {
        return $this->getFieldLocation(BaseField::LOCATION_DETAILS, $owner, $fields);
    }

    public function getHiddenFields($owner = null, $fields = null)
    {
        return $this->getFieldLocation(BaseField::LOCATION_HIDDEN, $owner, $fields);
    }

    public function getHeaderFields($owner = null, $fields = null)
    {
        return $this->getFieldLocation(BaseField::LOCATION_HEADER, $owner, $fields);
    }

    public function getSubheaderFields($owner = null, $fields = null)
    {
        return $this->getFieldLocation(BaseField::LOCATION_SUBHEADER, $owner, $fields);
    }

    public function createColumnSchema($name, $settings = [])
    {
        $settings = array_merge($this->defaultCustomColumnSchema, $settings);
        $settings['name'] = $name;
        $settings['class'] = $this->columnSchemaClass;

        return Yii::createObject($settings);
    }

    public function getValidators()
    {
        $validators = parent::getValidators();

        if (is_object($this->objectType) && ($disabledFields = $this->objectType->disabledFields) && !empty($disabledFields)) {
            foreach ($validators as $validator) {
                $validator->attributes = array_diff($validator->attributes, $disabledFields);
            }
        }

        return $validators;
    }

    public function getField($field, $owner = null)
    {
        $fields = $this->fields;
        if (isset($fields[$field])) {
            return $fields[$field];
        } else {
            $functionName = 'get' . Inflector::camelize($field) . 'Field';
            if (method_exists($this, $functionName)) {
                return $this->$functionName();
            } elseif (isset($this->{$field})) {
                // create artificial field
                return $this->createArtificialField($field, $this->{$field}, $owner);
            }
        }

        return;
    }

    public function getRelationTaxonomies()
    {
        if (isset($this->relationModel) && isset($this->relationModel['id'])) {
            $parts = [];
            $relationClass = Yii::$app->classes['Relation'];
            $taxonomyClass = Yii::$app->classes['Taxonomy'];
            $relationModel = $relationClass::getRegisterModel($this->relationModel);
            //\d($relationModel->taxonomy_id);
            foreach ($relationModel->taxonomy_id as $taxonomy) {
                $taxonomyModel = $taxonomyClass::get($taxonomy, false);
                if ($taxonomyModel) {
                    $parts[] = $taxonomyModel->descriptor;
                }
            }
            if (empty($parts)) {
                return;
            }

            return implode(', ', $parts);
        }

        return;
    }

    public function getFilterFields()
    {
        $filters = [];
        foreach ($this->getFields() as $id => $field) {
            $filter = $field->filterSettings;
            if (!$filter) {
                continue;
            }
            $filter['id'] = $id;
            $filters[] = $filter;
        }

        return $filters;
    }

    /**
     * @param unknown $model                 (optional)
     * @param unknown $univeralFieldSettings (optional)
     *
     * @return unknown
     */
    public function getFields($owner = null)
    {
        if (!isset($this->_fields)) {
            $disabledFields = $this->objectType->disabledFields;
            $modelName = self::className();
            $this->_fields = [];
            $fieldSettings = $this->fieldSettings();
            $aliases = [];
            foreach (self::getTableSchema()->columns as  $name => $column) {
                if (in_array($name, $disabledFields)) {
                    continue;
                }
                $settings = [];
                if (isset($fieldSettings[$name])) {
                    $settings = array_merge_recursive($settings, $fieldSettings[$name]);
                }
                if (isset($settings['alias'])) {
                    $aliases[$name] = $settings['alias'];
                    unset($settings['alias']);
                }
                if (is_array($column)) {
                    $column = $this->createColumnSchema($name, $column);
                }
                $this->_fields[$name] = $this->createField($column, $owner, $settings);
            }

            $objectTypeItem = $this->objectTypeItem;
            if ($objectTypeItem) {
                $relationRelationship = null;
                $relationClass = Yii::$app->classes['Relation'];
                $taxonomies = $objectTypeItem->taxonomies;
                foreach ($objectTypeItem->parents as $relationship) {
                    $fieldName = 'parent:' . $relationship->parent->systemId;
                    if (in_array($fieldName, $disabledFields)) {
                        continue;
                    }
                    $fieldSchema = $this->createColumnSchema($fieldName, ['type' => 'relation', 'phpType' => 'object', 'dbType' => 'relation', 'allowNull' => true]);
                    $settings = [];
                    if (isset($fieldSettings[$fieldName])) {
                        $settings = array_merge_recursive($settings, $fieldSettings[$fieldName]);
                    }
                    if (isset($settings['alias'])) {
                        $aliases[$fieldName] = $settings['alias'];
                        unset($settings['alias']);
                    }
                    $settings['modelRole'] = 'child';
                    $settings['relationship'] = $relationship;
                    $this->_fields[$fieldName] = $this->createRelationField($fieldSchema, $owner, $settings);
                }

                foreach ($objectTypeItem->children as $relationship) {
                    $fieldName = 'child:' . $relationship->child->systemId;
                    if (in_array($fieldName, $disabledFields)) {
                        continue;
                    }
                    $fieldSchema = $this->createColumnSchema($fieldName, ['type' => 'relation', 'phpType' => 'object', 'dbType' => 'relation', 'allowNull' => true]);
                    $settings = [];
                    if (isset($fieldSettings[$fieldName])) {
                        $settings = array_merge_recursive($settings, $fieldSettings[$fieldName]);
                    }
                    if (isset($settings['alias'])) {
                        $aliases[$fieldName] = $settings['alias'];
                        unset($settings['alias']);
                    }
                    $settings['modelRole'] = 'parent';
                    $settings['relationship'] = $relationship;
                    $this->_fields[$fieldName] = $this->createRelationField($fieldSchema, $owner, $settings);
                }

                foreach ($taxonomies as $taxonomy) {
                    if (!in_array(self::className(), $taxonomy->models)) {
                        continue;
                    }

                    $fieldName = 'taxonomy:' . $taxonomy->systemId;
                    if (in_array($fieldName, $disabledFields)) {
                        continue;
                    }
                    $fieldSchema = $this->createColumnSchema($fieldName, ['type' => 'taxonomy', 'phpType' => 'object', 'dbType' => 'taxonomy', 'allowNull' => true]);

                    $settings = [];
                    if (isset($fieldSettings[$fieldName])) {
                        $settings = array_merge_recursive($settings, $fieldSettings[$fieldName]);
                    }
                    if (isset($settings['alias'])) {
                        $aliases[$fieldName] = $settings['alias'];
                        unset($settings['alias']);
                    }
                    $settings['model'] = $this;
                    $this->_fields[$fieldName] = $this->createTaxonomyField($fieldSchema, $taxonomy, $owner);
                }
            }

            foreach ($this->additionalFields() as $name => $column) {
                if (in_array($name, $disabledFields)) {
                    continue;
                }
                $settings = [];
                if (isset($fieldSettings[$name])) {
                    $settings = array_merge_recursive($settings, $fieldSettings[$name]);
                }
                if (isset($settings['alias'])) {
                    $aliases[$name] = $settings['alias'];
                    unset($settings['alias']);
                }
                if (is_string($column) && isset($this->_fields[$column])) {
                    $this->_fields[$name] = $this->duplicateField($name, $this->_fields[$column], $owner, $settings);
                } elseif (is_array($column)) {
                    $column = $this->createColumnSchema($name, $column);
                    $this->_fields[$name] = $this->createField($column, $owner, $settings);
                } else {
                    $this->_fields[$name] = $this->createField($column, $owner, $settings);
                }
            }
            foreach ($aliases as $from => $to) {
                if (isset($this->_fields[$to])) {
                    $this->_fields[$from] = $this->_fields[$to];
                }
            }
            $currentKeys = array_keys($this->_fields);
            foreach ($this->_fields as $name => $field) {
                if (!isset($field->priority)) {
                    $field->priority = (int) array_search($name, $currentKeys);
                    $field->priority = ($field->priority * 100);
                }
            }
            $this->_fields['relationTaxonomies'] = $this->createRelationTaxonomyField($owner, []);
            ArrayHelper::multisort($this->_fields, 'priority', SORT_ASC);
        }
        if (!empty($owner)) {
            foreach ($this->_fields as $field) {
                if (!$field->formField) {
                    continue;
                }
                $field->formField->owner = $owner;
            }
        }

        return $this->_fields;
    }

    public function duplicateField($name, $originalField, $owner, $settings = [])
    {
        $newField = clone $originalField;
        $newField->fieldSchema->name = $name;
        $newField->formField->owner = $owner;
        if ($newField->hasModel()) {
            $newField->model->tabularId = $name;
        }
        $newField->label = $this->getAttributeLabel($name);
        Yii::configure($newField, $settings);

        return $newField;
    }

    public function createField($fieldSchema, $owner, $settings = [])
    {
        $settings['class'] = $this->modelFieldClass;
        if (!isset($settings['model'])) {
            $settings['model'] = $this;
        }
        if (!is_object($fieldSchema)) {
            $fieldSchema = $this->createColumnSchema($fieldSchema);
        }
        $settings['fieldSchema'] = $fieldSchema;
        $settings['required'] = $this->isAttributeRequired($fieldSchema->name);

        if (!isset($settings['formField'])) {
            $settings['formField'] = [];
        }
        $settings['formField']['owner'] = $owner;

        return Yii::createObject($settings);
    }

    public function createArtificialField($fieldName, $fieldValue, $owner, $settings = [])
    {
        $settings['class'] = $this->artificialFieldClass;
        if (!isset($settings['model'])) {
            $settings['model'] = $this;
        }
        $settings['fieldName'] = $fieldName;
        $settings['fieldValue'] = $fieldValue;
        $settings['required'] = false;
        $settings['formField'] = false;

        return Yii::createObject($settings);
    }

    public function createRelationTaxonomyField($owner, $settings = [])
    {
        $settings['class'] = $this->relationTaxonomyFieldClass;
        if (!isset($settings['model'])) {
            $settings['model'] = $this;
        }
        $settings['fieldName'] = 'relationTaxonomies';
        $settings['required'] = false;
        $settings['formField'] = false;

        return Yii::createObject($settings);
    }

    public function createRelationField($fieldSchema, $owner, $settings = [])
    {
        $settings['class'] = $this->relationFieldClass;
        if (!isset($settings['baseModel'])) {
            $settings['baseModel'] = $this;
        }
        $settings['fieldSchema'] = $fieldSchema;
        $settings['required'] = $this->isAttributeRequired($fieldSchema->name);
        //$settings['baseModel'] = $this;

        if (!isset($settings['formField'])) {
            $settings['formField'] = [];
        }
        $settings['formField']['owner'] = $owner;

        return Yii::createObject($settings);
    }

    public function createTaxonomyField($fieldSchema, $taxonomy, $owner, $settings = [])
    {
        $settings['class'] = $this->taxonomyFieldClass;
        $settings['fieldSchema'] = $fieldSchema;
        if (!isset($settings['formField'])) {
            $settings['formField'] = [];
        }
        $settings['formField']['owner'] = $owner;
        $settings['taxonomy'] = $taxonomy;
        $settings['required'] = $taxonomy->required;

        return Yii::createObject($settings);
    }

    public function getObjectType()
    {
        $objectTypeItem = $this->objectTypeItem;
        if ($objectTypeItem) {
            return $objectTypeItem->object;
        }

        return false;
    }

    public function getObjectTypeItem()
    {
        if (isset(Yii::$app->collectors['types']) && Yii::$app->collectors['types']->has(get_class($this), 'object.primaryModel')) {
            return Yii::$app->collectors['types']->getOne(get_class($this), 'object.primaryModel');
        }

        return false;
    }
    /**
     * @return unknown
     */
    public function fieldSettings()
    {
        return;
    }

    public function formSettings($name, $settings = [])
    {
        if (!is_array($settings)) {
            $settings = [];
        }

        return $settings;
    }

    /**
     * @param unknown $key (optional)
     *
     * @return unknown
     */
    public function setFormValues($key = null)
    {
        if (!isset($_POST[get_class($this)])) {
            return true;
        }
        $base = $_POST[get_class($this)];
        if (is_null($key) or $key === 'primary') {
            if (!empty($base)) {
                $this->attributes = $base;
            }
        } else {
            $key = md5($key);
            if (!empty($base[$key])) {
                $this->attributes = $base[$key];
            }
        }

        return $this->validate();
    }
}


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

namespace cascade\components\dataInterface;

/**
 * FieldMap [[@doctodo class_description:cascade\components\dataInterface\FieldMap]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class FieldMap extends \canis\base\Object
{
    /**
     * @var [[@doctodo var_type:dataSource]] [[@doctodo var_description:dataSource]]
     */
    public $dataSource;

    /**
     * @var [[@doctodo var_type:localField]] [[@doctodo var_description:localField]]
     */
    public $localField = false;
    /**
     * @var [[@doctodo var_type:foreignField]] [[@doctodo var_description:foreignField]]
     */
    public $foreignField = false;
    /**
     * @var [[@doctodo var_type:foreignModel]] [[@doctodo var_description:foreignModel]]
     */
    public $foreignModel = false;
    /**
     * @var [[@doctodo var_type:searchFields]] [[@doctodo var_description:searchFields]]
     */
    public $searchFields;
    /**
     * @var [[@doctodo var_type:value]] [[@doctodo var_description:value]]
     */
    public $value;
    /**
     * @var [[@doctodo var_type:filter]] [[@doctodo var_description:filter]]
     */
    public $filter;
    /**
     * @var [[@doctodo var_type:taxonomy]] [[@doctodo var_description:taxonomy]]
     */
    public $taxonomy;

    /**
     * @var [[@doctodo var_type:mute]] [[@doctodo var_description:mute]]
     */
    public $mute = [];

    /**
     * @var [[@doctodo var_type:ignore]] [[@doctodo var_description:ignore]]
     */
    public $ignore = [];

    /**
     * [[@doctodo method_description:testIgnore]].
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     *
     * @return [[@doctodo return_type:testIgnore]] [[@doctodo return_description:testIgnore]]
     */
    public function testIgnore($value)
    {
        if (is_array($value)) {
            $model = $value;
            foreach ($this->ignore as $field => $test) {
                $settings = [];
                if (is_numeric($field)) {
                    $settings = $test;
                    $field = isset($settings['field']);
                    $test = $settings['test'];
                }
                $value = null;
                if (isset($model[$field])) {
                    $value = $model[$field];
                }
                if (is_string($test)) {
                    $subvalue = null;
                    if (isset($model[$test])) {
                        $subvalue = $model[$test];
                    }
                    if ($value === $subvalue) {
                        return true;
                    }
                } elseif ($test instanceof Match && $test->test($value)) {
                    return true;
                }
            }
        } else {
            foreach ($this->ignore as $test) {
                if ($test instanceof Match && $test->test($value)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * [[@doctodo method_description:extractValue]].
     *
     * @param [[@doctodo param_type:caller]]       $caller       [[@doctodo param_description:caller]]
     * @param [[@doctodo param_type:foreignModel]] $foreignModel [[@doctodo param_description:foreignModel]] [optional]
     * @param [[@doctodo param_type:localModel]]   $localModel   [[@doctodo param_description:localModel]] [optional]
     *
     * @return [[@doctodo return_type:extractValue]] [[@doctodo return_description:extractValue]]
     */
    public function extractValue($caller, $foreignModel = null, $localModel = null)
    {
        if (is_null($foreignModel)) {
            $foreignModel = $this->foreignModel;
        }
        $foreignField = $this->foreignField;

        $value = null;
        if (isset($this->value)) {
            if (is_callable($this->value)) {
                $value = call_user_func($this->value, $foreignModel, $this);
            } else {
                $value = $this->value;
            }
        } elseif (isset($foreignField)) {
            if (is_callable($foreignField)) {
                $value = call_user_func($foreignField, $foreignModel);
            } elseif (!is_object($foreignField) && is_array($foreignField)) {
                $value = $caller->buildLocalAttributes($foreignModel, $localModel, $caller->buildMap($foreignField));
            } elseif (is_string($foreignField)) {
                $value = (isset($foreignModel->{$foreignField}) ? $foreignModel->{$foreignField} : null);
            }
        }

        if (is_object($value) && $value instanceof DataItem) {
            $object = $value->handle();
            if ($object) {
                $value = $object->primaryKey;
            } else {
                $value = null;
            }
        }
        if (!is_array($value)) {
            if (isset($this->filter)) {
                $value = call_user_func($this->filter, $value);
            }

            $value = $this->dataSource->universalFilter($value);
        }

        return $value;
    }
}


<?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 Controller\Page;

use RedKiteCms\Rendering\Controller\Page\HidePageController as BaseHidePageController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * This object implements the Silex controller to hide a published page from production
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Seo
 */
class HidePageController extends BaseHidePageController
{
    /**
     * Hide page action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function hideAction(Request $request, Application $app)
    {
        $options = array(
            "request" => $request,
            "page_manager" => $app["red_kite_cms.page_manager"],
            "username" => $this->fetchUsername($app["security"], $app["red_kite_cms.configuration_handler"]),
        );

        return parent::hide($options);
    }
}


<?php
namespace Poirot\Queue\Payload;

use Poirot\Queue\Interfaces\iPayloadQueued;

class FailedPayload
    extends QueuedPayload
{
    /** @var iPayloadQueued */
    protected $qPayloadWrapper;

    protected $countRetries = 0;

    /**
     * BasePayload constructor.
     *
     * @param mixed $payload
     * @param int   $countTries
     */
    function __construct(iPayloadQueued $payload, $countTries = null)
    {
        $this->qPayloadWrapper = $payload;

        if (null !== $countTries)
            $this->setCountRetries($countTries);
    }

    // Wrapper

    /**
     * Get Storage UID for This Payload
     *
     * @return mixed
     */
    function getUID()
    {
        return $this->qPayloadWrapper->getUID();
    }

    /**
     * Get Payload Content
     *
     * @return mixed Serializable content
     */
    function getData()
    {
        return $this->qPayloadWrapper->getData();
    }

    /**
     * With Given Payload
     *
     * @param mixed $data Serializable payload
     *
     * @return $this
     */
    function withData($data)
    {
        $n = clone $this;
        $qPayload = clone $this->qPayloadWrapper;
        $qPayload = $qPayload->withData($data);
        $n->qPayloadWrapper = $qPayload;
        return $n;
    }

    /**
     * Get Queue Name
     *
     * @return string Queue name
     */
    function getQueue()
    {
        return $this->qPayloadWrapper->getQueue();
    }

    /**
     * Queue Name
     *
     * @param string $queue
     *
     * @return $this
     */
    function withQueue($queue)
    {
        $n = clone $this;
        $qPayload = clone $this->qPayloadWrapper;
        $qPayload = $qPayload->withQueue($queue);
        $n->qPayloadWrapper = $qPayload;
        return $n;
    }

    /**
     * With UID
     *
     * @param mixed $uid
     *
     * @return $this
     */
    function withUID($uid)
    {
        $n = clone $this;
        $qPayload = clone $this->qPayloadWrapper;
        $qPayload = $qPayload->withUID($uid);
        $n->qPayloadWrapper = $qPayload;
        return $n;
    }

    /**
     * Get Created Timestamp
     *
     * @return int Timestamp
     */
    function getCreatedTimestamp()
    {
        return $this->qPayloadWrapper->getCreatedTimestamp();
    }

    // Implement Failed Payload

    function getCountRetries()
    {
        return $this->countRetries;
    }

    function incCountRetries()
    {
        $this->countRetries++;
        return $this;
    }

    function setCountRetries($countRetries)
    {
        $this->countRetries = (int) $countRetries;
        return $this;
    }

    // Implement Serializable:

    /**
     * @inheritdoc
     */
    function serialize()
    {
        $s = [
            'wrp' => serialize($this->qPayloadWrapper),
            'try' => $this->getCountRetries(),
        ];

        return serialize($s);
    }

    /**
     * @inheritdoc
     */
    function unserialize($serialized)
    {
        $us = unserialize($serialized);
        $this->qPayloadWrapper = unserialize($us['wrp']);
        $this->countRetries    = $us['try'];
    }
}


<?php

/*
 * Chill is a software for social workers
 *
 * Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
 * <http://www.champs-libres.coop>, <info@champs-libres.coop>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace Chill\CustomFieldsBundle\CustomFields;

use Chill\CustomFieldsBundle\CustomFields\CustomFieldInterface;
use Chill\CustomFieldsBundle\Entity\CustomField;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Chill\MainBundle\Templating\TranslatableStringHelper;

/**
 * @author Julien Fastré <julien.fastre@champs-libres.coop>
 * @author Marc Ducobu <marc@champs-libres.coop>
 */
class CustomFieldText extends AbstractCustomField
{

    private $requestStack;

    /**
     *
     * @var TwigEngine
     */
    private $templating;

    /**
     * @var TranslatableStringHelper Helper that find the string in current locale from an array of translation
     */
    private $translatableStringHelper;

    public function __construct(RequestStack $requestStack, TwigEngine $templating,
        TranslatableStringHelper $translatableStringHelper)
    {
        $this->requestStack = $requestStack;
        $this->templating = $templating;
        $this->translatableStringHelper = $translatableStringHelper;
    }

    const MAX_LENGTH = 'maxLength';
    const MULTIPLE_CF_INLINE ='multipleCFInline';

    /**
     * Create a form according to the maxLength option
     *
     * if maxLength < 256 THEN the form type is 'text'
     * if not, THEN the form type is textarea
     *
     * @param FormBuilderInterface $builder
     * @param CustomField $customField
     */
    public function buildForm(FormBuilderInterface $builder, CustomField $customField)
    {
        $options =  $customField->getOptions();

        $type = ($options[self::MAX_LENGTH] < 256) ? 'text'
              : 'textarea';

        $attrArray = array();

        if(array_key_exists(self::MULTIPLE_CF_INLINE, $options) and
            $options[self::MULTIPLE_CF_INLINE]) {
            $attrArray['class'] = 'multiple-cf-inline';
        }

        $builder->add($customField->getSlug(), $type, array(
            'label' => $this->translatableStringHelper->localize($customField->getName()),
            'required' => false,
            'attr' => $attrArray
        ));
    }

    public function render($value, CustomField $customField,  $documentType = 'html')
    {
        $template = 'ChillCustomFieldsBundle:CustomFieldsRendering:text.html.twig';
        if($documentType == 'csv') {
            $template = 'ChillCustomFieldsBundle:CustomFieldsRendering:text.csv.twig';
        }

        return $this->templating
            ->render($template, array('text' => $value));
    }

    public function serialize($value, CustomField $customField)
    {
        return $value;
    }

    public function deserialize($serialized, CustomField $customField)
    {
        return $serialized;
    }

    public function getName()
    {
        return 'text field';
    }

    public function buildOptionsForm(FormBuilderInterface $builder)
    {
        return $builder
            ->add(self::MAX_LENGTH, 'integer', array('empty_data' => 256))
            ->add(self::MULTIPLE_CF_INLINE, 'choice',  array(
                'choices'  => array(
                   '1' => 'Multiple boxes on the line',
                   '0' => 'One box on the line'
                   ),
                'label' => 'Box appearance',
                'expanded' => True
               ))
        ;
    }
}


<?php

/*
 * This file is part of the Сáша framework.
 *
 * (c) tchiotludo <http://github.com/tchiotludo>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types = 1);

namespace Cawa\Renderer;

use Cawa\Controller\ViewController;

class Element extends ViewController
{
    /**
     * HtmlElement constructor.
     *
     * @param string $content
     */
    public function __construct(string $content = null)
    {
        $this->content = $content;
    }

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

    /**
     * @return string|null
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * @param string $content
     *
     * @return $this|self
     */
    public function setContent($content) : self
    {
        $this->content = $content;

        return $this;
    }

    /**
     * @param string $content
     *
     * @return $this|self
     */
    public function prependContent(string $content) : self
    {
        $this->content = $content . $this->content;

        return $this;
    }

    /**
     * @param string $content
     *
     * @return $this|self
     */
    public function appendContent(string $content) : self
    {
        $this->content = $this->content . $content;

        return $this;
    }

    /**
     * @var bool
     */
    private $renderable = true;

    /**
     * @return bool
     */
    public function isRenderable() : bool
    {
        return $this->renderable;
    }

    /**
     * @param bool $renderable
     *
     * @return $this|self
     */
    public function setRenderable(bool $renderable) : self
    {
        $this->renderable = $renderable;

        return $this;
    }

    /**
     * @return string
     */
    public function render()
    {
        return $this->renderable ? $this->content : '';
    }
}


<?php

namespace Dhii\Data\Container;

use Dhii\Util\String\StringableInterface as Stringable;
use Exception as RootException;
use InvalidArgumentException;

/**
 * Functionality for storage and retrieval of a data key.
 *
 * @since [*next-version*]
 */
trait DataKeyAwareTrait
{
    /**
     * The data key, if any.
     *
     * @since [*next-version*]
     *
     * @var string|Stringable|null
     */
    protected $dataKey;

    /**
     * Assigns a data key to this instance.
     *
     * @since [*next-version*]
     *
     * @param string|Stringable|null $key The key.
     *
     * @throws InvalidArgumentException If the key is invalid.
     */
    protected function _setDataKey($key)
    {
        if (!is_null($key) && !is_string($key) && !($key instanceof Stringable)) {
            throw $this->_createInvalidArgumentException($this->__('Data key must be a string or stringable'), 0, null, $key);
        }

        $this->dataKey = $key;

        return $this;
    }

    /**
     * Retrieves the data key associated with this instance.
     *
     * @since [*next-version*]
     *
     * @return string|Stringable|null The key, if any.
     */
    protected function _getDataKey()
    {
        return $this->dataKey;
    }

    /**
     * Creates a new Invalid Argument exception.
     *
     * @since [*next-version*]
     *
     * @param string        $message  The error message.
     * @param int           $code     The error code.
     * @param RootException $previous The inner exception for chaining, if any.
     * @param mixed         $argument The invalid argument, if any.
     *
     * @return InvalidArgumentException The new exception.
     */
    abstract protected function _createInvalidArgumentException(
            $message = '',
            $code = 0,
            RootException $previous = null,
            $argument = null
    );

    /**
     * Translates a string, and replaces placeholders.
     *
     * @since [*next-version*]
     * @see sprintf()
     *
     * @param string $string  The format string to translate.
     * @param array  $args    Placeholder values to replace in the string.
     * @param mixed  $context The context for translation.
     *
     * @return string The translated string.
     */
    abstract protected function __($string, $args = [], $context = null);
}


<?php

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

/**
 * AuthorizerAccessToken.php.
 *
 * Part of Overtrue\WeChat.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author    lixiao <leonlx126@gmail.com>
 * @copyright 2016
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\OpenPlatform;

// Don't change the alias name please. I met the issue "name already in use"
// when used in Laravel project, not sure what is causing it, this is quick
// solution.
use EasyWeChat\Core\AccessToken as BaseAccessToken;

/**
 * Class AuthorizerAccessToken.
 *
 * AuthorizerAccessToken is responsible for the access token of the authorizer,
 * the complexity is that this access token also requires the refresh token
 * of the authorizer which is acquired by the open platform authorizer process.
 *
 * This completely overrides the original AccessToken.
 */
class AuthorizerAccessToken extends BaseAccessToken
{
    /**
     * @var \EasyWeChat\OpenPlatform\Authorizer
     */
    protected $authorizer;

    /**
     * AuthorizerAccessToken constructor.
     *
     * @param string                              $appId
     * @param \EasyWeChat\OpenPlatform\Authorizer $authorizer
     */
    public function __construct($appId, Authorizer $authorizer)
    {
        parent::__construct($appId, null);

        $this->authorizer = $authorizer;
    }

    /**
     * Get token from WeChat API.
     *
     * @param bool $forceRefresh
     *
     * @return string
     */
    public function getToken($forceRefresh = false)
    {
        $cached = $this->authorizer->getAccessToken();

        if ($forceRefresh || empty($cached)) {
            return $this->renewAccessToken();
        }

        return $cached;
    }

    /**
     * Refresh authorizer access token.
     *
     * @return string
     */
    protected function renewAccessToken()
    {
        $token = $this->authorizer->getApi()
            ->getAuthorizerToken(
                $this->authorizer->getAppId(),
                $this->authorizer->getRefreshToken()
            );

        $this->authorizer->setAccessToken($token['authorizer_access_token'], $token['expires_in'] - 1500);

        return $token['authorizer_access_token'];
    }

    /**
     * Return the AuthorizerAppId.
     *
     * @return string
     */
    public function getAppId()
    {
        return $this->authorizer->getAppId();
    }
}


<?php
/**
 * This file is part of the "Easy System" package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Damon Smith <damon.easy.system@gmail.com>
 */
namespace Es\Modules;

use Es\Services\ServicesInterface;
use ReflectionClass;

/**
 * Implements the core functionality of custom Module.
 */
abstract class AbstractModule
{
    /**
     * The module directory.
     *
     * @var string
     */
    private $moduleDir = '';

    /**
     * The module config.
     *
     * @var null|array
     */
    private $config;

    /**
     * Gets the version of module.
     *
     * @return string The version of module in format "X.Y.Z"
     */
    abstract public function getVersion();

    /**
     * Gets the module directory.
     *
     * @return string The module directory
     */
    final public function getModuleDir()
    {
        if (! $this->moduleDir) {
            $reflection      = new ReflectionClass(static::class);
            $this->moduleDir = dirname($reflection->getFileName());
        }

        return $this->moduleDir;
    }

    /**
     * Gets the system configuration, which is necessary for the module.
     *
     * @return array The system configuration
     */
    final public function getConfig()
    {
        if (null === $this->config) {
            $this->config = [];

            $configFile = $this->getModuleDir() . PHP_DS . 'config'
                        . PHP_DS . 'system.config.php';

            if (file_exists($configFile)) {
                $this->config = (array) require $configFile;
            }
        }

        return $this->config;
    }
}


<?php

/**
 * Jin Framework
 * Diatem
 */

namespace Jin2\Log;

use Jin2\Assets\AssetsInterface;
use Jin2\FileSystem\File;

/**
 * Outils de debuggage/dump
 */
class Debug implements AssetsInterface
{

  /**
   *  @var boolean  Etat d'activation de l'affichage des instructions de debug
   */
  protected static $activated = true;

  /**
   *  @var boolean  Premier trace/dump envoyé dans la sortie navigateur. (Pour affichage css nécessaire)
   */
  protected static $firstDump = false;

  /**
   * Implements getAssetUrl function
   *
   * @param string $key
   * @return string
   */
  public static function getAssetUrl($key)
  {
    $root =  __DIR__
      . DIRECTORY_SEPARATOR .'..'
      . DIRECTORY_SEPARATOR .'..'
      . DIRECTORY_SEPARATOR .'assets/';
    switch ($key) {
      case 'js':
        return $root . 'js/debug.js';
      case 'css':
        return $root . 'css/debug.css';
    }
    return null;
  }

  /**
   * Implements getAssetContent function
   *
   * @param string $key
   * @return string
   */
  public static function getAssetContent($key)
  {
    if ($url = static::getAssetUrl($key)) {
      return file_get_contents($url, FILE_USE_INCLUDE_PATH);
    }
    return null;
  }

  /**
   * Affiche le dump de la structure d'une variable
   *
   * @param  mixed    $var      Variable à tracer
   * @param  integer  $maxSize  Si renseigné, permet de limiter la taille des variables tracées.
   */
  public static function dump($var, $maxSize = null)
  {
    if (self::$activated) {
      print static::getDump($var, $maxSize);
    }
  }

  /**
   * Retourne le dump de la structure d'une variable
   *
   * @param  mixed   $var  Variable à tracer
   * @param  integer  $maxSize  Si renseigné, permet de limiter la taille des variables tracées.
   * @return string        Dump formaté HTML de la structure
   * @todo Tests sur les classes SGBD à refaire
   */
  public static function getDump($var, $maxSize = null)
  {

    // Trace
    $trace = debug_backtrace();

    // Initialise la sortie
    $dump = '';

    // Header
    $dump .= static::getHeader('Dump de variable');

    // Contexte
    $dump .= '
Contexte
';
    if (count($trace) > 2) {
      $dump .= static::getContext($trace[1], $trace[2]);
    } else {
      $dump .= static::getContext($trace[1]);
    }

    // Requête SQL
    if (is_object($var) && get_class($var) == 'sylab\common\sgbd\Query') {
      $dump .= '
Requête SQL
';
      $dump .= '

' . $var->getSql() . '

';
    }

    // Exploration
    $dump .= '
Exploration de la variable
';
    $dump .= '

';
    if (is_object($var) && get_class($var) == 'sylab\framework\query\Query') {
      $dump .= static::getDumpQueryResult($var->getQueryResults());
    } elseif (is_object($var) && get_class($var) == 'sylab\framework\query\QueryResult') {
      $dump .= static::getDumpQueryResult($var);
    } else {
      $dump .= static::getDumpContent($var, $maxSize);
    }
    $dump .= '

';

    // Footer
    $dump .= static::getFooter();
    return $dump;
  }

  /**
   * Retourne le dump d'une query
   *
   * @param  Query $var  Instance de Jin2\query\Query
   * @return string      Code HTML du dump de la Query
   */
  public static function getDumpQueryResult($var)
  {
    $header = true;
    $dump = '
';
    $i = 1;
    foreach ($var as $ligne) {
      // Affichage du header
      if ($header) {
        $dump .= '
';
        foreach ($ligne as $key => $value) {
          if (!is_numeric($key)) {
            $dump .= '' . $key . '	';
          }
        }
        $dump .= '
';
        $header = false;
      }
      // Affichage des données
      $class = '';
      if (!($i % 2)) {
        $class = 'highlight';
      }
      $dump .= '
';
      foreach ($ligne as $key => $value) {
        if (!is_numeric($key)) {
          if ($value != '') {
            $dump .= '' . $value . '	';
          } else {
            $dump .= ' 	';
          }
        }
      }
      $dump .= '
';
      $i++;
    }
    $dump .= '
';
    return $dump;
  }

  /**
   * Retourne le dump d'une variable standard
   *
   * @param  type $var  Variable à dumper
   * @return string     Dump formatté HTML
   */
  protected static function getDumpContent($var, $maxSize = null)
  {

    $dump = '
';
      $dump .= '
';
        $dump .= sprintf('
%s
', static::dumpElement($var, '', $maxSize));
      $dump .= '
';
    $dump .= '
';
    return $dump;
  }

  /**
   * Dump d'un élément (fonction recursive)
   *
   * @param  mixed   $var   Variable à tracer
   * @param  string  $name  Nom de l'élément ('' par défaut)
   * @param  integer  $maxSize  Si renseigné, permet de limiter la taille des variables tracées.
   * @return string         Dump de la variable
   */
  protected static function dumpElement($var, $name = '', $maxSize = null)
  {
    $dump = '';

    // On récupère le type de variable
    $type = gettype($var);

    // Is parcourable
    $iterable = $type == 'object' || $type == 'array';

    // Affichage des informations sur l'élément courant
    $dump .= '
';
    $dump .= '
';

    if ($name !== "") {
      $dump .= '
' . $name . '

';
    }
    $dump .= '
' . $type . '
';
    if ($type == 'string') {
      $dump .= '

(' . strlen($var) . ' caractères)
';
    } else if ($type == 'object') {
      $dump .= '

' . get_class($var) . '
';
    } else if ($type == 'array') {
      $dump .= '

(' . count($var) . ' éléments)
';
    }
    $dump .= '

';
    $dump .= '
';

    // Affichage du contenu
    if ($type == 'string') {

      $dt = htmlspecialchars($var);
      if($maxSize && strlen($dt) > $maxSize){
        $dt = substr($dt, 0, $maxSize).'[...]';
      }
      $dump .= '

' . $dt . '

';
    } else if ($type == 'boolean') {
      $dump .= '

' . ($var ? 'TRUE' : 'FALSE') . '

';
    } else if ($type == 'object') {
      $dump .= '';
    } else if ($type == 'array') {
      $dump .= '

';
    } else {
      $dump .= '

' . $var . '

';
    }

    // On parcourt les éléments iterables
    if ($iterable) {
      $dump .= '
';
      foreach ($var as $key => $e) {
        $dump .= static::dumpElement($e, $key, $maxSize);
      }
      $dump .= '
';
    }

    // Fermeture balise élément
    $dump .= '
';
    return $dump;
  }

  /**
   * Trace la pile d'execution
   */
  public static function trace()
  {
    if (self::$activated) {
      print static::getTrace();
    }
  }

  /**
   * Retourne le contenu d'un trace de la pile d'execution
   *
   * @return string  Contenu formaté de la pile d'execution
   */
  public static function getTrace()
  {
    // Trace
    $trace = debug_backtrace();

    // Initialise la sortie
    $dump = '';

    // Header
    $dump .= static::getHeader('Trace du contexte');

    // Contexte
    $dump .= '
Contexte
';

    $nb = count($trace);
    for ($i = 1; $i < $nb; $i++) {
      if ($i < $nb - 1) {
        $dump .= static::getContext($trace[$i], $trace[$i + 1]);
      } else {
        $dump .= static::getContext($trace[$i]);
      }
    }

    // Footer
    $dump .= static::getFooter();
    return $dump;
  }

  /**
   * Permet de rendre un contenu sous la forme d'un trace personnalisé
   *
   * @param  string $titre    Titre de la fenêtre
   * @param  string $content  Contenu à afficher
   * @return string           Contenu formatté HTML
   */
  public static function getCustomTrace($titre, $content)
  {
    // Initialise la sortie
    $dump = '';

    // Header
    $dump .= static::getHeader($titre);

    // Onglets
    foreach ($content as $onglet) {
      $dump .= sprintf('
%s
', $onglet['name']);
      $dump .= sprintf('
%s
', $onglet['content']);
    }

    // Footer
    $dump .= static::getFooter();
    return $dump;
  }

  /**
   * Retourne la balise style pour l'affichage des dump/trace
   *
   * @return string  Contenu style
   */
  protected static function getStyle()
  {
    $style = static::getAssetContent('css');
    return sprintf('', $style);
  }

  /**
   * Retourne la balise script pour l'affichage des dump/trace
   *
   * @return string  Contenu script
   */
  protected static function getScript()
  {
    $script = static::getAssetContent('js');
    return sprintf('', $script);
  }

  /**
   * Retourne la trace d'un contexte
   *
   * @param  array    $contexte   Contexte à analyser
   * @param  array    $rcontexte  Contexte servant à analyser la méthode courante (contexte à n+1)
   * @return string               Contexte formaté
   */
  public static function getContext($contexte, $rcontexte = NULL)
  {
    $dump = '';

    $segmentId = uniqid();
    $dump .= '
';
    $dump .= '
';
    $dump .= '' . $contexte['file'] . ' ligne ' . $contexte['line'] . '
';
    $dump .= '
';

    if (!is_null($rcontexte) && isset($rcontexte['function']) && $rcontexte['function'] != '') {
      $dump .= '
';
      if (isset($rcontexte['class'])) {
        $dump .= '
classe : ' . $rcontexte['class'] . '
';
      }
      $dump .= '
méthode : ' . $rcontexte['function'] . "(";

      if (isset($rcontexte['class'])) {
        // Cas d'une méthode
        $rm = new \ReflectionMethod($rcontexte['class'], $rcontexte['function']);
        $argsname = $rm->getParameters();
        $args = $rcontexte['args'];

        $nb = count($argsname);
        for ($i = 0; $i < $nb; $i++) {
          $ap = $argsname[$i];
          if ($i > 0) {
            $dump .= ', ';
          }
          $dump .= $argsname[$i]->name;
        }
      } else {
        // Cas d'une fonction
        $args = $rcontexte['args'];

        $nb = count($args);
        for ($i = 0; $i < $nb; $i++) {
          if ($i > 0) {
            $dump .= ', ';
          }
          $dump .= $i . '=\'' . $args[$i] . '\'';
        }
      }
      $dump .= ')
';
      $dump .= '
';
    }

    $file = new File($contexte['file']);
    $index = $contexte['line'] - 5;
    if ($index < 0) {
      $index = 0;
    }
    $fileLines = $file->getLines($index, 11, false);

    $nb = count($fileLines);
    for ($i = 0; $i < $nb; $i++) {
      if ($index == $contexte['line'] - 1) {
        $dump .= '
';
      } else {
        $dump .= '
';
      }

      $dump .= '
' . ($index + 1) . '

' . htmlspecialchars($fileLines[$i]) . '
';
      $index++;
      $dump .= '
';
    }
    $dump .= '

';
    $dump .= '
';
    $dump .= '
';

    return $dump;
  }

  /**
   * Retourne un header formaté d'une opération de debug/trace
   *
   * @param  string   $titre  (optional) Titre de la fenêtre (Vide par défaut)
   * @return string           Contenu formaté
   */
  protected static function getHeader($titre = NULL)
  {
    $dump = '';
    if (!self::$firstDump) {
      $dump .= static::getStyle();
      $dump .= static::getScript();
    }
    $dump .= '
';
    if ($titre) {
      $dump .= '
' . $titre . '
';
    }
    return $dump;
  }

  /**
   * Retourne un footer formaté d'une opération de debug/trace
   *
   * @return string  Contenu formaté
   */
  protected static function getFooter()
  {
    return '
';
  }

  /**
   * Active ou désactive les instructions de debug
   *
   * @param  boolean $etat   Etat d'activation
   */
  public static function setEnabled($etat)
  {
    self::$activated = $etat;
  }

  /**
   * Retourne le statut d'activation du debug
   *
   * @return boolean Etat d'activation
   */
  public static function getEnabled()
  {
    return self::$activated;
  }

}


<?php

namespace Versatile\Search;

use OutOfBoundsException;
use Versatile\Search\Contracts\SearchFactory;
use Versatile\Search\Contracts\Criteria as CriteriaContract;
use Collection\Support\FindsCallableByInheritance;

class ProxySearchFactory implements SearchFactory
{

    use FindsCallableByInheritance;

    /**
     * {@inheritdoc}
     *
     * @param \Versatile\Search\Contracts\Criteria $criteria
     * @return \Versatile\Search\Contracts\Search
     **/
    public function search(CriteriaContract $criteria)
    {

        if (!$factory = $this->nearestForClass($criteria->modelClass())) {
            throw new OutOfBoundsException('No factory for ' . $criteria->modelClass() . ' found');
        }

        return call_user_func($factory, $criteria);

    }

    /**
     * Assign a callable to create a search object for $modelClass
     *
     * @param string $class
     * @param callable $factory
     * @return self
     **/
    public function forModelClass($class, callable $factory)
    {
        return $this->addCallable($class, $factory);
    }
}


<?php

namespace Webforge\Types;

use Webforge\Common\ArrayUtil AS A;

abstract class DynamicEnumType extends EnumType {

  public function __construct(Type $valueType) {
    parent::__construct($valueType, array());
    $this->values = NULL; // die setzen wir selbst in dynamic values (kompatibler wäre hier array())
  }

  /**
   * @var array
   */
  protected $valueLabels = array();

  /**
   * Gibt entweder einen Array mit $value => $label oder einen array mit $value zurück
   *
   * wenn gesetzt (array nicht numerisch) werden die Labels der Componente dann vorgeschlagen, diese kann diese aber mit dem Labeler aber überschreiben
   *
   * @return assocArray|numericArray wenn assoc dann $value=>$label sonst list($value1, $value2, $value3) usw
   */
  abstract protected function getDynamicValues();

  public function getValues() {
    if (!isset($this->values)) {
      $dynamics = $this->getDynamicValues();
      // performance: kein check ob array

      if (A::isNumeric($dynamics)) {
        $this->values = $dynamics;
        $this->valueLabels = array();
      } else {
        $this->values = array_keys($dynamics);
        $this->valueLabels = $dynamics;
      }
    }

    return $this->values;
  }

  /**
   * Gibt die Component mit den Labels der Dynamic Values zurück (wenn gesetzt)
   *
   * Wird decoraten die Component wenn sie LabelerAware ist mit unseren Labels die wir aus den getDynamicValues erhalten, wenn der zurückgegebene array assoziativ ist
   * @return Psc\CMS\Component
   */
  public function getMappedComponent(\Webforge\Types\Adapters\ComponentMapper $componentMapper) {
    $component = parent::getMappedComponent($componentMapper); // ruft this getValues() auf, somit ist sichergestellt, dass valueLabels gesetzt ist

    if ($component instanceof \Psc\CMS\LabelerAware) {
      $labeler = $component->getLabeler();
      foreach ($this->valueLabels as $value => $label) {
        $labeler->addLabelMapping($value, $label);
      }
    }

    return $component;
  }
}


<?php

/**
 * @file
 *
 * @package In2pire
 * @subpackage Cli
 * @author Nhat Tran <nhat.tran@inspire.vn>
 */

namespace In2pire\Cli;

use Symfony\Component\Console\Output\ConsoleOutput;
use In2pire\Cli\Application as ConsoleApplication;
use In2pire\Cli\Command\Container as CommandContainer;
use In2pire\Cli\Input\ArgvInput as ConsoleInput;
use In2pire\Component\Utility\Text;

class CliApplication extends BaseCliApplication
{
    /**
     * Application name.
     *
     * @var string
     */
    protected $name = null;

    /**
     * Version.
     *
     * @var string
     */
    protected $version = null;

    /**
     * Description.
     *
     * @var string
     */
    protected $description = null;

    /**
     * Application alias.
     */
    protected $alias = null;

    /**
     * CLI input.
     * @var Symfony\Component\Console\Input\ArgvInput
     */
    protected $request = null;

    /**
     * CLI output
     * @var Symfony\Component\Console\Output\ConsoleOutput
     */
    protected $response = null;

    /**
     * Application runner.
     *
     * @var string
     */
    protected $runner = null;

    /**
     * List of commands defined in settings file.
     *
     * @var array
     */
    protected $commands = [];

    public function __construct()
    {
        // Read settings file.
        $this->settings = Configuration::getInstance()->getAll('application', true);

        // Set application name.
        if (isset($this->settings['name'])) {
            $this->name = $this->settings['name'];
        }

        // Read application version.
        if (isset($this->settings['version'])) {
            $this->version = $this->settings['version'];
        }

        // Read application description.
        if (isset($this->settings['description'])) {
            $this->description = $this->settings['description'];
        }

        // Read application alias.
        if (isset($this->settings['alias'])) {
            $this->alias = $this->settings['alias'];
        }

        if (isset($this->settings['token'])) {
            foreach ($this->settings['token'] as $key => $callback) {
                list($class, $action) = explode('::', $callback);

                $class = explode('.', $class);
                $class = array_map(array('In2pire\\Component\\Utility\\Text', 'convertToCamelCase'), $class);
                $class = implode('\\', $class);

                Token::register($key, [$class, $action]);
            }
        }

        // Prepare symfony cli application.
        $this->runner = $this->getRunner();
        $this->request = new ConsoleInput();
        $this->response = new ConsoleOutput();

        if (!empty($this->settings['commands']) && is_array($this->settings['commands'])) {
            $this->commands = $this->settings['commands'];
        }

        foreach ($this->commands as $commandName) {
            if ($command = CommandContainer::create($commandName, $this)) {
                $command->setApplication($this->runner);
                $this->runner->add($command);
                $this->commands[$commandName] = $command;
            }
        }

        // Allow to change default command in configuration file.
        if (!empty($this->settings['default-command'])) {
            $defaultCommand = $this->settings['default-command'];

            if (empty($this->commands[$defaultCommand])) {
                throw new \RuntimeException('Cannot find default command ' . $defaultCommand);
            }

            $defaultCommand = $this->commands[$defaultCommand];
            $this->runner->setDefaultCommand($defaultCommand->getName());
        }
    }

    /**
     * Get console application object.
     *
     * @return \Symfony\Component\Console\Application
     *   Console Application.
     */
    protected function getRunner()
    {
        if (null === $this->runner) {
            $this->runner = new ConsoleApplication($this->name, $this->version, $this->description, $this->alias);
        }

        return $this->runner;
    }

    /**
     * Get Application settings.
     *
     * @return array
     *   List of settings.
     */
    public function getSettings()
    {
        return $this->settings;
    }

    /**
     * Set a settings.
     *
     * @param string $name
     *   Setting name.
     * @param mixed $default
     *   (optional) Default value if cannot find setting.
     *
     * @return mixed
     *   Setting.
     */
    public function getSetting($name, $default = null)
    {
        return empty($this->settings[$name]) ? $default : $this->settings[$name];
    }

    /**
     * Get application name.
     *
     * @return string
     *   Name.
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Get application version.
     *
     * @return string
     *   Version.
     */
    public function getVersion()
    {
        return $this->version;
    }

    /**
     * Boot application.
     *
     * @return In2pire\Cli\ApplicationInterface.
     *   The called object.
     */
    public function boot()
    {
        if ($this->booted) {
            // Already booted.
            return $this;
        }

        // Boot parent.
        parent::boot();

        return $this;
    }

    /**
     * Run application.
     *
     * @return In2pire\Cli\ApplicationInterface.
     *   The called object.
     */
    public function run()
    {
        // Boot the application.
        if (false === $this->boot()) {
            exit(1);
        }

        // Let symfony/console do the rest.
        $this->runner->run($this->request, $this->response);
        return $this;
    }
}


<?php

namespace Gaufrette\Core\Operator;

use Gaufrette\Core\Adapter;
use Gaufrette\Core\File;

final class SizeOperator extends AbstractOperator implements CanLoad
{
    /**
     * {@inheritdoc}
     */
    public function supports(File $file, Adapter $adapter)
    {
        return $this->adapterHasBehavior($adapter, 'Gaufrette\Core\Adapter\KnowsSize');
    }

    /**
     * {@inheritdoc}
     */
    public function load(File $file, Adapter $adapter)
    {
        $file->setSize($adapter->readSize($file->getName()));
    }
}