<?php

namespace Cpwc\Lta\HttpClient;

use Guzzle\Http\Client as GuzzleClient;
use Guzzle\Http\ClientInterface;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
use Cpwc\Lta\Exception\ErrorException;
use Cpwc\Lta\Exception\RuntimeException;
use Cpwc\Lta\HttpClient\Listener\AuthListener;
use Cpwc\Lta\HttpClient\Listener\ErrorListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Performs requests on LTA DataMall API. API documentation should be self-explanatory.
 *
 * @author Poh Wei Cheng <calvinpohwc@gmail.com>
 */
class HttpClient implements HttpClientInterface
{
    protected $options = array(
        'base_url'   => 'http://datamall2.mytransport.sg/ltaodataservice/',
        'user_agent' => 'php-lta-api (https://github.com/cpwc/php-lta-api)',
        'accept'     => 'application/json',
        'timeout'    => 10,
        'cache_dir'  => null
    );

    protected $headers = array();

    private $lastResponse;
    private $lastRequest;

    /**
     * @param array           $options
     * @param ClientInterface $client
     */
    public function __construct(array $options = array(), ClientInterface $client = null)
    {
        $this->options = array_merge($this->options, $options);
        $client = $client ?: new GuzzleClient($this->options['base_url'], $this->options);
        $this->client = $client;

        $this->addListener('request.error', array(new ErrorListener($this->options), 'onRequestError'));
        $this->clearHeaders();
    }

    /**
     * {@inheritDoc}
     */
    public function setOption($name, $value)
    {
        $this->options[$name] = $value;
    }

    /**
     * {@inheritDoc}
     */
    public function setHeaders(array $headers)
    {
        $this->headers = array_merge($this->headers, $headers);
    }

    /**
     * Clears used headers.
     */
    public function clearHeaders()
    {
        $this->headers = array(
            'Accept'     => 'application/json',
            'User-Agent' => sprintf('%s', $this->options['user_agent']),
        );
    }

    public function addListener($eventName, $listener)
    {
        $this->client->getEventDispatcher()->addListener($eventName, $listener);
    }

    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        $this->client->addSubscriber($subscriber);
    }

    /**
     * {@inheritDoc}
     */
    public function get($path, array $parameters = array(), array $headers = array())
    {
        return $this->request($path, null, 'GET', $headers, array('query' => $parameters));
    }

    /**
     * {@inheritDoc}
     */
    public function post($path, $body = null, array $headers = array())
    {
        return $this->request($path, $body, 'POST', $headers);
    }

    /**
     * {@inheritDoc}
     */
    public function patch($path, $body = null, array $headers = array())
    {
        return $this->request($path, $body, 'PATCH', $headers);
    }

    /**
     * {@inheritDoc}
     */
    public function delete($path, $body = null, array $headers = array())
    {
        return $this->request($path, $body, 'DELETE', $headers);
    }

    /**
     * {@inheritDoc}
     */
    public function put($path, $body, array $headers = array())
    {
        return $this->request($path, $body, 'PUT', $headers);
    }

    /**
     * {@inheritDoc}
     */
    public function request(
        $path,
        $body = null,
        $httpMethod = 'GET',
        array $headers = array(),
        array $options = array()
    ) {
        $request = $this->createRequest($httpMethod, $path, $body, $headers, $options);

        try {
            $response = $this->client->send($request);
        } catch (\LogicException $e) {
            throw new ErrorException($e->getMessage(), $e->getCode(), $e);
        } catch (\RuntimeException $e) {
            throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
        }

        $this->lastRequest = $request;
        $this->lastResponse = $response;

        return $response;
    }

    /**
     * {@inheritDoc}
     */
    public function authenticate($accountKey, $uniqueUserId, $method)
    {
        $this->addListener('request.before_send', array(
            new AuthListener($accountKey, $uniqueUserId, $method),
            'onRequestBeforeSend'
        ));
    }

    /**
     * @return Request
     */
    public function getLastRequest()
    {
        return $this->lastRequest;
    }

    /**
     * @return Response
     */
    public function getLastResponse()
    {
        return $this->lastResponse;
    }

    protected function createRequest(
        $httpMethod,
        $path,
        $body = null,
        array $headers = array(),
        array $options = array()
    ) {
        return $this->client->createRequest(
            $httpMethod,
            $path,
            array_merge($this->headers, $headers),
            $body,
            $options
        );
    }
}


<?php

/**
 * HTTP response for controllers.
 *
 * @link http://framework.zend.com/manual/1.12/en/zend.controller.response.html Zend_Controller_Response_Http
 */
class Benri_Controller_Response_Http extends Zend_Controller_Response_Http
{
    /**
     * @internal
     * @var array
     */
    private static $_messages = [
        // Informational 1xx
        100 => 'Continue',
        101 => 'Switching Protocols',

        // Success 2xx
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',

        // Redirection 3xx
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',  // 1.1
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        // 306 is deprecated but reserved
        307 => 'Temporary Redirect',

        // Client Error 4xx
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        422 => 'Unprocessable Entity',

        // Server Error 5xx
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        509 => 'Bandwidth Limit Exceeded',
    ];

    /**
     * Return the message related to `$code`.
     *
     * @param int
     * @return string
     */
    public function getMessageFromCode($code)
    {
        if (array_key_exists($code, self::$_messages)) {
            return self::$_messages[$code];
        }
    }

    /**
     * Send all headers.
     *
     * Sends any headers specified. If an HTTP response code has been
     * specified, it is sent with the first header.
     *
     * @return Benri_Controller_Response_Http
     */
    public function sendHeaders()
    {
        // Only check if we can send headers if we have headers to send
        if (count($this->_headersRaw) || count($this->_headers) || (200 !== $this->_httpResponseCode)) {
            $this->canSendHeaders(true);
        } elseif (200 === $this->_httpResponseCode) {
            // Haven't changed the response code, and we have no headers
            return $this;
        }

        $httpCodeSent = false;

        foreach ($this->_headersRaw as $header) {
            if (!$httpCodeSent && $this->_httpResponseCode) {
                header($header, true, $this->_httpResponseCode);
                $httpCodeSent = true;
            } else {
                header($header);
            }
        }

        foreach ($this->_headers as $header) {
            header("{$header['name']}: {$header['value']}", $header['replace']);
        }

        if (!$httpCodeSent) {
            $message = array_key_exists($this->_httpResponseCode, self::$_messages)
                ? self::$_messages[$this->_httpResponseCode]
                : 'No Reason Phrase';

            header("HTTP/1.1 {$this->_httpResponseCode} {$message}", true);
            $httpCodeSent = true;
        }

        return $this;
    }
}


<?php
namespace eMacros\Runtime\Binary;

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

class BinaryAnd implements Applicable {
	/**
	 * Applies the binary AND to a list of operands
	 * Usage: (& 11 5 1)
	 * Returns: number
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		if (count($arguments) == 0) throw new \BadFunctionCallException("BinaryAnd: No parameters found.");
		$it = $arguments->getIterator();
		$it->rewind();
		if (!$it->valid()) return 0;
		$value = $it->current()->evaluate($scope);
		for ($it->next(); $it->valid(); $it->next())
			$value &= $it->current()->evaluate($scope);
		return $value;
	}
}
?>


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB\DemoContent;

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

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

Page non trouvée

La page que vous tentez d'afficher n'existe pas. Vérifiez s'il vous plait que l'url est correcte.

EOF;
        $routePattern = "errorPage404";
        $language = "fr";

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

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

Page not found

The page you are trying to display does not exist. Please verify the url is correct.

EOF;
        $routePattern = "errorPage404";
        $language = "en";

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

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

Seite nicht gefunden

Die Seite, die Sie versuchen, existiert nicht angezeigt werden soll. Bitte überprüfen Sie die URL korrekt ist.

EOF;
        $routePattern = "errorPage404";
        $language = "de";

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

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

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

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

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

        $nodeError404->setNodeType(NodeInterface::TYPE_ERROR);
        $nodeError404->setLanguage($language);
        $nodeError404->setNodeId(NodeInterface::ERROR_404_NODE_ID);
        $nodeError404->setName('404');
        $nodeError404->setVersionName($this->getVersionName($nodeError404));
        $nodeError404->setCreatedBy('fake_admin');
        $nodeError404->setParentId(NodeInterface::ROOT_PARENT_ID);
        $nodeError404->setRoutePattern($routePattern);
        $nodeError404->setInFooter(false);
        $nodeError404->setInMenu(false);
        $nodeError404->setOrder(-1);

        return $nodeError404;
    }
}


<?php

declare(strict_types=1);

namespace GBProd\ElasticaSpecification\QueryFactory;

use Elastica\QueryBuilder;
use GBProd\ElasticaSpecification\Registry;
use GBProd\Specification\Not;
use GBProd\Specification\Specification;

/**
 * Factory for Not specification
 *
 * @author gbprod <contact@gb-prod.fr>
 */
class NotFactory implements Factory
{
    /**
     * @var Registry
     */
    private $registry;

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

    /**
     * {inheritdoc}
     */
    public function create(Specification $spec, QueryBuilder $qb)
    {
        if (!$spec instanceof Not) {
            throw new \InvalidArgumentException();
        }

        $firstPartFactory = $this->registry->getFactory($spec->getWrappedSpecification());

        return $qb->query()->bool()
            ->addMustNot($firstPartFactory->create($spec->getWrappedSpecification(), $qb))
        ;
    }
}


<?php

/*
 * This file is part of the Common API Interface package.
 *
 * (c) Pavel Logachev <alhames@mail.ru>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Alhames\Api\Authentication;

use Alhames\Api\Exception\AuthenticationException;
use Alhames\Api\HttpInterface;
use GuzzleHttp\Exception\GuzzleException;

/**
 * Class OAuth2AuthenticationHelper.
 *
 * @see https://tools.ietf.org/html/rfc6749
 */
abstract class AbstractOAuth2Client extends AbstractAuthenticationClient
{
    /** @var string */
    protected $accessToken;
    /** @var string */
    protected $clientId;
    /** @var string */
    protected $clientSecret;
    /** @var array|string */
    protected $scope;

    /**
     * {@inheritdoc}
     */
    public function __construct(array $config)
    {
        parent::__construct($config);

        if (empty($config['redirect_uri'])) {
            throw new \InvalidArgumentException('Option "redirect_uri" is required.');
        }
        if (empty($config['client_id'])) {
            throw new \InvalidArgumentException('Option "client_id" is required.');
        }
        if (empty($config['client_secret'])) {
            throw new \InvalidArgumentException('Option "client_secret" is required.');
        }

        $this->redirectUri = $config['redirect_uri'];
        $this->clientId = $config['client_id'];
        $this->clientSecret = $config['client_secret'];
        $this->accessToken = $config['access_token'] ?? null;
        $this->scope = $config['scope'] ?? null;
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthenticationUri(?string $state = null, array $options = []): string
    {
        $query = array_merge($options, [
            'response_type' => 'code',
            'client_id' => $this->clientId,
        ]);

        if (!isset($query['redirect_uri'])) {
            $query['redirect_uri'] = $this->redirectUri;
        }

        if (!isset($query['scope']) && null !== $this->scope) {
            $query['scope'] = $this->scope;
        }

        if (isset($query['scope']) && is_array($query['scope'])) {
            $query['scope'] = implode(' ', $query['scope']);
        }

        if (null !== $state) {
            $query['state'] = $state;
        }

        return $this->getAuthEndpoint().'?'.http_build_query($query);
    }

    /**
     * {@inheritdoc}
     */
    public function authenticate(array $options = []): array
    {
        if (empty($options['code']) || !is_string($options['code'])) {
            throw AuthenticationException::invalidArgument('code', $options);
        }

        $query = [
            'grant_type' => 'authorization_code',
            'code' => $options['code'],
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret,
            'redirect_uri' => $options['redirect_uri'] ?? $this->redirectUri,
        ];

        try {
            $data = (array) $this->httpClient->requestJson(HttpInterface::METHOD_POST, $this->getTokenEndpoint(), null, $query);
        } catch (GuzzleException $e) {
            throw $this->handleApiException($e);
        }

        if (empty($data['access_token'])) {
            throw new AuthenticationException($data, 'OAuth2 authentication is failed.');
        }

        $this->setAccessToken($data['access_token']);

        return $data;
    }

    /**
     * @param null|string $accessToken
     *
     * @return static
     */
    public function setAccessToken(?string $accessToken)
    {
        $this->accessToken = $accessToken;

        return $this;
    }

    /**
     * @see https://tools.ietf.org/html/rfc6749#section-1.4
     *
     * @return null|string
     */
    public function getAccessToken(): ?string
    {
        return $this->accessToken;
    }

    /**
     * {@inheritdoc}
     *
     * @see https://tools.ietf.org/html/rfc6750#section-2.1
     */
    public function request(string $method, array $query = [], string $httpMethod = HttpInterface::METHOD_GET)
    {
        $uri = $this->getApiEndpoint($method);
        $get = HttpInterface::METHOD_GET === $httpMethod ? $query : null;
        $post = HttpInterface::METHOD_GET !== $httpMethod ? $query : null;
        $headers = null !== $this->accessToken ? [HttpInterface::HEADER_AUTHORIZATION => 'Bearer '.$this->accessToken] : null;

        try {
            return $this->httpClient->requestJson($httpMethod, $uri, $get, $post, null, $headers);
        } catch (GuzzleException $e) {
            throw $this->handleApiException($e);
        }
    }

    /**
     * @see https://tools.ietf.org/html/rfc6749#section-3.2
     *
     * @return string
     */
    abstract protected function getTokenEndpoint(): string;
}


<?php

declare(strict_types=1);

namespace Ruwork\Reform\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class CheckboxTypeFalseValueExtension extends AbstractTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public static function getExtendedTypes(): iterable
    {
        return [CheckboxType::class];
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefined('false_value')
            ->setDefault('false_values', function (Options $options, $defaultFalseValues = null): array {
                if (isset($options['false_value'])) {
                    return [$options['false_value']];
                }

                return $defaultFalseValues ?? [];
            })
            ->setAllowedTypes('false_value', 'string');
    }

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        if (array_key_exists('false_value', $options)) {
            $view->vars['false_value'] = $options['false_value'];
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getExtendedType()
    {
        return CheckboxType::class;
    }
}


<?php

namespace Litecms\Forum\Policies;

use Litepie\User\Contracts\UserPolicy;
use Litecms\Forum\Models\Question;

class QuestionPolicy
{

    /**
     * Determine if the given user can view the question.
     *
     * @param UserPolicy $user
     * @param Question $question
     *
     * @return bool
     */
    public function view(UserPolicy $user, Question $question)
    {
        if ($user->canDo('forum.question.view') && $user->isAdmin()) {
            return true;
        }

        return $question->user_id == user_id() && $question->user_type == user_type();
    }

    /**
     * Determine if the given user can create a question.
     *
     * @param UserPolicy $user
     * @param Question $question
     *
     * @return bool
     */
    public function create(UserPolicy $user)
    {
        return  $user->canDo('forum.question.create');
    }

    /**
     * Determine if the given user can update the given question.
     *
     * @param UserPolicy $user
     * @param Question $question
     *
     * @return bool
     */
    public function update(UserPolicy $user, Question $question)
    {
        if ($user->canDo('forum.question.edit') && $user->isAdmin()) {
            return true;
        }

        return $question->user_id == user_id() && $question->user_type == user_type();
    }

    /**
     * Determine if the given user can delete the given question.
     *
     * @param UserPolicy $user
     * @param Question $question
     *
     * @return bool
     */
    public function destroy(UserPolicy $user, Question $question)
    {
        return $question->user_id == user_id() && $question->user_type == user_type();
    }

    /**
     * Determine if the given user can verify the given question.
     *
     * @param UserPolicy $user
     * @param Question $question
     *
     * @return bool
     */
    public function verify(UserPolicy $user, Question $question)
    {
        if ($user->canDo('forum.question.verify')) {
            return true;
        }

        return false;
    }

    /**
     * Determine if the given user can approve the given question.
     *
     * @param UserPolicy $user
     * @param Question $question
     *
     * @return bool
     */
    public function approve(UserPolicy $user, Question $question)
    {
        if ($user->canDo('forum.question.approve')) {
            return true;
        }

        return false;
    }

    /**
     * Determine if the user can perform a given action ve.
     *
     * @param [type] $user    [description]
     * @param [type] $ability [description]
     *
     * @return [type] [description]
     */
    public function before($user, $ability)
    {
        if ($user->isSuperuser()) {
            return true;
        }
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\SynchronizerBundle\DependencyInjection\Compiler;

use Ruwork\Synchronizer\Type\TypeInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

final class RegisterSynchronizationTypesPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container): void
    {
        if (!$container->has('ruwork_synchronizer.factory')) {
            return;
        }

        $syncTypes = $container->findTaggedServiceIds('ruwork_synchronizer.synchronization_type', true);
        $syncTypeRefs = [];

        foreach ($syncTypes as $id => $attributes) {
            $class = $container->getDefinition($id)->getClass();

            if (!is_subclass_of($class, TypeInterface::class)) {
                throw new \InvalidArgumentException(sprintf('Synchronization type "%s" must implement "%s".', $class, TypeInterface::class));
            }

            $syncTypeRefs[$class] = new Reference($id);
        }

        $container
            ->findDefinition('ruwork_synchronizer.factory')
            ->setArgument('$types', ServiceLocatorTagPass::register($container, $syncTypeRefs));
    }
}


<?php

namespace Esockets\Protocol;

use Esockets\Base\AbstractProtocol;
use Esockets\Base\CallbackEventListener;
use Esockets\Base\Exception\ReadException;
use Esockets\Base\Exception\SendException;
use Esockets\Base\IoAwareInterface;
use Esockets\Base\PingPacket;
use Esockets\Base\PingSupportInterface;

/**
 * Протокол-обёртка над php-шными структурами данных,
 * передаваемых по сети.
 * В задачи данного протокола входит:
 *  - сериализация (json-изация) отправляемых структур данных
 *  - уведомления о доставке (нужно для UDP) todo
 *  - десериализация полученных на другой стороне данных.
 */
final class EasyDataGram extends AbstractProtocol implements PingSupportInterface
{
    /**
     * ID последнего отправленного пакета.
     *
     * @var int
     */
    private $lastSendPacketId = 1;
    private $pingCallback;
    private $pongCallback;

    /**
     * @inheritDoc
     */
    public function __construct(IoAwareInterface $provider)
    {
        parent::__construct($provider);
    }

    /**
     * @inheritDoc
     */
    public function returnRead()
    {
        $result = null;
        $data = $this->provider->read($this->provider->getReadBufferSize(), false);
        if (null !== $data) {
            $result = $this->unpack($data);
            if ($result instanceof PingPacket) {
                if (!$result->isResponse()) {
                    if (!$this->send(PingPacket::response($result->getValue()))) {
                        throw new \RuntimeException('Cannot send pong packet.');
                    }
                    $this->pingReceived($result);
                } else {
                    $this->pongReceived($result);
                }
                $result = null;
            }
        }
        return $result;
    }

    /**
     * Распаковывает принятые из сокета данные.
     * Возвращает null если данные не были распакованы по неизвестным причинам.
     *
     * @param string $raw
     *
     * @return mixed
     * @throws ReadException
     */
    private function unpack(string $raw)
    {
        if (null === ($data = json_decode($raw, true)) && json_last_error() > 0) {
            throw new ReadException('Cannot decode json packet.', ReadException::ERROR_PROTOCOL);
        }
        if (!isset($data['type']) || !isset($data['data']) || !isset($data['id'])) {
            throw new ReadException('Invalid packet received.', ReadException::ERROR_PROTOCOL);
        }
        switch ($data['type']) {
            case 'string':
            case 'array':
                $data = $data['data'];
                break;
            case 'integer':
                $data = (int)$data['data'];
                break;
            case 'float':
                $data = (float)$data['data'];
                break;
            case 'double':
                $data = (double)$data['data'];
                break;
            case 'object':
                $data = unserialize($data['data']);
                break;
            default:
                throw new ReadException(
                    sprintf(
                        'Unknown packet data type "%s".',
                        $data['type']
                    ), ReadException::ERROR_PROTOCOL
                );
        }
        return $data;
    }

    /**
     * @inheritdoc
     */
    public function send($data): bool
    {
        $packetId = $this->lastSendPacketId++;
        $packet = $this->pack($packetId, $data);
        if (!$this->provider->send($packet)) {
            return false;
        }
        return true;
    }

    /**
     * Пакует данные в пакеты, и возвращает массив пакетов,
     * которые можно отправлять в любом порядке.
     *
     * @param int $packetId
     * @param mixed $data
     *
     * @return string
     * @throws SendException
     */
    private function pack(int $packetId, $data): string
    {
        if (!$this->canSend($type = gettype($data))) {
            throw new SendException('Cannot send data of type "' . $type . '".');
        }
        if ($type === 'object') {
            $data = serialize($data);
        }
        $data = json_encode([
            'id' => $packetId,
            'type' => $type,
            'data' => $data,
        ]);

        $maxPacketSize = $this->provider->getMaxPacketSizeForWriting();
        if ($maxPacketSize > 0 && strlen($data) > $maxPacketSize) {
            throw new SendException('Large size of data to send! Please break it into your code.');
        }
        return $data;
    }

    /**
     * Выбирает флаг соотетствующий типу данных.
     *
     * @param string $dataType
     *
     * @return int
     */
    private function canSend(string $dataType): int
    {
        switch ($dataType) {
            case 'boolean':
            case 'resource':
            case 'NULL':
            case 'unknown type':
                return false;
        }
        return true;
    }

    private function pingReceived(PingPacket $ping): void
    {
        if (null !== $this->pingCallback) {
            call_user_func($this->pingCallback, $ping);
        }
    }

    private function pongReceived(PingPacket $pong): void
    {
        if (null !== $this->pongCallback) {
            call_user_func($this->pongCallback, $pong);
            $this->pongCallback = null;
        }
    }

    /**
     * @inheritDoc
     */
    public function onReceive(callable $callback): CallbackEventListener
    {
        return $this->eventReceive->attachCallbackListener($callback);
    }

    /**
     * @inheritdoc
     */
    public function ping(PingPacket $pingPacket): void
    {
        $this->send($pingPacket);
    }

    /**
     * @inheritdoc
     */
    public function onPingReceived(callable $pingReceived): void
    {
        $this->pingCallback = $pingReceived;
    }

    /**
     * @inheritdoc
     */
    public function pong(callable $pongReceived): void
    {
        $this->pongCallback = $pongReceived;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Repository;

use OpenOrchestra\ModelInterface\Repository\TrashItemRepositoryInterface;
use OpenOrchestra\Pagination\Configuration\PaginateFinderConfiguration;
use OpenOrchestra\Repository\AbstractAggregateRepository;
use Solution\MongoAggregation\Pipeline\Stage;

/**
 * Class TrashItemRepository
 */
class TrashItemRepository extends AbstractAggregateRepository implements TrashItemRepositoryInterface
{
    /**
     * @param PaginateFinderConfiguration $configuration
     * @param string                      $siteId
     *
     * @return array
     */
    public function findForPaginate(PaginateFinderConfiguration $configuration, $siteId)
    {
        $qa = $this->createAggregationQuery();

        $this->filterSearch($configuration, $qa, $siteId);

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

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

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

    /**
     * @param PaginateFinderConfiguration $configuration
     * @param string                      $siteId
     *
     * @return int
     */
    public function countWithFilter(PaginateFinderConfiguration $configuration, $siteId)
    {
        $qa = $this->createAggregationQuery();
        $this->filterSearch($configuration, $qa, $siteId);

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

    /**
     * @param string $siteId
     *
     * @return int
     */
    public function countBySite($siteId)
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array('siteId' => $siteId));

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

    /**
     * @param array $trashItemIds
     *
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
     */
    public function removeTrashItems(array $trashItemIds)
    {
        array_walk($trashItemIds, function(&$trashItemId) {$trashItemId = new \MongoId($trashItemId);});

        $qb = $this->createQueryBuilder();
        $qb->remove()
            ->field('id')->in($trashItemIds)
            ->getQuery()
            ->execute();
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     * @param Stage                       $qa
     * @param string                      $siteId
     *
     * @return array
     */
    protected function filterSearch(PaginateFinderConfiguration $configuration, Stage $qa, $siteId)
    {
        $qa->match(array('siteId' => $siteId));

        $name = $configuration->getSearchIndex('name');
        if (null !== $name && '' !== $name) {
            $qa->match(array('name' => new \MongoRegex('/.*'.$name.'.*/i')));
        }

        $type = $configuration->getSearchIndex('type');
        if (null !== $type && '' !== $type) {
            $qa->match(array('type' => $type));
        }

        $dateBefore = $configuration->getSearchIndex('date-before');
        if (null !== $dateBefore && '' !== $dateBefore) {
            $dateFormatBefore = $configuration->getSearchIndex('date-format-before');
            if (null !== $dateFormatBefore && '' !== $dateFormatBefore) {
                $dateBefore = $this->getFormattedDate($dateBefore, $dateFormatBefore);
                $qa->match(array('deletedAt' => array('$lt' => new \MongoDate(strtotime($dateBefore)))));
            }
        }

        $dateAfter = $configuration->getSearchIndex('date-after');
        if (null !== $dateAfter && '' !== $dateAfter) {
            $dateFormatAfter = $configuration->getSearchIndex('date-format-after');
            if (null !== $dateFormatAfter && '' !== $dateFormatAfter) {
                $dateAfter = $this->getFormattedDate($dateAfter, $dateFormatAfter);
                $qa->match(array('deletedAt' => array('$gt' => new \MongoDate(strtotime($dateAfter)))));
            }
        }

        return $qa;
    }

    /**
     * @param string $date
     * @param string $dateFormat
     *
     * @return \DateTime
     */
    protected function getFormattedDate($date, $dateFormat)
    {
        $dateFormat = str_replace('yy', 'Y', $dateFormat);
        $dateFormat = str_replace('mm', 'm', $dateFormat);
        $dateFormat = str_replace('dd', 'd', $dateFormat);

        return \DateTime::createFromFormat($dateFormat, $date)->format('Y-m-d');
    }
}


<?php

namespace AdminBundle\Service;

/**
 * Class YoutubeService
 *
 * This is the class that communicates with YouTube api
 */
class YoutubeService extends \Google_Service_YouTube
{
    /**
     * @var GoogleClient client
     */
    public $client;

    /**
     * Constructor
     * @param GoogleClient $client
     */
    public function __construct(GoogleClient $client)
    {
        $this->client = $client;
        parent::__construct($client->getGoogleClient());
    }

    /**
     * Get status of a video
     * Return an array like this one:
     * array(
     *    "uploadStatus"        => "processed",
     *    "privacyStatus"       => "public",
     *    "license"             => "youtube",
     *    "embeddable"          => true,
     *    "publicStatsViewable" => true
     * )
     *
     * @param  string $videoId
     * @return array
     */
    public function getStatus($videoId)
    {
        $listResponse = $this->videos->listVideos('status', array('id' => $videoId));
        if (empty($listResponse)) {
            throw new \RuntimeException(sprintf('Could not find video with id %s', $videoId));
        }

        return $listResponse['items'][0]['status'];
    }

    /**
     * Get thumbnails of a video
     * You can specify a format. If so, you get a single thumbnail of specified format,
     * otherwise you get an array with all three available formats
     *
     * @param  string $videoId
     * @param  string $format  "default", "medium", "high", or null
     * @return array
     */
    public function getThumbnails($videoId, $format = null)
    {
        $listResponse = $this->videos->listVideos('snippet', array('id' => $videoId));
        if (empty($listResponse)) {
            throw new \RuntimeException(sprintf('Could not find video with id %s', $videoId));
        }
        $video = $listResponse[0];
        $videoSnippet = $video['snippet'];
        if (is_null($format)) {
            return $videoSnippet['thumbnails']['data'];
        }
        if (!in_array($format, array('default', 'medium', 'high'))) {
            throw new \InvalidArgumentException(sprintf('Invalid format "%s"', $format));
        }

        return $videoSnippet['thumbnails']['data'][$format];
    }

    /**
     * Get related videos
     * See https://developers.google.com/youtube/v3/docs/search/list#response for returned value
     *
     * @param  string $videoId
     * @return array
     */
    public function getRelatedVideos($videoId)
    {
        $listResponse = $this->search->listSearch('snippet', array('relatedToVideoId' => $videoId, 'type' => 'video'));
        if (empty($listResponse)) {
            throw new \RuntimeException(sprintf('Could not find video with id %s', $videoId));
        }

        return $listResponse;
    }
}


<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Cityware\Regex;

/**
 * Description of VerbalExpressions
 *
 * @author fabricio.xavier
 */
class VerbalExpressions {

    public $prefixes = "";
    public $source = "";
    public $suffixes = "";
    public $modifiers = "m"; // default to global multi line matching
    public $replaceLimit = 1;   // the limit of preg_replace when g modifier is not set
    protected $lastAdded = false; // holds the last added regex

    /**
     * Sanitize
     *
     * Sanitation function for adding anything safely to the expression
     *
     * @access public
     * @param  string $value the to be added
     * @return string escaped value
     */

    public static function sanitize($value) {
        return $value ? preg_quote($value, "/") : $value;
    }

    /**
     * Add
     *
     * Add stuff to the expression
     *
     * @access public
     * @param  string $value the stuff to be added
     * @return VerbalExpressions
     */
    public function add($value) {
        $this->source .= $this->lastAdded = $value;
        return $this;
    }

    /**
     * Start of Line
     *
     * Mark the expression to start at the beginning of the line.
     *
     * @access public
     * @param  boolean $enable Enables or disables the line starting. Default value: true
     * @return VerbalExpressions
     */
    public function startOfLine($enable = true) {
        $this->prefixes = $enable ? "^" : "";
        return $this;
    }

    /**
     * End of line
     *
     * Mark the expression to end at the last character of the line.
     *
     * @access public
     * @param  boolean $enable Enables or disables the line ending. Default value: true
     * @return VerbalExpressions
     */
    public function endOfLine($enable = true) {
        $this->suffixes = $enable ? "$" : "";
        return $this;
    }

    /**
     * Then
     *
     * Add a string to the expression
     *
     * @access public
     * @param  string $value The string to be looked for
     * @return VerbalExpressions
     */
    public function then($value) {
        return $this->add("(?:" . self::sanitize($value) . ")");
    }

    /**
     * Find
     *
     * alias for then()
     * @param  string $value The string to be looked for
     * @return VerbalExpressions
     */
    public function find($value) {
        return $this->then($value);
    }

    /**
     * Maybe
     *
     * Add a string to the expression that might appear once (or not).
     *
     * @access public
     * @param  string $value The string to be looked for
     * @return VerbalExpressions
     */
    public function maybe($value) {
        return $this->add("(?:" . self::sanitize($value) . ")?");
    }

    /**
     * Anything
     *
     * Accept any string
     *
     * @access public
     * @return VerbalExpressions
     */
    public function anything() {
        return $this->add("(?:.*)");
    }

    /**
     * AnythingBut
     *
     * Anything but this chars
     *
     * @access public
     * @param  string $value The unaccepted chars
     * @return VerbalExpressions
     */
    public function anythingBut($value) {
        return $this->add("(?:[^" . self::sanitize($value) . "]*)");
    }

    /**
     * Something
     *
     * Accept any non-empty string
     *
     * @access public
     * @return VerbalExpressions
     */
    public function something() {
        return $this->add("(?:.+)");
    }

    /**
     * Anything but
     *
     * Anything non-empty except for these chars
     *
     * @access public
     * @param  string $value The unaccepted chars
     * @return VerbalExpressions
     */
    public function somethingBut($value) {
        return $this->add("(?:[^" . self::sanitize($value) . "]+)");
    }

    /**
     * Preg Replace
     *
     * Shorthand for preg_replace()
     *
     * @access public
     * @param  string $source the string that will be affected(subject)
     * @param  string $value  the replacement
     * @return VerbalExpressions
     */
    public function replace($source, $value) {
        // php doesn't have g modifier so we remove it if it's there and we remove limit param
        if (strpos($this->modifiers, 'g') !== false) {
            $this->modifiers = str_replace('g', '', $this->modifiers);
            return preg_replace($this->getRegex(), $value, $source);
        }
        return preg_replace($this->getRegex(), $value, $source, $this->replaceLimit);
    }

    /**
     * Line break
     *
     * Match line break
     *
     * @access public
     * @return VerbalExpressions
     */
    public function lineBreak() {
        return $this->add("(?:\\n|(\\r\\n))");
    }

    /**
     * Line break
     *
     * Shorthand for lineBreak
     *
     * @access public
     * @return VerbalExpressions
     */
    public function br() {
        return $this->lineBreak();
    }

    /**
     * Tabs
     *
     * Match tabs.
     *
     * @access public
     * @return VerbalExpressions
     */
    public function tab() {
        return $this->add("\\t");
    }

    /**
     * Alpha Numeric
     *
     * Match any alpha numeric
     *
     * @access public
     * @return VerbalExpressions
     */
    public function word() {
        return $this->add("\\w+");
    }

    /**
     * List Chars
     *
     * Any of the listed chars
     *
     * @access public
     * @param  string $value The chars looked for
     * @return VerbalExpressions
     */
    public function anyOf($value) {
        return $this->add("[" . $value . "]");
    }

    /**
     * Alias
     *
     * Shorthand for anyOf
     *
     * @access public
     * @param  string $value The chars looked for
     * @return VerbalExpressions
     */
    public function any($value) {
        return $this->anyOf($value);
    }

    /**
     * Add a range
     *
     * Adds a range to our expression ex: range(a,z) => a-z, range(a,z,0,9) => a-z0-9
     *
     * @access public
     * @return VerbalExpressions
     * @throws \InvalidArgumentException
     */
    public function range() {
        $arg_num = func_num_args();
        if ($arg_num % 2 != 0) {
            throw new \InvalidArgumentException("Number of args must be even", 1);
        }
        $value = "[";
        $arg_list = func_get_args();
        for ($i = 0; $i < $arg_num;) {
            $value .= self::sanitize($arg_list[$i++]) . "-" . self::sanitize($arg_list[$i++]);
        }
        $value .= "]";
        return $this->add($value);
    }

    /**
     * Add a modifier
     *
     * Adds a modifier
     *
     * @access public
     * @param  string $modifier
     * @return VerbalExpressions
     */
    public function addModifier($modifier) {
        if (strpos($this->modifiers, $modifier) === false) {
            $this->modifiers .= $modifier;
        }
        return $this;
    }

    /**
     * Remove Modifier
     *
     * Removes a modifier
     *
     * @access public
     * @param  string $modifier
     * @return VerbalExpressions
     */
    public function removeModifier($modifier) {
        $this->modifiers = str_replace($modifier, '', $modifier);
        return $this;
    }

    /**
     * Case Sensitivity
     *
     * Match case insensitive or sensitive based on $enable value
     *
     * @access public
     * @param  boolean $enable Enables or disables case sensitive. Default true
     * @return VerbalExpressions
     */
    public function withAnyCase($enable = true) {
        return $enable ? $this->addModifier('i') : $this->removeModifier('i');
    }

    /**
     * Stop At First
     *
     * Toggles g modifier
     *
     * @access public
     * @param  boolean $enable Enables or disables g modifier. Default true
     * @return VerbalExpressions
     */
    public function stopAtFirst($enable = true) {
        return $enable ? $this->addModifier('g') : $this->removeModifier('g');
    }

    /**
     * SearchOneLine
     *
     * Toggles m modifier
     *
     * @access public
     * @param  boolean $enable Enables or disables m modifier. Default true
     * @return VerbalExpressions
     */
    public function searchOneLine($enable = true) {
        return $enable ? $this->addModifier('m') : $this->removeModifier('m');
    }

    /**
     * Multiple
     *
     * Adds the multiple modifier at the end of your expression
     *
     * @access public
     * @param  string $value Your expression
     * @return VerbalExpressions
     */
    public function multiple($value) {
        $value = self::sanitize($value);
        switch (substr($value, -1)) {
            case '+':
            case '*':
                break;
            default:
                $value .= '+';
                break;
        }
        return $this->add($value);
    }

    /**
     * OR
     *
     * Wraps the current expression in an `or` with $value
     * Notice: OR is a reserved keyword in PHP, so this method is prefixed with "_"
     *
     * @access public
     * @param  string $value new expression
     * @return VerbalExpressions
     */
    public function _or($value) {
        if (strpos($this->prefixes, "(") === false) {
            $this->prefixes .= "(?:";
        }
        if (strpos($this->suffixes, ")") === false) {
            $this->suffixes .= ")";
        }
        $this->add(")|(?:");
        if ($value) {
            $this->add($value);
        }
        return $this;
    }

    /**
     * Object to string
     *
     * PHP Magic method to return a string representation of the object.
     *
     * @access public
     * @return string
     */
    public function __toString() {
        return $this->getRegex();
    }

    /**
     * Get the Expression
     *
     * Creates the final regex.
     *
     * @access public
     * @return string The final regex
     */
    public function getRegex() {
        return "/" . $this->prefixes . $this->source . $this->suffixes . "/" . $this->modifiers;
    }

    /**
     * Test
     *
     * tests the match of a string to the current regex
     *
     * @access public
     * @param  string  $value The string to be tested
     * @return boolean true if it's a match
     */
    public function test($value) {
        // php doesn't have g modifier so we remove it if it's there and call preg_match_all()
        if (strpos($this->modifiers, 'g') !== false) {
            $this->modifiers = str_replace('g', '', $this->modifiers);
            return preg_match_all($this->getRegex(), $value);
        }
        return (bool) preg_match($this->getRegex(), $value);
    }

    /**
     * Clean
     *
     * deletes the current regex for a fresh start
     *
     * @access public
     * @param  array $options
     * @return VerbalExpressions
     */
    public function clean(array $options = array()) {
        $options = array_merge(array("prefixes" => "", "source" => "", "suffixes" => "", "modifiers" => "gm", "replaceLimit" => "1"), $options);
        $this->prefixes = $options['prefixes'];
        $this->source = $options['source'];
        $this->suffixes = $options['suffixes'];
        $this->modifiers = $options['modifiers'];    // default to global multi line matching
        $this->replaceLimit = $options['replaceLimit']; // default to global multi line matching
        return $this;
    }

    /**
     * Limit
     *
     * Adds char limit to the last added expression.
     * If $max is less then $min the limit will be: At least $min chars {$min,}
     * If $max is 0 the limit will be: exactly $min chars {$min}
     * If $max bigger then $min the limit will be: at least $min but not more then $max {$min, $max}
     *
     * @access public
     * @param integer $min
     * @param integer $max
     * @return VerbalExpressions
     */
    public function limit($min, $max = 0) {
        if ($max == 0) {
            $value = "{" . $min . "}";
        } elseif ($max < $min) {
            $value = "{" . $min . ",}";
        } else {
            $value = "{" . $min . "," . $max . "}";
        }
        // check if the expression has * or + for the last expression
        if (preg_match("/\*|\+/", $this->lastAdded)) {
            $l = 1;
            $this->source = strrev(str_replace(array('+', '*'), strrev($value), strrev($this->source), $l));
            return $this;
        }
        return $this->add($value);
    }

}


<?php
/**
 * This source file is part of Xloit project.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the MIT License that is bundled with this package in the file LICENSE.
 * It is also available through the world-wide-web at this URL:
 * <http://www.opensource.org/licenses/mit-license.php>
 * If you did not receive a copy of the license and are unable to obtain it through the world-wide-web,
 * please send an email to <license@xloit.com> so we can send you a copy immediately.
 *
 * @license   MIT
 * @link      http://xloit.com
 * @copyright Copyright (c) 2016, Xloit. All rights reserved.
 */

namespace Xloit\Bridge\Zend\Form\View\Helper;

use Xloit\Bridge\Zend\Form\Element\CkEditor;
use Zend\Form\ElementInterface;
use Zend\Form\View\Helper\FormElement as ZendFormElement;

/**
 * A {@link FormElement} class.
 *
 * @package Xloit\Bridge\Zend\Form\View\Helper
 */
class FormElement extends ZendFormElement
{
    use HelperTrait;

    /**
     *
     *
     * @var array
     */
    protected $skippedElement = [
        'button',
        'submit'
    ];

    /**
     * Invoke helper as function. Proxies to {@link render()}.
     *
     * @param ElementInterface $element
     *
     * @return string|$this
     */
    public function __invoke(ElementInterface $element = null)
    {
        if (!$element) {
            return $this;
        }

        if (!in_array($element->getAttribute('type'), $this->skippedElement, true)) {
            $element = $this->addElementClass($element, ['form-control']);
        }

        return $this->render($element);
    }

    /**
     * Render an element.
     * Introspects the element type and attributes to determine which helper to utilize when rendering.
     *
     * @param ElementInterface $element
     *
     * @return string
     */
    public function render(ElementInterface $element)
    {
        $renderer = $this->getView();

        if ($element instanceof CkEditor) {
            /** @noinspection PhpUndefinedMethodInspection */
            $plugin = $renderer->plugin('form_ckeditor');

            return $plugin($element);
        }

        return parent::render($element);
    }
}


<?php

/**
 * Manage Form
 *
 * @category  	lib
 * @package		lib\Form
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
namespace Venus\lib\Form;

/**
 * This class manage the Form
 *
 * @category  	lib
 * @package		lib\Form
 * @author    	Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version   	Release: 1.0.0
 * @filesource	https://github.com/las93/venus2
 * @link      	https://github.com/las93
 * @since     	1.0
 */
class Select extends Common
{
	/**
	 * the name of element
	 *
	 * @access private
	 * @var    string
	 */
	private $_aOptions = null;

	/**
	 * the label of element
	 *
	 * @access private
	 * @var    string
	 */
	private $_sLabel = null;

	/**
	 * the value of element
	 *
	 * @access private
	 * @var    string
	 */
	private $_sValue = null;

	/**
	 * constructor that it increment (static) for all use
	 *
	 * @access public
	 * @param  string $sName name
	 * @param  array $aOptions options
	 * @param  string $sLabel label of input
	 * @param  string $sValue value of input
	 * @return \Venus\lib\Form\Input
	 */
	public function __construct(string $sName, array $aOptions, string $sLabel = null, string $sValue = null)
	{
		$this->setName($sName);
		$this->setOptions($aOptions);
		$this->setValue($sValue);
		$this->setLabel($sLabel);
	}

	/**
	 * get the Options
	 *
	 * @access public
	 * @return array
	 */
	public function getOptions() : array
	{
		return $this->_aOptions;
	}

	/**
	 * set the Options
	 *
	 * @access public
	 * @param  array $aOptions Options of input;
	 * @return Select
	 */
	public function setOptions(array $aOptions) : Select
	{
		$this->_aOptions = $aOptions;
		return $this;
	}

	/**
	 * get the Value
	 *
	 * @access public
	 * @return string
	 */
	public function getValue() : string
	{
		return $this->_sValue;
	}

	/**
	 * set the Value
	 *
	 * @access public
	 * @param  string $sValue Value of input;
	 * @return \Venus\lib\Form\Select
	 */
	public function setValue(string $sValue) : Select
	{
		$this->_sValue = $sValue;
		return $this;
	}

	/**
	 * get the Label
	 *
	 * @access public
	 * @return string
	 */
	public function getLabel() : string
	{
		return $this->_sLabel;
	}

	/**
	 * set the Label
	 *
	 * @access public
	 * @param  string $sLabel Label of input;
	 * @return \Venus\lib\Form\Select
	 */
	public function setLabel(string $sLabel) : Select
	{
		$this->_sLabel = $sLabel;
		return $this;
	}

	/**
	 * get the <html>
	 *
	 * @access public
	 * @return string
	 */
	public function fetch() : string
	{
		$sContent = '';

		if ($this->getLabel() !== null) { $sContent .= '<label>'.$this->getLabel().'</label> '; }

		$sContent .= '<select name="'.$this->getName().'" id="'.$this->getName().'">';

		foreach ($this->getOptions() as $sKey => $sValue) {

			$sContent .= '<option value="'.$sKey.'"';

			if ($this->getValue() == $sKey) { $sContent .= ' selected="selected"'; }

			$sContent .= '>'.$sValue.'</option>';
		}

		$sContent .= '</select> ';

		return $sContent;
	}
}


<?php

/**
 * Manage Image
 *
 * @category    lib
 * @author      Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright   Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license     https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version     Release: 1.0.0
 * @filesource  https://github.com/las93/venus2
 * @link        https://github.com/las93
 * @since       1.0
 */
namespace Venus\lib;

/**
 * This class manage the Image
 *
 * @category    lib
 * @author      Judicaël Paquet <judicael.paquet@gmail.com>
 * @copyright   Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
 * @license     https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
 * @version     Release: 1.0.0
 * @filesource  https://github.com/las93/venus2
 * @link        https://github.com/las93
 * @since       1.0
 */
class Image
{
	/**
	 * the translation language
	 * @var string
	 */
	private $_sLanguage = LANGUAGE;

    /**
     * set the language if you don't want take the default language of the configuration file
     *
     * @access public
     * @param int $iImageUri
     * @param  int $iWidth
     * @param  int $iHeight
     * @param bool $bKeepDimension
     * @return void
     */
	public static function showImageInSize(int $iImageUri, int $iWidth, int $iHeight, bool $bKeepDimension = false)
	{
	    $aSize = getimagesize($iImageUri);
	    $rActualImage = imagecreatefromjpeg($iImageUri);

	    $ImageChoisie = imagecreatefromjpeg($_FILES['ImageNews']['tmp_name']);
        $TailleImageChoisie = getimagesize($_FILES['ImageNews']['tmp_name']);

        $rNewImage = imagecreatetruecolor($iWidth , $iHeight);

        if ($bKeepDimension === false) {

            imagecopyresampled($rNewImage, $rActualImage, 0, 0, 0, 0, $iWidth, $iHeight, $aSize[0], $aSize[1]);
        }
        else {

            if ($aSize[0] > $aSize[1]) {

                $rWhite = imagecolorallocate($rNewImage, 255, 255, 255);
                imagefilledrectangle($rNewImage, 0, 0, $iWidth, $iHeight, $rWhite);
                $fCoef = $aSize[1] / $aSize[0];
                $iHeight = round($iWidth * $fCoef);
                $iDestY = round(($iWidth - $iHeight) / 2);
                $iDestX = 0;
            }
            else {

                $rWhite = imagecolorallocate($rNewImage, 255, 255, 255);
                imagefilledrectangle($rNewImage, 0, 0, $iWidth, $iHeight, $rWhite);
                $fCoef = $aSize[0] / $aSize[1];
                $iWidth = round($iHeight * $fCoef);
                $iDestX = round(($iHeight - $iWidth) / 2);
                $iDestY = 0;
            }

            $rWhite = imagecolorallocate($rNewImage, 255, 255, 255);
            imagefilledrectangle($rNewImage, 0, 0, $iWidth, $iHeight, $rWhite);
            imagecopyresampled($rNewImage, $rActualImage, $iDestX, $iDestY, 0, 0, $iWidth, $iHeight, $aSize[0], $aSize[1]);
        }

        imagedestroy($rActualImage);
        $NomImageChoisie = explode('.', $rNewImage);
        $NomImageExploitable = time();

        header('Content-Type: image/jpeg');
        imagejpeg($rNewImage , null, 100);
	}
}


<?php

namespace PeterColes\Cluster\HttpClients;

use PeterColes\Cluster\Contracts\HttpClientInterface;
use GuzzleHttp\Client;
use Exception;

class GuzzleHttp implements HttpClientInterface
{
    public $request;

    /**
     * Initialise Guzzle client using headers appropriate to adapter.
     *
     * @param array $headers
     * @return void
     */
    public function initClient($headers)
    {
        try {
            $this->request = new Client($headers);
        } catch (Exception $e) {
            echo 'Unable to initialise http client because '.$e->getMessage()."\n";
        }
    }

    /**
     * Get status code from http response.
     *
     * @param GuzzleResponse $response
     * @return integer
     */
    public function getStatus($response)
    {
        return (int) $response->getStatusCode();
    }

    /**
     * Get http response body, cast to json and decode.
     *
     * @param GuzzleHttp\Response object $response
     * @return array
     */
    public function getBody($response)
    {
        return json_decode((string) $response->getBody());
    }
}


<?php
namespace cascade\components\rest;

use Yii;
use yii\base\InvalidParamException;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;

/**
 * IndexAction [[@doctodo class_description:cascade\components\rest\IndexAction]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class IndexAction extends \yii\rest\IndexAction
{
    use ActionTrait;

    /**
     * @var [[@doctodo var_type:parentObject]] [[@doctodo var_description:parentObject]]
     */
    public $parentObject;
    /**
     * @var [[@doctodo var_type:_dataProvider]] [[@doctodo var_description:_dataProvider]]
     */
    protected $_dataProvider;

    /**
     * Get required params.
     *
     * @throws InvalidParamException [[@doctodo exception_description:InvalidParamException]]
     * @return [[@doctodo return_type:getRequiredParams]] [[@doctodo return_description:getRequiredParams]]
     *
     */
    public function getRequiredParams()
    {
        $requiredParams = parent::getRequiredParams();
        $modelClass = $this->modelClass;
        $objectType = (new $modelClass())->objectType;
        if (empty($objectType)) {
            throw new InvalidParamException($modelClass . ' does not have a corresponding object type');
        }
        if (!$objectType->hasDashboard) {
            $requiredParams[] = 'parentObject';
        }

        return $requiredParams;
    }

    /**
     * [[@doctodo method_description:params]].
     *
     * @return [[@doctodo return_type:params]] [[@doctodo return_description:params]]
     */
    public function params()
    {
        return ['parentObject'];
    }

    /**
     * @inheritdoc
     */
    protected function prepareDataProvider()
    {
        if (!isset($this->_dataProvider)) {
            $modelClass = $this->modelClass;
            $dummyModel = new $modelClass();
            $this->_dataProvider = $dataProvider = parent::prepareDataProvider();
            $this->_dataProvider->sort->attributes['descriptor'] = [
                'label' => 'Descriptor',
                'asc' => $dummyModel->getDescriptorDefaultOrder($dummyModel->tableName(), SORT_ASC),
                'desc' => $dummyModel->getDescriptorDefaultOrder($dummyModel->tableName(), SORT_DESC),
            ];
            $this->_dataProvider->sort->defaultOrder = ['descriptor' => SORT_ASC];
            $objectType = $dummyModel->objectType;
            $query = false;
            if (!empty(Yii::$app->request->queryParams['query'])) {
                $query = $dataProvider->query->buildContainsQuery(Yii::$app->request->queryParams['query']);
            } elseif (!empty(Yii::$app->request->queryParams['advancedQuery'])) {
                $query = json_decode(Yii::$app->request->queryParams['advancedQuery'], true);
            }
            $whereConditions = $dataProvider->query->andWhereFromQuery($query);
            if (empty($objectType)) {
                throw new InvalidParamException($modelClass . ' does not have a corresponding object type');
            }
            if (!isset($this->parentObject)) {
                $dataProvider->query->denyInherit();
            } else {
                $registryClass = Yii::$app->classes['Registry'];
                $parentObject = $registryClass::get($this->parentObject, false);
                if (!$parentObject) {
                    throw new NotFoundHttpException("Object not found: {$this->parentObject}");
                }
                if (!$parentObject->can('read')) {
                    throw new ForbiddenHttpException("Unable to access {$this->parentObject}");
                }
                $newQuery = $parentObject->queryChildObjects($this->modelClass);
                $this->_dataProvider->query = $newQuery;
            }
        }

        return $this->_dataProvider;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: xedin
 * Date: 1/10/2018
 * Time: 6:53 PM.
 */

namespace Dhii\Output;

use Dhii\Util\String\StringableInterface as Stringable;
use Exception as RootException;
use Dhii\Output\Exception\RendererException;

trait CreateRendererExceptionCapableTrait
{
    /**
     * Creates a new render-related exception.
     *
     * @since [*next-version*]
     *
     * @param string|Stringable|null $message  The error message, if any.
     * @param int|null               $code     The error code, if any.
     * @param RootException|null     $previous The inner exception for chaining, if any.
     * @param RendererInterface      $renderer The associated renderer, if any.
     *
     * @return RendererException The new exception.
     */
    protected function _createRendererException(
        $message = null,
        $code = null,
        RootException $previous = null,
        RendererInterface $renderer = null
    ) {
        return new RendererException($message, $code, $previous, $renderer);
    }
}


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

namespace cascade\components\web\form\fields;

use cascade\components\web\browser\Response as BrowserResponse;
use canis\helpers\Html;
use Yii;

/**
 * Relation [[@doctodo class_description:cascade\components\web\form\fields\Relation]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class Relation extends Base
{
    /**
     * @var [[@doctodo var_type:relationSettings]] [[@doctodo var_description:relationSettings]]
     */
    public $relationSettings = true;
    /**
     * @var [[@doctodo var_type:lockFields]] [[@doctodo var_description:lockFields]]
     */
    public $lockFields = [];
    /**
     * @var [[@doctodo var_type:inlineRelation]] [[@doctodo var_description:inlineRelation]]
     */
    public $inlineRelation = false;
    /**
     * @var [[@doctodo var_type:linkMultiple]] [[@doctodo var_description:linkMultiple]]
     */
    public $linkMultiple = false;

    /**
     * Get related object.
     *
     * @return [[@doctodo return_type:getRelatedObject]] [[@doctodo return_description:getRelatedObject]]
     */
    public function getRelatedObject()
    {
        return $this->modelField->value;
    }

    /**
     * [[@doctodo method_description:generate]].
     *
     * @return unknown
     */
    public function generate()
    {
        //$this->relatedObject->setParentModel($this->modelField->baseModel);
        if ($this->relationSettings) {
            $this->model->setParentModel($this->modelField->baseModel);
            // we are matching with an existing document
            $relationSettings = $this->relationSettings;
            if ($relationSettings === true) {
                $relationSettings = ['template' => 'simple'];
            }
            if (!is_array($relationSettings)) {
                $relationSettings = [];
            }
            if (!isset($relationSettings['template'])) {
                $relationSettings['template'] = 'hierarchy';
            }

            return $this->generateRelationField($relationSettings);
        } elseif ($this->inlineRelation) {
            //$this->model->setParentModel($this->modelField->baseModel, false);
            $this->model->setParentModel($this->relatedObject);
            // we are matching with an existing document
            return $this->generateRelationField(['template' => 'fields']);
        } elseif (!empty($this->relatedObject)) {
            $this->model->setParentModel($this->relatedObject);
            $formSegment = $this->relatedObject->objectType->getFormSegment($this->relatedObject, ['relationField' => $this->modelField]);
            $formSegment->owner = $this->owner;

            return $formSegment->generate();
        } else {
            return;
        }
    }

    /**
     * Get relation model field.
     *
     * @return [[@doctodo return_type:getRelationModelField]] [[@doctodo return_description:getRelationModelField]]
     */
    public function getRelationModelField()
    {
        $field = $this->model->tabularPrefix;
        if ($this->modelField->relationship->companionRole($this->modelField->modelRole) === 'child') {
            $field .= 'child_object_id';
        } else {
            $field .= 'parent_object_id';
        }

        return $field;
    }

    /**
     * [[@doctodo method_description:generateRelationField]].
     *
     * @param array $initialSettings [[@doctodo param_description:initialSettings]] [optional]
     *
     * @return [[@doctodo return_type:generateRelationField]] [[@doctodo return_description:generateRelationField]]
     */
    protected function generateRelationField($initialSettings = [])
    {
        $model = $this->model;
        $field = $this->getRelationModelField();
        $parts = [];
        $r = $initialSettings;
        $r['title'] = $this->modelField->label;
        $r['context'] = [];
        $r['selector'] = ['browse' => [], 'search' => ['data' => []]];
        if ($this->modelField->relationship->temporal && empty($this->model->start)) {
            $this->model->start = date("m/d/Y");
        }
        $r['context']['relationship'] = $this->modelField->relationship->package();
        if ($this->modelField->baseModel && !$this->modelField->baseModel->isNewRecord) {
            $r['context']['object'] = ['id' => $this->modelField->baseModel->primaryKey, 'descriptor' => $this->modelField->baseModel->descriptor];
        }
        $r['context']['role'] = $role = $this->modelField->relationship->companionRole($this->modelField->modelRole);
        $companionType = $this->modelField->relationship->companionRoleType($this->modelField->modelRole);
        $r['selector']['inputLabel'] = 'Select ' . $companionType->title->upperSingular;
        //\d($r);exit;

        if (($modelTypeItem = $this->modelField->relationship->{$role}->collectorItem)) {
            $typeBundle = BrowserResponse::handleInstructions(['handler' => 'types', 'relationshipRole' => $role, 'relationship' => $this->modelField->relationship->systemId, 'typeFilters' => ['hasDashboard']]);
            $r['selector']['browse']['root'] = $typeBundle->package();
        }
        $r['model'] = [
            'prefix' => $this->model->formName() . $this->model->tabularPrefix,
            'attributes' => array_merge($this->model->attributes, ['taxonomy_id' => $this->model->taxonomy_id]),
        ];
        if (!empty($this->modelField->value->primaryKey)) {
            $r['select'] = [
                'id' => $this->modelField->value->primaryKey,
                'descriptor' => $this->modelField->value->descriptor,
                'subdescriptor' => $this->modelField->value->primarySubdescriptor,
            ];
        }
        if (!empty($r['model']['attributes']['start'])) {
            $r['model']['attributes']['start'] = Yii::$app->formatter->asDate($r['model']['attributes']['start']);
        }
        if (!empty($r['model']['attributes']['end'])) {
            $r['model']['attributes']['end'] = Yii::$app->formatter->asDate($r['model']['attributes']['end']);
        }
        $r['lockFields'] = isset($this->relationSettings['lockFields']) ? array_merge($this->relationSettings['lockFields'], $this->lockFields) : $this->lockFields;
        $r['multiple'] = $this->linkMultiple; // && $this->modelField->relationship->multiple;
        $this->htmlOptions['data-relationship'] = json_encode($r, JSON_FORCE_OBJECT);
        Html::addCssClass($this->htmlOptions, 'relationship');
        //$model->_moduleHandler = $this->modelField->relationship->companionRole($this->modelField->modelRole) .':'. $this->modelField->relationship->companionRoleType($this->modelField->modelRole)->systemId;
        $parts[] = Html::activeHiddenInput($model, $this->model->tabularPrefix . '_moduleHandler');
        $parts[] = Html::activeHiddenInput($model, $field, $this->htmlOptions);

        return implode($parts);
    }

    /**
     * Gets the value of relationSettings.
     *
     * @return mixed
     */
    public function getLinkExisting()
    {
        return $this->relationSettings;
    }

    /**
     * Sets the value of relationSettings.
     *
     * @param mixed $relationSettings the link existing
     *
     * @return self
     */
    public function setLinkExisting($relationSettings)
    {
        $this->relationSettings = $relationSettings;

        return $this;
    }

    /**
     * Gets the value of linkMultiple.
     *
     * @return mixed
     */
    public function getLinkMultiple()
    {
        return $this->linkMultiple;
    }

    /**
     * Sets the value of linkMultiple.
     *
     * @param mixed $linkMultiple the link multiple
     *
     * @return self
     */
    public function setLinkMultiple($linkMultiple)
    {
        $this->linkMultiple = $linkMultiple;

        return $this;
    }
}


<?php namespace Ordercloud\Cart\Entities;

use Ordercloud\Cart\Entities\Policies\BaseCartPolicy;
use Ordercloud\Cart\Entities\Policies\CartPolicy;
use Ordercloud\Cart\Exceptions\CartItemNotFoundException;
use Ordercloud\Entities\Organisations\OrganisationShort;
use Ordercloud\Entities\Products\Product;

class Cart
{
    /** @var string */
    private $id;
    /** @var array|CartItem[] */
    private $items = [];
    /**
     * @var CartPolicy
     */
    private $policy;
    /** @var string */
    private $note = '';

    /**
     * @param string     $id
     * @param CartPolicy $policy
     */
    public function __construct($id, CartPolicy $policy = null)
    {
        $this->id = $id;
        $this->policy = is_null($policy) ? new BaseCartPolicy() : $policy;
    }

    /**
     * @param Product $product
     * @param int     $quantity
     * @param array   $options
     * @param array   $extras
     * @param string  $note
     */
    public function addItem(Product $product, $quantity = 1, array $options = [], array $extras = [], $note = null)
    {
        $item = new CartItem($product, $quantity, $options, $extras, $note);

        $this->items = $this->policy->add($item, $this->items);
    }

    /**
     * @param $itemPUID
     */
    public function removeItem($itemPUID)
    {
        $item = $this->getItemByPuid($itemPUID);

        $this->items = $this->policy->remove($item, $this->items);
    }

    /**
     * @param $itemPuid
     * @param $quantity
     */
    public function updateItemQuantity($itemPuid, $quantity)
    {
        if ($quantity <= 0) {
            $this->removeItem($itemPuid);
            return;
        }

        $originalItem = $this->getItemByPuid($itemPuid);
        $updatedItem = $this->getItemByPuid($itemPuid);

        $updatedItem->setQuantity($quantity);

        $this->items = $this->policy->update($originalItem, $updatedItem, $this->items);
    }

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

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

    /**
     * @return array|CartItem[]
     */
    public function getItems()
    {
        return $this->items;
    }

    /**
     * @param string $puid
     *
     * @return CartItem
     *
     * @throws CartItemNotFoundException
     */
    public function getItemByPuid($puid)
    {
        foreach ($this->getItems() as $item) {
            if ($item->getPuid() == $puid) {
                return $item;
            }
        }

        throw new CartItemNotFoundException($puid, $this);
    }

    /**
     * @return int
     */
    public function getItemCount()
    {
        $itemCount = 0;

        foreach ($this->getItems() as $item) {
            $itemCount += $item->getQuantity();
        }

        return $itemCount;
    }

    /**
     * @return bool
     */
    public function isEmpty()
    {
        return empty($this->items);
    }

    /**
     * @return float
     */
    public function getTotalAmount()
    {
        $amount = 0;

        foreach ($this->getItems() as $item) {
            $amount = bcadd($amount, $item->getAmount(), 2);
        }

        return floatval($amount);
    }

    /**
     * Check if there are any items in the cart from the specified merchant
     *
     * @param int $merchantId
     *
     * @return bool
     */
    public function isProductOfMerchantInCart($merchantId)
    {
        return in_array($merchantId, array_keys($this->getMerchantsOfProducts()));
    }

    /**
     * @return array|OrganisationShort[]
     */
    public function getMerchantsOfProducts()
    {
        $productMerchants = [];

        foreach ($this->getItems() as $item) {
            $organisation = $item->getProduct()->getOrganisation();

            $productMerchants[$organisation->getId()] = $organisation;
        }

        return $productMerchants;
    }

    /**
     * @param int $merchantID
     *
     * @return array
     */
    public function getItemsByMerchantID($merchantID)
    {
        return array_filter($this->getItems(), function(CartItem $item) use ($merchantID)
        {
            return $item->getProduct()->getOrganisation()->getId() == $merchantID;
        });
    }

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


<?php

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

namespace ItePHP\Structure;
use Pactum\ConfigBuilder;
use Pactum\ConfigBuilderObject;

/**
 * Structure for events.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class EventStructure implements Structure{

    /**
     * {@inheritdoc}
     */
	public function doConfig(ConfigBuilder $configBuilder){
        $configBuilder->addArray('event',new ConfigBuilderObject())->getValue()
            ->addString('class')
            ->addArray('method',new ConfigBuilderObject())->getValue()
            ->addString('name')
            ->addArray('argument',new ConfigBuilderObject())->getValue()
            ->addString('type')
            ->addString('value'); //FIXME change to addMixed

        $configBuilder->getArray('event')->getValue()
            ->addArray('bind',new ConfigBuilderObject())->getValue()
            ->addString('name')
            ->addString('method');
    }
}


<?php
namespace app\manage\controller;

use think\Url;
use think\Request;
use core\manage\logic\ConfigLogic;

class Config extends Base
{

    /**
     * 配置列表
     *
     * @param Request $request
     * @return string
     */
    public function index(Request $request)
    {
        $this->site_title = '配置列表';

        $map = [];
        $config_model = ConfigLogic::model();

        // 配置分组
        $group_name = $request->param('group', '');
        if (! empty($group_name)) {
            $map['config_group'] = $group_name;
        }
        $this->assign('group', $group_name);

        // total_count
        $total_count = $config_model->where($map)->count();
        $this->assign('total_count', $total_count);

        // list
        $list = $config_model->where($map)
            ->order('config_sort asc')
            ->paginate($this->rows_num);
        $this->assign('list', $list);
        $this->assign('page', $list->render());

        // group_list
        $group_list = $config_model->field('id, config_group')
            ->group('config_group')
            ->order('config_sort asc')
            ->select();
        $this->assign('group_list', $group_list);

        return $this->fetch();
    }

    /**
     * 添加配置
     *
     * @param Request $request
     * @return string
     */
    public function addConfig(Request $request)
    {
        $config_logic = ConfigLogic::instance();
        if ($request->isPost()) {
            $data = [
                'config_name' => $request->param('config_name'),
                'config_type' => $request->param('config_type'),
                'config_title' => $request->param('config_title'),
                'config_group' => $request->param('config_group'),
                'config_sort' => $request->param('config_sort', 0),
                'config_extra' => $request->param('config_extra'),
                'config_remark' => $request->param('config_remark')
            ];

            // 验证数据
            $res = $config_logic->validate->scene('add')->check($data);
            if (! $res) {
                return $this->error($config_logic->validate->getError());
            }
            $config_logic->addConfig($data);

            return $this->success('添加配置成功', Url::build('config/index'));
        } else {
            $this->site_title = '添加配置';

            $config_type = $config_logic->getConfigType();
            $this->assign('config_type', $config_type);

            return $this->fetch();
        }
    }

    /**
     * 编辑配置
     *
     * @param Request $request
     * @return string
     */
    public function editConfig(Request $request)
    {
        $config_id = $request->param('config_id');
        if (empty($config_id)) {
            return $this->error('配置ID为空');
        }

        $config_logic = ConfigLogic::instance();
        if ($request->isPost()) {
            $data = [
                'config_name' => $request->param('config_name'),
                'config_type' => $request->param('config_type'),
                'config_title' => $request->param('config_title'),
                'config_group' => $request->param('config_group'),
                'config_sort' => $request->param('config_sort', 0),
                'config_extra' => $request->param('config_extra'),
                'config_remark' => $request->param('config_remark')
            ];

            // 验证数据
            $res = $config_logic->validate->scene('edit')->check($data);
            if (! $res) {
                return $this->error($config_logic->validate->getError());
            }
            $config_logic->saveConfig($data, $config_id);

            return $this->success('修改配置成功', Url::build('config/index'));
        } else {
            $this->site_title = '编辑配置';
            $this->assign('config_id', $config_id);

            $config_type = $config_logic->getConfigType();
            $this->assign('config_type', $config_type);

            $config = $config_logic->model->get($config_id);
            $this->assign('config', $config);

            return $this->fetch();
        }
    }

    /**
     * 更改配置
     *
     * @param Request $request
     * @return mixed
     */
    public function modifyConfig(Request $request)
    {
        $id = $request->param('id');
        if (empty($id)) {
            return $this->error('ID为空');
        }

        $field_arr = [
            'config_group',
            'config_sort'
        ];
        $field = $request->param('field');
        if (! in_array($field, $field_arr)) {
            return $this->error('非法的字段');
        }

        $value = $request->param('value', '');
        ConfigLogic::model()->modify($id, $field, $value);

        return $this->success('更改成功', Url::build('config/index'));
    }

    /**
     * 删除配置
     *
     * @param Request $request
     * @return mixed
     */
    public function delConfig(Request $request)
    {
        $config_id = $request->param('config_id');
        if (empty($config_id)) {
            return $this->error('配置ID为空');
        }

        // 删除配置
        ConfigLogic::instance()->delConfig($config_id);

        return $this->success('删除配置成功');
    }

    /**
     * 网站设置
     *
     * @return string
     */
    public function setting()
    {
        $this->site_title = '网站设置';

        // 配置列表
        $list = ConfigLogic::instance()->getGroupList();
        $this->assign('list', $list);

        return $this->fetch();
    }

    /**
     * 保存设置
     *
     * @param Request $request
     * @return mixed
     */
    public function saveConfig(Request $request)
    {
        $config = $request->param('config/a', []);

        // 逐条保存
        $config_logic = ConfigLogic::instance();
        foreach ($config as $co => $vo) {
            $map = [
                'config_name' => $co
            ];
            $data = [
                'config_value' => is_array($vo) ? json_encode($vo, JSON_UNESCAPED_UNICODE) : $vo
            ];
            $config_logic->saveConfig($data, $map);
        }

        return $this->success('保存设置成功');
    }
}


<?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\Container\AbstractContainer;
use Es\Container\Countable\CountableTrait;
use Es\Container\Iterator\IteratorTrait;
use RuntimeException;

/**
 * The collection of modules.
 */
class Modules extends AbstractContainer implements ModulesInterface
{
    use CountableTrait, IteratorTrait;

    /**
     * Sets the module.
     *
     * @param string         $name   The module name
     * @param AbstractModule $module The instance of module class
     *
     * @return self
     */
    public function set($name, AbstractModule $module)
    {
        $this->container[(string) $name] = $module;

        return $this;
    }

    /**
     * Removes the module.
     *
     * @param string $name The module name
     *
     * @return self
     */
    public function remove($name)
    {
        if (isset($this->container[$name])) {
            unset($this->container[$name]);
        }

        return $this;
    }

    /**
     * Checks whether there is a module.
     *
     * @param string $name The module name
     *
     * @return bool Returns true on success, false otherwise
     */
    public function has($name)
    {
        return isset($this->container[$name]);
    }

    /**
     * Gets the module.
     *
     * @param string $name The module name
     *
     * @throws \RuntimeException If module is not found
     *
     * @return AbstractModule The module
     */
    public function get($name)
    {
        if (! isset($this->container[$name])) {
            throw new RuntimeException(
                sprintf(
                    'Module "%s" is not found',
                    $name
                )
            );
        }

        return $this->container[$name];
    }
}


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

namespace cascade\models;

use cascade\components\types\Relationship;
use canis\base\exceptions\Exception;
use yii\base\Model;

/**
 * DeleteForm [[@doctodo class_description:cascade\models\DeleteForm]]
 * LoginForm is the model behind the login form.
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class DeleteForm extends Model
{
    /**
     * @var [[@doctodo var_type:confirm]] [[@doctodo var_description:confirm]]
     */
    public $confirm = false;
    /**
     * @var [[@doctodo var_type:_target]] [[@doctodo var_description:_target]]
     */
    protected $_target;
    /**
     * @var [[@doctodo var_type:relationModel]] [[@doctodo var_description:relationModel]]
     */
    public $relationModel;
    /**
     * @var [[@doctodo var_type:relationshipWith]] [[@doctodo var_description:relationshipWith]]
     */
    public $relationshipWith;
    /**
     * @var [[@doctodo var_type:relationship]] [[@doctodo var_description:relationship]]
     */
    public $relationship;
    /**
     * @var [[@doctodo var_type:object]] [[@doctodo var_description:object]]
     */
    public $object;
    /**
     * @var [[@doctodo var_type:_possibleTargets]] [[@doctodo var_description:_possibleTargets]]
     */
    protected $_possibleTargets;

    /**
     * [[@doctodo method_description:rules]].
     *
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['confirm', 'target'], 'safe'],
        ];
    }

    /**
     * Get labels.
     *
     * @return [[@doctodo return_type:getLabels]] [[@doctodo return_description:getLabels]]
     */
    public function getLabels()
    {
        $labels = [];
        $labels['delete_object'] = [
            'short' => 'Delete ' . $this->object->objectType->title->getSingular(true),
            'long' => 'delete the ' . $this->object->objectType->title->getSingular(false) . ' ' . $this->object->descriptor . '',
            'past' => $this->object->objectType->title->getSingular(false) . ' ' . $this->object->descriptor . ' has been deleted',
            'options' => ['class' => 'btn-danger'],
            'response' => 'home',
        ];
        $labels['archive_object'] = [
            'short' => 'Archive ' . $this->object->objectType->title->getSingular(true),
            'long' => 'archive the ' . $this->object->objectType->title->getSingular(false) . ' ' . $this->object->descriptor . '',
            'past' => $this->object->objectType->title->getSingular(false) . ' ' . $this->object->descriptor . ' has been archived',
            'response' => 'refresh',
        ];
        $labels['unarchive_object'] = [
            'short' => 'Unarchive ' . $this->object->objectType->title->getSingular(true),
            'long' => 'unarchive the ' . $this->object->objectType->title->getSingular(false) . ' ' . $this->object->descriptor . '',
            'past' => $this->object->objectType->title->getSingular(false) . ' ' . $this->object->descriptor . ' has been unarchived',
            'response' => 'refresh',
        ];
        if (isset($this->relationshipWith)) {
            $labels['delete_relationship'] = [
                'short' => 'Delete Relationship',
                'long' => 'delete the relationship between ' . $this->object->descriptor . ' and ' . $this->relationshipWith->descriptor . '',
                'past' => 'the relationship between ' . $this->object->descriptor . ' and ' . $this->relationshipWith->descriptor . ' has been deleted',
                'options' => ['class' => 'btn-warning'],
            ];
            $labels['end_relationship'] = [
                'short' => 'End Relationship',
                'long' => 'end the relationship between ' . $this->object->descriptor . ' and ' . $this->relationshipWith->descriptor . '',
                'past' => 'the relationship between ' . $this->object->descriptor . ' and ' . $this->relationshipWith->descriptor . ' has been ended',
            ];
        }

        return $labels;
    }

    /**
     * Get target.
     *
     * @return [[@doctodo return_type:getTarget]] [[@doctodo return_description:getTarget]]
     */
    public function getTarget()
    {
        if (is_null($this->_target) && !empty($this->possibleTargets)) {
            $this->_target = $this->possibleTargets[0];
        }

        return $this->_target;
    }

    /**
     * [[@doctodo method_description:canDeleteObject]].
     *
     * @return [[@doctodo return_type:canDeleteObject]] [[@doctodo return_description:canDeleteObject]]
     */
    public function canDeleteObject()
    {
        if ($this->object->objectType->hasDashboard && isset($this->relationship) && !$this->relationship->isHasOne()) {
            return false;
        }

        return $this->object->can('delete');
    }

    /**
     * [[@doctodo method_description:canArchiveObject]].
     *
     * @return [[@doctodo return_type:canArchiveObject]] [[@doctodo return_description:canArchiveObject]]
     */
    public function canArchiveObject()
    {
        if ($this->object->objectType->hasDashboard && isset($this->relationship) && !$this->relationship->isHasOne()) {
            return false;
        }

        return $this->object->can('archive');
    }

    /**
     * [[@doctodo method_description:canDeleteRelation]].
     *
     * @return [[@doctodo return_type:canDeleteRelation]] [[@doctodo return_description:canDeleteRelation]]
     */
    public function canDeleteRelation()
    {
        if (isset($this->relationModel)) {
            if (!$this->object->allowRogue($this->relationModel)) {
                return false;
            }
            if (!$this->object->canDeleteAssociation($this->relationshipWith)) {
                return false;
            }

            return true;
        }

        return false;
    }

    /**
     * [[@doctodo method_description:canEndRelation]].
     *
     * @return [[@doctodo return_type:canEndRelation]] [[@doctodo return_description:canEndRelation]]
     */
    public function canEndRelation()
    {
        if (!isset($this->relationModel) || !isset($this->relationship)) {
            return false;
        }
        if (!$this->relationship->temporal) {
            return false;
        }
        if (!$this->object->canUpdateAssociation($this->relationshipWith)) {
            return false;
        }

        return true;
    }

    /**
     * [[@doctodo method_description:hasObjectTargets]].
     *
     * @return [[@doctodo return_type:hasObjectTargets]] [[@doctodo return_description:hasObjectTargets]]
     */
    public function hasObjectTargets()
    {
        foreach ($this->possibleTargets as $target) {
            if (in_array($target, ['delete_object', 'archive_object'])) {
                return true;
            }
        }

        return false;
    }

    /**
     * [[@doctodo method_description:hasRelationshipTargets]].
     *
     * @return [[@doctodo return_type:hasRelationshipTargets]] [[@doctodo return_description:hasRelationshipTargets]]
     */
    public function hasRelationshipTargets()
    {
        foreach ($this->possibleTargets as $target) {
            if (in_array($target, ['end_relationship', 'delete_relationship'])) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get possible targets.
     *
     * @return [[@doctodo return_type:getPossibleTargets]] [[@doctodo return_description:getPossibleTargets]]
     */
    public function getPossibleTargets()
    {
        if (is_null($this->_possibleTargets)) {
            $this->_possibleTargets = [];

            if ($this->canEndRelation()) {
                $this->_possibleTargets[] = 'end_relationship';
            }

            if ($this->canDeleteRelation()) {
                $this->_possibleTargets[] = 'delete_relationship';
            }

            if ($this->canArchiveObject()) {
                if ($this->object->archived) {
                    $this->_possibleTargets[] = 'unarchive_object';
                } else {
                    $this->_possibleTargets[] = 'archive_object';
                }
            }

            if ($this->canDeleteObject()) {
                $this->_possibleTargets[] = 'delete_object';
            }
        }

        return $this->_possibleTargets;
    }

    /**
     * Set target.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     *
     * @throws Exception [[@doctodo exception_description:Exception]]
     */
    public function setTarget($value)
    {
        if (in_array($value, $this->possibleTargets)) {
            $this->_target = $value;
        } else {
            throw new Exception('Unknown deletion target ' . $value);
        }
    }

    /**
     * Get target label.
     *
     * @return [[@doctodo return_type:getTargetLabel]] [[@doctodo return_description:getTargetLabel]]
     */
    public function getTargetLabel()
    {
        if (!isset($this->labels[$this->target])) {
            return ['long' => 'unknown', 'short' => 'unknown'];
        }

        return $this->labels[$this->target];
    }

    /**
     * Get target descriptor.
     *
     * @return [[@doctodo return_type:getTargetDescriptor]] [[@doctodo return_description:getTargetDescriptor]]
     */
    public function getTargetDescriptor()
    {
        if ($this->target === 'object') {
            return $this->object->descriptor;
        } else {
            return 'relationship';
        }
    }

    /**
     * [[@doctodo method_description:handle]].
     *
     * @return [[@doctodo return_type:handle]] [[@doctodo return_description:handle]]
     */
    public function handle()
    {
        $result = false;
        switch ($this->target) {
            case 'delete_object':
                $result = true;
                if (!is_null($this->relationModel)) {
                    $result = $this->relationModel->suppressAudit()->delete();
                }
                $result = $result && $this->object->delete();
            break;
            case 'archive_object':
                $result = $this->object->archive();
            break;
            case 'unarchive_object':
                $result = $this->object->unarchive();
            break;
            case 'delete_relationship':
                $result = $this->relationModel->delete();
            break;
            case 'end_relationship':
                $result = $this->relationModel->endRelationship();
            break;
        }

        return $result;
    }
}


<?php

namespace Onsigbaar\Components\Commands;

use Illuminate\Console\Command;
use Onsigbaar\Components\Migrations\Migrator;
use Onsigbaar\Components\Module;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class MigrateCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'component:migrate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migrate the migrations from the specified module or from all modules.';

    /**
     * @var \Onsigbaar\Components\Contracts\RepositoryInterface
     */
    protected $module;

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->module = $this->laravel['modules'];

        $name = $this->argument('module');

        if ($name) {
            $module = $this->module->findOrFail($name);

            return $this->migrate($module);
        }

        foreach ($this->module->getOrdered($this->option('direction')) as $module) {
            $this->line('Running for component: <info>' . $module->getName() . '</info>');

            $this->migrate($module);
        }
    }

    /**
     * Run the migration from the specified module.
     *
     * @param Module $module
     */
    protected function migrate(Module $module)
    {
        $path = str_replace(base_path(), '', (new Migrator($module))->getPath());

        if ($this->option('subpath')) {
            $path = $path . "/" . $this->option("subpath");
        }

        $this->call('migrate', [
            '--path' => $path,
            '--database' => $this->option('database'),
            '--pretend' => $this->option('pretend'),
            '--force' => $this->option('force'),
        ]);

        if ($this->option('seed')) {
            $this->call('component:seed', ['module' => $module->getName()]);
        }
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['module', InputArgument::OPTIONAL, 'The name of module will be used.'],
        ];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['direction', 'd', InputOption::VALUE_OPTIONAL, 'The direction of ordering.', 'asc'],
            ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use.'],
            ['pretend', null, InputOption::VALUE_NONE, 'Dump the SQL queries that would be run.'],
            ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'],
            ['seed', null, InputOption::VALUE_NONE, 'Indicates if the seed task should be re-run.'],
            ['subpath', null, InputOption::VALUE_OPTIONAL, 'Indicate a subpath to run your migrations from'],
        ];
    }
}