<?php

declare(strict_types = 1);

namespace OctoLab\Kilex\ServiceProvider;

use OctoLab\Common\Monolog\Service\ComponentFactory;
use OctoLab\Common\Monolog\Service\Locator;
use Symfony\Bridge\Monolog\Handler\ConsoleHandler;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * @author Kamil Samigullin <kamil@samigullin.info>
 */
class MonologServiceProvider
{
    /**
     * @param \Pimple $app
     *
     * @throws \InvalidArgumentException
     *
     * @api
     */
    public function setup(\Pimple $app)
    {
        $config = $app['config'];
        \assert('$config instanceof \OctoLab\Common\Config\SimpleConfig');
        $app['loggers'] = $app::share(function (\Pimple $app) use ($config) : Locator {
            return new Locator($config['monolog'], $app['monolog.component_factory'], $app['app.name']);
        });
        $app['logger'] = $app::share(function (\Pimple $app) : \Monolog\Logger {
            return $app['loggers']->getDefaultChannel();
        });
        $app['monolog.bridge'] = $app::share(function (\Pimple $app) : callable {
            return $this->getBridge($app);
        });
        $app['monolog.component_factory'] = $app::share(function () : ComponentFactory {
            return ComponentFactory::withDefaults();
        });
    }

    /**
     * @param \Pimple $app
     *
     * @return callable
     */
    private function getBridge(\Pimple $app): callable
    {
        return function (OutputInterface $output) use ($app) {
            if (class_exists('Symfony\Bridge\Monolog\Handler\ConsoleHandler')
                && interface_exists('Symfony\Component\EventDispatcher\EventSubscriberInterface')) {
                $consoleHandler = new ConsoleHandler($output);
                /** @var \Monolog\Logger $logger */
                foreach ($app['loggers'] as $logger) {
                    $logger->pushHandler($consoleHandler);
                }
            }
        };
    }
}


<?php

namespace Chill\CustomFieldsBundle\DependencyInjection;

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

/**
 * This is the class that validates and merges configuration from
 * your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('chill_custom_fields');

        $classInfo = "The class which may receive custom fields";
        $nameInfo = "The name which will appears in the user interface. May be translatable";
        $optionsInfo = "Options available for custom fields groups referencing this class";
        $optionsFormType = "The name of the form to append";
        $optionsFormOptionsInfos = "the arguments to pass the form";
        $customizableEntitiesInfo = "A list of customizable entities";

        $rootNode
            ->children()
                ->arrayNode('customizables_entities')
                    ->info($customizableEntitiesInfo)
                    ->defaultValue(array())
                    ->prototype('array')
                    ->children()
                        ->scalarNode('class')->isRequired()->info($classInfo)
                        ->end()
                        ->scalarNode('name') ->isRequired()->info($nameInfo)
                        ->end()
                        ->arrayNode('options')
                            ->info($optionsInfo)
                            ->defaultValue(array())
                            ->useAttributeAsKey('key')
                            ->prototype('array')
                                ->children()
                                    ->scalarNode('form_type')
                                        ->isRequired()
                                        ->info($optionsFormType)
                                    ->end()
                                    ->variableNode('form_options')
                                        ->info($optionsFormOptionsInfos)
                                        ->defaultValue(array())
                                    ->end()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
            ->booleanNode('show_empty_values_in_views')
                ->info('Show the empty value for custom fields in the views, timeline, ...')
                ->defaultValue(true)
            ->end()
        ->end()
        ;

        return $treeBuilder;
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Repository\RepositoryTrait;

use OpenOrchestra\ModelInterface\Model\StatusInterface;
/**
 * Trait AutoPublishableTrait
 */
trait AutoPublishableTrait
{
    /**
     * Find all element (in all versions and all languages) ready to be auto-published
     *
     * @param string $siteId
     * @param array  $fromStatus
     *
     * @return array
     */
    public function findElementToAutoPublish($siteId, array $fromStatus)
    {
        $date = new \Mongodate(strtotime(date('d F Y')));

        $statusIds = array();
        foreach($fromStatus as $status) {
            $statusIds[] = new \MongoId($status->getId());
        }

        $qa = $this->createAggregationQuery();

        $filter = array(
            'siteId' => $siteId,
            'deleted' => false,
            'status._id' => array('$in' => $statusIds),
            'status.outOfWorkflow' => false,
            'publishDate' => array('$lte' => $date),
            '$or' => array(
                array('unpublishDate' => array('$exists' => false)),
                array('unpublishDate' => array('$gte' => $date))
            )
        );

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

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

    /**
     * Find all elements (in all versions and all langauges) ready to be auto-unpublished
     *
     * @param string          $siteId
     * @param StatusInterface $publishedStatus
     *
     * @return array
     */
    public function findElementToAutoUnpublish($siteId, StatusInterface $publishedStatus)
    {
        $date = new \Mongodate(strtotime(date('d F Y')));
        $statusId = new \MongoId($publishedStatus->getId());

        $qa = $this->createAggregationQuery();

        $filter = array(
            'siteId' => $siteId,
            'deleted' => false,
            'status._id' => $statusId,
            'status.outOfWorkflow' => false,
            'unpublishDate' => array('$lte' => $date)
        );

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

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


<?php
/**
 * FratilyPHP Framework Bundle
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.
 * Redistributions of files must retain the above copyright notice.
 *
 * @author      Kento Oka <kento-oka@kentoka.com>
 * @copyright   (c) Kento Oka
 * @license     MIT
 * @since       1.0.0
 */
namespace Fratily\Bundle\Twig\Container;

use Fratily\Container\Builder\AbstractContainer;
use Fratily\Container\Builder\ContainerBuilder;

class TwigContainer extends AbstractContainer{

    /**
     * {@inheritdoc}
     */
    public static function build(ContainerBuilder $builder, array $options){
        $builder
            ->add(
                "twig",
                \Twig_Environment::class,
                [],
                [
                    \Twig\Environment::class,
                    \Twig_Environment::class,
                ]
            )
            ->add(
                "twig.loader",
                \Twig_Loader_Chain::class,
                [],
                [
                    \Twig\Loader\LoaderInterface::class,
                    \Twig_LoaderInterface::class,
                ]
            )
        ;

        $builder->parameter(\Twig_Environment::class)
            ->add("loader", $builder->lazyGet("twig.loader"))
        ;

        $builder->parameter(\Twig_Loader_Chain::class)
            ->add(
                "options",
                $builder->lazyArray([
                    "debug" => $builder->LazyGetShareValue("kernel.debug"),
                    "cache" => $builder->LazyGetShareValue("twig.cache"),
                ])
            )
        ;

        $builder->addShareValue(
            "twig.cache",
            $builder->lazyCallable(
                function($kernel){
                    return
                        $kernel->getConfig()->getProjectDir()
                        . implode(DIRECTORY_SEPARATOR, ["", "var", "twig"])
                    ;
                },
                [$builder->lazyGet("kernel")]
            )
        );
    }

    public static function modify(\Fratily\Container\Container $container){
        $loader = $container->get("twig.loader");

        foreach($container->getTagged("twig.loader") as $subLoader){
            $loader->addLoader($subLoader);
        }
    }
}


<?php
/*
 * Copyright 2016 CampaignChain, Inc. <info@campaignchain.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace CampaignChain\Hook\DueBundle\EntityService;

use CampaignChain\CoreBundle\Entity\Hook;
use CampaignChain\CoreBundle\EntityService\HookServiceTriggerInterface;
use CampaignChain\Hook\DueBundle\Entity\Due;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\Common\Inflector\Inflector;
use Symfony\Component\DependencyInjection\ContainerInterface;

class DueService extends HookServiceTriggerInterface
{
//    public function newObject($entityClass, $entityId, $formData){
//        $due = new Due();
//        $due->setEntityId($entityId);
//        $due->setEntityClass($entityClass);
//        $due->setDate($formData['date']);
//
//        return $due;
//    }

    public function getHook($entity, $mode = Hook::MODE_DEFAULT){
        $hook = new Due();

        if(
            is_object($entity) &&
            $entity->getId() !== null
        ){
            if(
                $mode == Hook::MODE_DEFAULT &&
                // Operations have no direct relation to a campaign, so exclude them.
                strpos(get_class($entity), 'CoreBundle\Entity\Operation') === false &&
                // Don't process Campaigns here.
                strpos(get_class($entity), 'CoreBundle\Entity\Campaign') === false &&
                // Check if the Action's campaign has relative dates.
                $entity->getCampaign()->getHasRelativeDates()
            ){
                $interval = $entity->getCampaign()->getStartDate()->diff(
                    $entity->getStartDate()
                );
                $time = $entity->getStartDate()->format('H').':'.$entity->getStartDate()->format('i');
                $days = $interval->format("%a");
                if($time != '00:00'){
                    $days = ++$days;
                }
                $hook->setDays($days);
                $hook->setTime($time);
            }

            $hook->setStartDate($entity->getStartDate());
        }

        return $hook;
    }

    public function processHook($entity, $hook){
        // TODO: Remove this hack which fixes a validation issue.
        if(!$hook->getStartDate()){
            $now = new \DateTime('now', new \DateTimeZone($hook->getTimezone()));
            $hook->setStartDate($now);
        }

        if($hook->getDays()){
            $campaignStartDate = $entity->getCampaign()->getStartDate();
            $days = $hook->getDays();
            if($hook->getTime() != '00:00'){
                $days = $days-1;
            }
            $hookStartDate = $campaignStartDate->modify('+'.$days.' days');
            $hookStartDate = new \DateTime(
                $hookStartDate->format('Y-M-d').' '.$hook->getTime().':00',
                new \DateTimeZone($hook->getTimezone())
            );

            $hook->setStartDate($hookStartDate);
        }

        // Update the dates of the entity.
        $entity->setStartDate($hook->getStartDate());
        $entity->setEndDate($hook->getEndDate());

        // If the entity is an Activity and it equals the Operation, then
        // - the same dates will be set for the Operation
        // - the same trigger Hook will be set for the Operation
        $class = get_class($entity);
        if(strpos($class, 'CoreBundle\Entity\Activity') !== false && $entity->getEqualsOperation() == true){
            $operation = $entity->getOperations()[0];
            if(is_object($operation)){
                $operation->setStartDate($hook->getStartDate());
                $operation->setEndDate($hook->getEndDate());
                $operation->setTriggerHook($entity->getTriggerHook());
            } else {
                throw new \Exception(
                    'The Activity with ID "'.$entity->getId().'" '
                    .'does not have a related Operation, although the module '
                    .'"'.$entity->getActivityModule()->getIdentifier().'" '
                    .'of bundle '
                    .'"'.$entity->getActivityModule()->getBundle()->getName().'" '
                    .'is configured so that the Activity equals the Operation.'
                );
            }
        }

        $this->setEntity($entity);

        return true;
    }

    public function arrayToObject($hookData){
        if(is_array($hookData) && count($hookData)){
            $datetimeUtil = $this->container->get('campaignchain.core.util.datetime');

            // Intercept if due date is supposed to be "now".
            if(isset($hookData['execution_choice'])){
                if($hookData['execution_choice'] == 'now'){
                    $nowDate = new \DateTime('now');
                    $hookData['date'] = $datetimeUtil->formatLocale($nowDate);
                }
                unset($hookData['execution_choice']);
            }

            $hook = new Due();
            foreach($hookData as $property => $value){
                // TODO: Research whether this is a security risk, e.g. if the property name has been injected via a REST post.
                $method = 'set'.Inflector::classify($property);
                if($method == 'setDate' && !is_object($value) && !$value instanceof \DateTime){
                    // TODO: De-localize the value and change from user format to ISO8601.
                    $value = new \DateTime($value, new \DateTimeZone($hookData['timezone']));
                }
                $hook->$method($value);
            }
        }

        return $hook;
    }

    public function tplInline($entity){
        $hook = $this->getHook($entity);
        return $this->container->get('templating')->render(
            'CampaignChainHookDueBundle::inline.html.twig',
            array(
                'hook' => $hook,
                'campaign_has_relative_dates' => $entity->getCampaign()->getHasRelativeDates(),
            )
        );
    }

    /**
     * Returns the corresponding start date field attribute name as specified in the respective form type.
     *
     * @return string
     */
    public function getStartDateIdentifier(){
        return 'date';
    }

    /**
     * Returns the corresponding end date field attribute name as specified in the respective form type.
     *
     * @return string
     */
    public function getEndDateIdentifier(){
        return 'date';
    }
}


<?php
/**
 * Таблица статей
 *
 * @version ${product.version}
 *
 * @copyright 2013, ООО "Два слона", http://dvaslona.ru/
 * @license http://www.gnu.org/licenses/gpl.txt	GPL License 3
 * @author Михаил Красильников <mk@dvaslona.ru>
 *
 * Данная программа является свободным программным обеспечением. Вы
 * вправе распространять ее и/или модифицировать в соответствии с
 * условиями версии 3 либо (по вашему выбору) с условиями более поздней
 * версии Стандартной Общественной Лицензии GNU, опубликованной Free
 * Software Foundation.
 *
 * Мы распространяем эту программу в надежде на то, что она будет вам
 * полезной, однако НЕ ПРЕДОСТАВЛЯЕМ НА НЕЕ НИКАКИХ ГАРАНТИЙ, в том
 * числе ГАРАНТИИ ТОВАРНОГО СОСТОЯНИЯ ПРИ ПРОДАЖЕ и ПРИГОДНОСТИ ДЛЯ
 * ИСПОЛЬЗОВАНИЯ В КОНКРЕТНЫХ ЦЕЛЯХ. Для получения более подробной
 * информации ознакомьтесь со Стандартной Общественной Лицензией GNU.
 *
 * Вы должны были получить копию Стандартной Общественной Лицензии
 * GNU с этой программой. Если Вы ее не получили, смотрите документ на
 * <http://www.gnu.org/licenses/>
 */

/**
 * Таблица статей
 *
 * @since 3.01
 */
class Articles_Entity_Table_Article extends ORM_Table
{
    /**
     * Описание таблицы
     * @since 3.01
     */
    protected function setTableDefinition()
    {
        $this->setTableName('articles');
        $this->hasColumns(array(
            'id' => array(
                'type' => 'integer',
                'unsigned' => true,
                'autoincrement' => true,
            ),
            'section' => array(
                'type' => 'integer',
                'unsigned' => true,
            ),
            'active' => array(
                'type' => 'boolean',
            ),
            'position' => array(
                'type' => 'integer',
                'unsigned' => true,
            ),
            'posted' => array(
                'type' => 'datetime',
            ),
            'block' => array(
                'type' => 'boolean',
                'default' => false,
            ),
            'caption' => array(
                'type' => 'string',
                'length' => 255,
            ),
            'preview' => array(
                'type' => 'string',
            ),
            'text' => array(
                'type' => 'string',
            )
        ));
        $this->setOrdering($this->getPlugin()->settings['listSortMode'],
            $this->getPlugin()->settings['listSortDesc']
                ? ezcQuerySelect::DESC
                : ezcQuerySelect::ASC);
        $this->index('admin_idx', array('fields' => array('section', 'position')));
        $this->index('cl_position_idx', array('fields' => array('section', 'active', 'position')));
        $this->index('cl_date_idx', array('fields' => array('section', 'active', 'posted')));
        $this->index('cl_block_idx', array('fields' => array('block', 'active')));
    }

    /**
     * Возвращает список статей в указанном разделе
     *
     * @param int  $sectionId  идентификатор раздела
     * @param int  $limit      ограничение на количество возвращаемых статей
     * @param int  $offset     пропустить указанное количество статей
     * @param bool $inactive   выводить неактивные объекты (true) или только активные (false)
     *
     * @return array
     *
     * @since 3.01
     */
    public function findInSection($sectionId, $limit = null, $offset = 0, $inactive = false)
    {
        $q = $this->createSelectQuery();
        $where = array();
        $where []= $q->expr->eq('section', $q->bindValue($sectionId, null, PDO::PARAM_INT));
        if (true !== $inactive)
        {
            $where []= $q->expr->eq('active', $q->bindValue(true, null, PDO::PARAM_INT));
        }
        $q->where($q->expr->lAnd($where));
        return $this->loadFromQuery($q, $limit, $offset);
    }

    /**
     * Возвращает количество статей в указанном разделе
     *
     * @param int  $sectionId  идентификатор раздела
     * @param bool $inactive   учитывать неактивные объекты (true) или только активные (false)
     *
     * @return int
     *
     * @since 3.01
     */
    public function countInSection($sectionId, $inactive = false)
    {
        $q = $this->createCountQuery();
        $where = array();
        $where []= $q->expr->eq('section', $q->bindValue($sectionId, null, PDO::PARAM_INT));
        if (true !== $inactive)
        {
            $where []= $q->expr->eq('active', $q->bindValue(true, null, PDO::PARAM_INT));
        }
        $q->where($q->expr->lAnd($where));
        return $this->count($q);
    }
}


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

namespace RedKiteCms\Content\BlockManager;

use RedKiteCms\Bridge\Dispatcher\Dispatcher;
use RedKiteCms\Bridge\Monolog\DataLogger;
use RedKiteCms\Content\Block\BlockFactory;
use RedKiteCms\EventSystem\BlockEvents;
use RedKiteCms\EventSystem\Event\Block\BlockEditedEvent;
use RedKiteCms\EventSystem\Event\Block\BlockEditingEvent;
use RedKiteCms\Tools\FilesystemTools;
use RedKiteCms\Tools\JsonTools;
use RedKiteCms\Tools\Utils;

/**
 * Class BlockManagerEdit is the object assigned to edit a block
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\BlockManager
 */
class BlockManagerEdit extends BlockManager
{
    /**
     * Edits the given block
     *
     * @param string $sourceDir
     * @param array $options
     * @param string $username
     * @param array $values
     */
    public function edit($sourceDir, array $options, $username, $values)
    {
        $this->resolveOptions($options);
        $this->init($sourceDir, $options, $username);
        $this->createContributorDir($sourceDir, $options, $username);

        $filename = sprintf('%s/blocks/%s.json', $this->getDirInUse(), $options["blockname"]);
        $currentBlock = $options["baseBlock"] = JsonTools::jsonDecode(FilesystemTools::readFile($filename));

        $values = $this->parseChildren($values);

        $block = JsonTools::join($currentBlock, $values);
        $encodedBlock = json_encode($block);

        $blockClass = BlockFactory::getBlockClass($block["type"]);
        $event = Dispatcher::dispatch(
            BlockEvents::BLOCK_EDITING,
            new BlockEditingEvent($this->serializer, $filename, $encodedBlock, $blockClass)
        );
        $blockContent = $event->getFileContent();

        FilesystemTools::writeFile($filename, $blockContent);

        Dispatcher::dispatch(
            BlockEvents::BLOCK_EDITED,
            new BlockEditedEvent($this->serializer, $filename, $encodedBlock, $blockClass)
        );
        DataLogger::log(
            sprintf(
                'Block "%s" has been edited on the "%s" slot on page "%s" for the "%s_%s" language',
                $options["blockname"],
                $options["slot"],
                $options["page"],
                $options["language"],
                $options["country"]
            )
        );
    }

    private function parseChildren($json)
    {
        $values = json_decode($json, true);
        if (!array_key_exists("children", $values)) {
            return $json;
        }

        $children = $values["children"];
        $values["children"] = $this->doParseChildren($children);

        return json_encode($values);
    }

    private function doParseChildren(array $children)
    {
        $parsedChildren = array();
        foreach ($children as $child) {
            if (!array_key_exists("type", $child)) {
                // @codeCoverageIgnoreStart
                continue;
                // @codeCoverageIgnoreEnd
            }

            $block = BlockFactory::createBlock($child["type"]);
            $encodedBlock = $this->serializer->serialize($block, 'json');

            $updatedBlock = JsonTools::join($encodedBlock, $child);
            $block = $this->serializer->deserialize(json_encode($updatedBlock), get_class($block), 'json');
            $block->updateSource();

            $children = json_decode($this->serializer->serialize($block, 'json'), true);

            if (array_key_exists("children", $children)) {
                $children["children"] = $this->doParseChildren($children["children"]);
            }
            $parsedChildren[] = $children;
        }

        return $parsedChildren;
    }

}


<?php

/*
 * Copyright (c) 2013, Flaming Code
 *
 */

namespace FlamingBase\Form\Element;

use Zend\Form\Element\DateTime as ZendDateTime;

use DateTime;

/**
 * DateTime
 *
 * @author Flemming Andersen <flemming@flamingcode.com>
 * @copyright (c) 2013, Flaming Code
 * @link https://github.com/FlamingCode/FlamingBase for the canonical source repository
 * @license http://opensource.org/licenses/MIT MIT
 */
class DateTimePicker extends ZendDateTime
{
	/**
	 * Seed attributes
	 *
	 * @var array
	 */
	protected $attributes = array(
		'type' => 'text',
		'class' => 'datetimepicker'
	);

	/**
	 * Provide default input rules for this element
	 *
	 * Attaches default validators for the datetime input.
	 *
	 * @return array
	 */
	public function getInputSpecification()
	{
		$datetimeElement = $this;

		return array(
			'name' => $this->getName(),
			'required' => true,
			'filters' => array(
				array('name' => 'Zend\Filter\StringTrim'),
				array(
					'name' => 'Callback',
					'options' => array(
						'callback' => function ($value) use ($datetimeElement) {
							if (!empty($value) && is_string($value)) {
								return DateTime::createFromFormat($datetimeElement->getFormat(), $value);
							}
							return $value;
						}
					)
				)
			),
			'validators' => $this->getValidators(),
		);
	}
}


<?php
namespace HtSettingsModule\Options;

use Zend\Stdlib\AbstractOptions;
use HtSettingsModule\Exception;

class ModuleOptions extends AbstractOptions implements ModuleOptionsInterface, DbOptionsInterface, StorageOptionsInterface
{
    /**
     * @var CacheOptionsInterface
     */
    protected $cacheOptions;

    /**
     * @var array
     */
    protected $namespaces = [];

    /**
     * @var string|\Zend\Db\Sql\TableIdentifier
     */
    protected $settingsTable = 'settings';

    /**
     * @var string
     */
    protected $parameterEntityClass = 'HtSettingsModule\Entity\Parameter';

    /**
     * @var string  Path to store settings if we want to store settings in xml, json etc.
     */
    protected $storagePath = 'data/settings';

    /**
     * Sets options of cache
     *
     * @param  array|CacheOptionsInterface $cacheOptions
     * @return self
     */
    public function setCacheOptions($cacheOptions)
    {
        if ($cacheOptions instanceof CacheOptionsInterface) {
            $this->cacheOptions = $cacheOptions;
        } elseif (is_array($cacheOptions)) {
            $this->cacheOptions = new CacheOptions($cacheOptions);
        } else {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    '%s expects parameter 1 to be array or an instance of HtSettingsModule\Options\CacheOptionsInterface, %s provided instead',
                    __METHOD__,
                    is_object($cacheOptions) ? get_class($cacheOptions) : gettype($cacheOptions)
                )
            );
        }

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getCacheOptions()
    {
        if (!$this->cacheOptions instanceof CacheOptionsInterface) {
            $this->cacheOptions = new CacheOptions;
        }

        return $this->cacheOptions;
    }

    /**
     * Sets namespaces
     *
     * @param  array $namespaces
     * @return void
     */
    public function setNamespaces(array $namespaces)
    {
        $this->namespaces = [];
        foreach ($namespaces as $namespace => $namespaceOptions) {
            $this->addNamespace($namespaceOptions, $namespace);
        }
    }

    /**
     * Adds new namespace
     *
     * @param  array|NamespaceOptionsInterface $namespaceOptions
     * @param  string|null                     $namespace
     * @return void
     */
    public function addNamespace($namespaceOptions, $namespace = null)
    {
        if (!$namespaceOptions instanceof NamespaceOptionsInterface) {
            if (is_array($namespaceOptions)) {
                $namespaceOptions = new NamespaceOptions($namespaceOptions);
                if ($namespace !== null) {
                    $namespaceOptions->setName($namespace);
                }
            } else {
                 throw new Exception\InvalidArgumentException(
                    sprintf(
                        '%s expects parameter 1 to be array or an instance of HtSettingsModule\Options\NamespaceOptionsInterface, %s provided instead',
                        __METHOD__,
                        is_object($namespaceOptions) ? get_class($namespaceOptions) : gettype($namespaceOptions)
                    )
                );
            }
        } else {
            if (!$namespaceOptions->getName() && $namespace) {
                $namespaceOptions->setName($namespace);
            }
        }
        if ($namespace === null) {
            $namespace = $namespaceOptions->getName();
        }
        $this->namespaces[$namespace] = $namespaceOptions;
    }

    /**
     * {@inheritDoc}
     */
    public function getNamespaces()
    {
        return $this->namespaces;
    }

    /**
     * {@inheritDoc}
     */
    public function getNamespaceOptions($namespace)
    {
        if (!isset($this->namespaces[$namespace])) {
            throw new Exception\InvalidArgumentException(
                sprintf('Options Namespace, "%s" does not exist!', $namespace)
            );
        }

        return $this->namespaces[$namespace];
    }

    /**
     * {@inheritDoc}
     */
    public function hasNamespace($namespace)
    {
        return isset($this->namespaces[$namespace]);
    }

    /**
     * Sets table name of settings
     *
     * @param  string|\Zend\Db\Sql\TableIdentifier $settingsTable
     * @return self
     */
    public function setSettingsTable($settingsTable)
    {
        $this->settingsTable = $settingsTable;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getSettingsTable()
    {
        return $this->settingsTable;
    }

    /**
     * {@inheritDoc}
     */
    public function getParameterEntityClass()
    {
        return $this->parameterEntityClass;
    }

    /**
     * Sets parameter entity class
     *
     * @param  string $parameterEntityClass
     * @return self
     */
    public function setParameterEntityClass($parameterEntityClass)
    {
        $this->parameterEntityClass = $parameterEntityClass;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getStoragePath()
    {
        return $this->storagePath;
    }

    /**
     * Sets storagePath
     *
     * @param  string                         $storagePath
     * @throws Exception\InvalidPathException
     * @return self
     */
    public function setStoragePath($storagePath)
    {
        $this->storagePath = $storagePath;

        return $this;
    }
}


<?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 Checkbox extends Common
{
	/**
	 * the name of element
	 *
	 * @access private
	 * @var    string
	 */
	private $_sType = null;

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

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

	/**
	 * the value of the checked element
	 *
	 * @access private
	 * @var    array
	 */
	private $_aValuesChecked = null;

	/**
	 * constructor that it increment (static) for all use
	 *
	 * @access public
	 * @param  string $sName name
	 * @param  string $sLabel label of checkbox
	 * @param  string $sValue value of checkbox
	 * @param  array $aValuesChecked value checked of checkbox
	 */
	public function __construct(string $sName, string $sLabel, string $sValue, array $aValuesChecked = null)
	{
		$this->setName($sName);
		$this->setValue($sValue);
		$this->setValuesChecked($aValuesChecked);
		$this->setLabel($sLabel);
	}

	/**
	 * 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 Checkbox
	 */
	public function setValue(string $sValue) : Checkbox
	{
		$this->_sValue = $sValue;
		return $this;
	}

	/**
	 * get the Value Checked
	 *
	 * @access public
	 * @return array
	 */
	public function getValuesChecked() : array
	{
		return $this->_aValuesChecked;
	}

	/**
	 * set the Value Checked
	 *
	 * @access public
	 * @param  array $aValuesChecked Values of input;
	 * @return Checkbox
	 */
	public function setValuesChecked(array $aValuesChecked) : Checkbox
	{
		$this->_aValuesChecked = $aValuesChecked;
		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 Checkbox
	 */
	public function setLabel(string $sLabel) : Checkbox
	{
		$this->_sLabel = $sLabel;
		return $this;
	}

	/**
	 * if the button is clicked
	 *
	 * @access public
	 * @param  string $sType type of input;
	 * @return bool
	 */
	public function isClicked(string $sType) : bool
	{
		if ($this->getType() === 'submit' || $this->getType() === 'button') {

			if (isset($_POST[$this->getName()])) { return true; }
		}

		return false;
	}

	/**
	 * get the <html>
	 *
	 * @access public
	 * @return string
	 */
	public function fetch() : string
	{
		$sContent = '<input type="checkbox" name="'.$this->getName().'[]" value="'.$this->getValue().'"';

		if (in_array($this->getValue(), $this->getValuesChecked())) { $sContent .= ' checked="checked"'; }

		$sContent .= '/> '.$this->getLabel();

		return $sContent;
	}
}


<?php

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

declare(strict_types = 1);

namespace Cawa\Renderer;

use Cawa\Cache\CacheFactory;

trait CacheTrait
{
    use CacheFactory;

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

    /**
     * @param string $key
     * @param int $tll
     * @param array $tags
     *
     * @return bool
     */
    private function renderCacheGet(string $key, int $tll = null, array $tags = []) : bool
    {
        $key = self::class . ':' . $key;

        $this->renderCacheData = [
            'key' => $key,
            'cache' => self::cache(self::class)->get($key),
            'ttl' => $tll,
            'tags' => $tags,

        ];

        return $this->renderCacheData['cache'] === false ? false : true;
    }

    /**
     * @param string $data
     *
     * @return string
     */
    private function renderCacheSet(string $data) {
        self::cache(self::class)->set(
            $this->renderCacheData['key'],
            $data,
            $this->renderCacheData['ttl'],
            $this->renderCacheData['tags']
        );

        return $data;
    }

    /**
     * @return string
     */
    public function render()
    {
        if ($this->renderCacheData['cache']) {
            return $this->renderCacheData['cache'];
        }

        return $this->renderCacheSet(parent::render());
    }
}


<?php

namespace CvoTechnologies\StreamEmulation;

use ArrayAccess;
use CvoTechnologies\StreamEmulation\Emulator\Emulator;
use Psr\Http\Message\StreamInterface;

class StreamWrapper implements ArrayAccess
{
    /**
     * @var resource
     */
    public $context;

    /**
     * @var \Psr\Http\Message\StreamInterface
     */
    protected $response;

    /**
     * @var \CvoTechnologies\StreamEmulation\Emulator\Emulator
     */
    protected $emulator;

    protected static $emulators = [
        'http' => 'CvoTechnologies\StreamEmulation\Emulator\HttpEmulator',
        'https' => 'CvoTechnologies\StreamEmulation\Emulator\HttpsEmulator',
    ];

    protected static $emulation;

    //region Stream wrapper methods

    // @codingStandardsIgnoreStart

    public function url_stat(string $path, int $flags)
    {
        $contents = file_get_contents($path);

        return [
            'size' => strlen($contents),
        ];
    }

    /**
     * Open a stream.
     *
     * @param string $path The path for the stream.
     * @return bool Whether the stream could be opened.
     */
    public function stream_open($path)
    {
        $scheme = parse_url($path, PHP_URL_SCHEME);
        if (substr($scheme, -10) === '-emulation') {
            $scheme = substr($scheme, 0, -10);
        }

        $emulator = static::getEmulatorInstance($scheme, $path, $this->getContext());
        if (!$emulator) {
            return false;
        }

        $this->setEmulator($emulator);

        $this->getEmulator()->setResponseStream($this->callEmulation($this->getEmulator()->getIncomingStream()));
        $this->setResponse($this->getEmulator()->getOutgoingStream());

        return true;
    }

    public function stream_stat()
    {
    }

    public function stream_read($length)
    {
        return $this->getResponse()->read($length);
    }

    public function stream_eof()
    {
        return $this->getResponse()->eof();
    }

    public function stream_set_option($option, $arg1, $arg2)
    {
        return true;
    }

    // @codingStandardsIgnoreEnd

    //endregion

    //region Getters and setters

    /**
     * Get the current stream context.
     *
     * @return resource The stream context.
     */
    public function getContext()
    {
        return $this->context;
    }

    /**
     * Get the emulator.
     *
     * @return Emulator The current emulator.
     */
    public function getEmulator()
    {
        return $this->emulator;
    }

    /**
     * Set the emulator to use.
     *
     * @param Emulator $emulator The emulator to use.
     * @return $this
     */
    public function setEmulator(Emulator $emulator)
    {
        $this->emulator = $emulator;

        return $this;
    }

    /**
     * Get the emulation to run.
     *
     * @return callable
     */
    public function getEmulation()
    {
        return static::$emulation;
    }

    /**
     * Get the response.
     *
     * @return StreamInterface The response as stream.
     */
    public function getResponse()
    {
        return $this->response;
    }

    /**
     * Set the response for this stream.
     *
     * @param StreamInterface $stream The response as stream.
     * @return $this
     */
    public function setResponse(StreamInterface $stream)
    {
        $this->response = $stream;

        return $this;
    }

    //endregion

    /**
     * Calls the emulation.
     *
     * @param StreamInterface $stream The request stream.
     * @return StreamInterface The response stream.
     */
    public function callEmulation(StreamInterface $stream)
    {
        return call_user_func($this->getEmulation(), $stream);
    }

    /**
     * Get an emulator instance.
     *
     * @param string $scheme The scheme to get an emulator for.
     * @param string $path The path of the stream.
     * @param resource $context The stream resource.
     * @return \CvoTechnologies\StreamEmulation\Emulator\Emulator The emulator instance.
     */
    public static function getEmulatorInstance($scheme, $path, $context)
    {
        if (!isset(static::$emulators[$scheme])) {
            throw new \InvalidArgumentException('No emulator found for scheme \'' . $scheme . '\'');
        }
        $emulator = static::$emulators[$scheme];

        return new $emulator($path, $context);
    }

    /**
     * Set the emulation to use.
     *
     * @param string|callable|object $emulation The emulation to use.
     * @param callable|null $assertionCallable The assertion call to use.
     * @return void
     */
    public static function emulate($emulation, callable $assertionCallable = null)
    {
        if ((is_string($emulation)) && (class_exists($emulation))) {
            $emulation = new $emulation($assertionCallable);
        }

        static::$emulation = $emulation;
    }

    /**
     * Registers an emulator class.
     *
     * @param string $scheme The method this emulator has to be registered to.
     * @param string $class The class name of the emulator.
     * @return void
     */
    public static function registerEmulator($scheme, $class)
    {
        if (!class_exists($class)) {
            throw new \InvalidArgumentException('Class \'' . $class . '\' does not exist');
        }

        static::$emulators[$scheme] = $class;
    }

    /**
     * Register a wrapper for the specified protocol.
     *
     * @param string $protocol The protocol to register a wrapper for.
     * @param bool $emulation Whether to suffix it with emulation.
     * @return void
     */
    public static function registerWrapper($protocol, $emulation = true)
    {
        if ($emulation) {
            $protocol .= '-emulation';
        }

        stream_wrapper_register($protocol, 'CvoTechnologies\StreamEmulation\StreamWrapper');
    }

    /**
     * Unregister a wrapper for the specified protocol.
     *
     * @param string $protocol The protocol to unregister a wrapper for.
     * @param bool $emulation Whether to suffix it with emulation.
     * @return void
     */
    public static function unregisterWrapper($protocol, $emulation = true)
    {
        if ($emulation) {
            $protocol .= '-emulation';
        }

        stream_wrapper_unregister($protocol);
    }

    /**
     * Override a internal stream wrapper.
     *
     * @param string $protocol The protocol to override.
     * @return void
     */
    public static function overrideWrapper($protocol)
    {
        stream_wrapper_unregister($protocol);

        static::registerWrapper($protocol, false);
    }

    /**
     * Restore an internal stream wrapper.
     *
     * @param string $protocol The protocol of the stream wrapper to restore.
     * @return void
     */
    public static function restoreWrapper($protocol)
    {
        stream_wrapper_restore($protocol);
    }

    /**
     * Whether a offset exists.
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
     * @param mixed $offset

     * An offset to check for.
     *

     * @return bool true on success or false on failure.
     *

     *

     * The return value will be casted to boolean if non-boolean was returned.
     * @since 5.0.0
     */
    public function offsetExists($offset)
    {
        return $this->getEmulator()->offsetExists($offset);
    }

    /**
     * Offset to retrieve.
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
     * @param mixed $offset

     * The offset to retrieve.
     *

     * @return mixed Can return all value types.
     * @since 5.0.0
     */
    public function offsetGet($offset)
    {
        return $this->getEmulator()->offsetGet($offset);
    }

    /**
     * Offset to set.
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
     * @param mixed $offset

     * The offset to assign the value to.
     *

     * @param mixed $value

     * The value to set.
     *

     * @return void
     * @since 5.0.0
     */
    public function offsetSet($offset, $value)
    {
        $this->getEmulator()->offsetSet($offset, $value);
    }

    /**
     * Offset to unset.
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
     * @param mixed $offset

     * The offset to unset.
     *

     * @return void
     * @since 5.0.0
     */
    public function offsetUnset($offset)
    {
        $this->getEmulator()->offsetUnset($offset);
    }
}


<?php

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

namespace Predis\Command\Redis;

use Predis\Command\Command as RedisCommand;

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

    /**
     * {@inheritdoc}
     */
    public function setArguments(array $arguments)
    {
        if (count($arguments) === 3 && is_array($arguments[2])) {
            list($operation, $destination) = $arguments;
            $arguments = $arguments[2];
            array_unshift($arguments, $operation, $destination);
        }

        parent::setArguments($arguments);
    }
}


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

namespace cascade\components\dataInterface\connectors\file;

use cascade\components\dataInterface\connectors\generic\Module as BaseModule;
use Yii;
use yii\helpers\Inflector;

/**
 * Module [[@doctodo class_description:cascade\components\dataInterface\connectors\file\Module]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class Module extends BaseModule
{
    /**
     * @var [[@doctodo var_type:_sourceFiles]] [[@doctodo var_description:_sourceFiles]]
     */
    protected $_sourceFiles = [];
    /**
     * @var [[@doctodo var_type:dataSourceClass]] [[@doctodo var_description:dataSourceClass]]
     */
    public $dataSourceClass = 'cascade\components\dataInterface\connectors\file\DataSource';
    /**
     * @var [[@doctodo var_type:sourceFileClass]] [[@doctodo var_description:sourceFileClass]]
     */
    public $sourceFileClass = 'cascade\components\dataInterface\connectors\file\SourceFile';

    /**
     * @var [[@doctodo var_type:_dataSources]] [[@doctodo var_description:_dataSources]]
     */
    protected $_dataSources;

    /**
     * @inheritdoc
     */
    public function beforeRun()
    {
        //\d($this->dataSources);exit;
        return true;
    }

    /**
     * Set source files.
     *
     * @param [[@doctodo param_type:value]] $value [[@doctodo param_description:value]]
     */
    public function setSourceFiles($value)
    {
        foreach ($value as $key => $settings) {
            if ($settings === false) {
                $this->_sourceFiles[$key] = false;
                continue;
            }
            if (!isset($settings['class'])) {
                $settings['class'] = $this->sourceFileClass;
            }
            $settings['id'] = $key;
            $this->_sourceFiles[$key] = Yii::createObject($settings);
        }
    }

    /**
     * Get source files.
     *
     * @return [[@doctodo return_type:getSourceFiles]] [[@doctodo return_description:getSourceFiles]]
     */
    public function getSourceFiles()
    {
        return $this->_sourceFiles;
    }

    /**
     * [[@doctodo method_description:loadForeignModels]].
     */
    public function loadForeignModels()
    {
    }

    /**
     * [[@doctodo method_description:packageNode]].
     *
     * @param [[@doctodo param_type:ous]]  $ous  [[@doctodo param_description:ous]]
     * @param [[@doctodo param_type:node]] $node [[@doctodo param_description:node]]
     *
     * @return [[@doctodo return_type:packageNode]] [[@doctodo return_description:packageNode]]
     */
    public function packageNode($ous, $node)
    {
        $attributes = $node->getAttributes();
        $p = ['object' => null, 'parents' => []];
        $object = [];
        $object['id'] = isset($attributes['objectGUID']) ? md5(implode(' ', $attributes['objectGUID']->getValues())) : null;
        $object['first_name'] = isset($attributes['givenName']) ? implode(' ', $attributes['givenName']->getValues()) : null;
        $object['last_name'] = isset($attributes['sn']) ? implode(' ', $attributes['sn']->getValues()) : null;
        $object['title'] = isset($attributes['title']) ? implode(' ', $attributes['title']->getValues()) : null;
        $object['email'] = isset($attributes['mail']) ? strtolower(implode(' ', $attributes['mail']->getValues())) : null;
        $object['phone_number'] = isset($attributes['telephoneNumber']) ? strtolower(implode(' ', $attributes['telephoneNumber']->getValues())) : null;
        $object['username'] = isset($attributes['sAMAccountName']) ? strtolower(implode(' ', $attributes['sAMAccountName']->getValues())) : null;

        if (empty($object['id'])) {
            return false;
        }
        $dataSources = $this->dataSources;
        $model = $dataSources['Individual']->registerReturnForeignModel($object);
        if (!$model) {
            return false;
        }
        $object['object_individual_id'] = $model;
        $userModel = $dataSources['User']->registerReturnForeignModel($object);

        //$dataSources['User']->registerReturnForeignModel($object);
        $p['object'] = $model;
        $p['parents'] = $this->discoverParents($ous, $node);
        foreach ($p['parents'] as $parent) {
            $parent->foreignObject->addChild($model);
        }

        return $p;
    }

    /**
     * Get foreign models config.
     *
     * @return [[@doctodo return_type:getForeignModelsConfig]] [[@doctodo return_description:getForeignModelsConfig]]
     */
    public function getForeignModelsConfig()
    {
        return [];
    }

    /**
     * Get foreign model config.
     *
     * @param [[@doctodo param_type:sourceFile]] $sourceFile [[@doctodo param_description:sourceFile]]
     * @param [[@doctodo param_type:modelName]]  $modelName  [[@doctodo param_description:modelName]]
     *
     * @return [[@doctodo return_type:getForeignModelConfig]] [[@doctodo return_description:getForeignModelConfig]]
     */
    public function getForeignModelConfig($sourceFile, $modelName)
    {
        $config = ['class' => Model::className()];
        if (isset($this->foreignModelsConfig[$modelName])) {
            $config = array_merge($config, $this->foreignModelsConfig[$modelName]);
        }
        $config['modelName'] = $modelName;
        $config['sourceFile'] = $sourceFile;
        $config['interface'] = $this;

        return $config;
    }

    /**
     * Get foreign model name.
     *
     * @param [[@doctodo param_type:tableName]] $tableName [[@doctodo param_description:tableName]]
     *
     * @return [[@doctodo return_type:getForeignModelName]] [[@doctodo return_description:getForeignModelName]]
     */
    public function getForeignModelName($tableName)
    {
        return Inflector::singularize(Inflector::id2camel($tableName, '_'));
    }

    /**
     * Get foreign model.
     *
     * @param [[@doctodo param_type:model]] $model [[@doctodo param_description:model]]
     *
     * @return [[@doctodo return_type:getForeignModel]] [[@doctodo return_description:getForeignModel]]
     */
    public function getForeignModel($model)
    {
        $models = $this->foreignModels;
        if (isset($models[$model])) {
            return $models[$model];
        }

        return false;
    }

    /**
     * Get foreign models.
     *
     * @return [[@doctodo return_type:getForeignModels]] [[@doctodo return_description:getForeignModels]]
     */
    public function getForeignModels()
    {
        if (is_null($this->_models)) {
            $this->_models = [];
            foreach ($this->sourceFiles as $sourceFile) {
                $modelName = $this->getForeignModelName($sourceFile->id);
                $this->_models[$modelName] = Yii::createObject($this->getForeignModelConfig($sourceFile, $modelName));
            }
        }

        return $this->_models;
    }

    /**
     * @inheritdoc
     */
    public function getForeignObject($foreignModelClass, $foreignPrimaryKey)
    {
        \d($foreignPrimaryKey);

        return false;
    }
}


<?php
namespace app\manage\controller;

use think\Url;
use think\Request;
use core\manage\logic\MemberLogic;
use core\manage\logic\MemberGroupLogic;

class Member extends Base
{

    /**
     * 用户列表
     *
     * @param Request $request
     * @return string
     */
    public function index(Request $request)
    {
        $this->site_title = '用户管理';
        $member_model = MemberLogic::model();

        $member_group = MemberGroupLogic::model()->select();
        $this->assign('member_group', $member_group);

        $list = MemberLogic::model()->select();
        $this->assign('list', $list);

        return $this->fetch();
    }

    /**
     * 添加用户
     *
     * @param Request $request
     * @return mixed
     */
    public function addMember(Request $request)
    {
        $user_logic = MemberLogic::instance();
        if ($request->isPost()) {
            $data = [
                'user_name' => $request->param('user_name'),
                'user_nick' => $request->param('user_nick'),
                'user_passwd' => $request->param('user_passwd'),
                're_passwd' => $request->param('re_passwd'),
                'group_id' => $request->param('group_id'),
                'user_status' => $request->param('user_status', 0)
            ];

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

            // 添加
            $user_logic->addMember($data);

            return $this->success('添加用户成功', Url::build('member/index'));
        } else {
            $this->site_title = '新增用户';

            // 群组下拉选择
            $member_group = MemberGroupLogic::instance()->getGroupSelect();
            $this->assign('member_group', $member_group);

            // 用户状态
            $user_status = $user_logic->userStatus();
            $this->assign('user_status', $user_status);

            return $this->fetch();
        }
    }

    /**
     * 编辑用户
     *
     * @param Request $request
     * @return mixed
     */
    public function editMember(Request $request)
    {
        $user_id = $request->param('user_id');
        if (empty($user_id)) {
            return $this->error('用户ID为空');
        }

        $user_logic = MemberLogic::instance();
        if ($request->isPost()) {
            $data = [
                'user_name' => $request->param('user_name'),
                'user_nick' => $request->param('user_nick'),
                'user_passwd' => $request->param('user_passwd'),
                're_passwd' => $request->param('re_passwd'),
                'group_id' => $request->param('group_id'),
                'user_status' => $request->param('user_status', 0)
            ];

            // 验证
            $scene = empty($data['user_passwd']) ? 'edit_info' : 'edit_passwd';
            $res = $user_logic->validate->scene($scene)->check($data);
            if (! $res) {
                return $this->error($user_logic->validate->getError());
            }

            // 修改
            $user_logic->saveMember($data, $user_id);

            return $this->success('修改用户成功', Url::build('member/index'));
        } else {
            $this->site_title = '编辑菜单';
            $this->assign('user_id', $user_id);

            // 用户
            $member = $user_logic->model->get($user_id);
            $this->assign('member', $member);

            // 群组下拉选择
            $member_group = MemberGroupLogic::instance()->getGroupSelect();
            $this->assign('member_group', $member_group);

            // 状态
            $user_status = $user_logic->userStatus();
            $this->assign('user_status', $user_status);

            return $this->fetch();
        }
    }

    /**
     * 删除用户
     *
     * @param Request $request
     * @return mixed
     */
    public function delMember(Request $request)
    {
        $user_id = $request->param('user_id');
        if (empty($user_id)) {
            return $this->error('用户ID为空');
        }
        $user_logic = MemberLogic::instance();

        // 超级用户
        if ($user_logic->isAdmin($user_id)) {
            return $this->error('超级用户不能删除');
        }

        // 删除用户
        $user_logic->model->del($user_id);

        return $this->success('删除用户成功', Url::build('member/index'));
    }

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

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

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

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


<?php

declare (strict_types=1);

namespace Coshi\Variator;

use Coshi\Variator\Exception\InvalidConfigurationException;
use Coshi\Variator\Variation\VariationInterface;

class ConfigResolver
{
    /**
     * @var callable[]
     */
    protected $contextCallbacks;

    /**
     * @param array  $arguments
     * @param string $name
     *
     * @return bool
     */
    public function containsArgumentsPattern(array $arguments, string $name) : bool
    {
        foreach ($arguments as $key => $argument) {
            if (is_string($argument) && '@'.$name === $argument) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param array  $requiredArgs
     * @param array  $parameters
     * @param string $type
     *
     * @return bool
     *
     * @throws InvalidConfigurationException
     */
    public function requireArguments(array $requiredArgs, array $parameters, string $type) : bool
    {
        foreach ($requiredArgs as $parameter) {
            if (!array_key_exists($parameter, $parameters)) {
                throw new InvalidConfigurationException(sprintf('Parameter "%s" for type "%s" is required', $parameter, $type));
            }
        }

        return true;
    }

    /**
     * @param array $config
     *
     * @return array
     *
     * @throws \InvalidArgumentException
     */
    public function resolveCallback(array $config)
    {
        if (count($config) < 1) {
            throw new \InvalidArgumentException('Cannot resolve empty callback');
        }

        if (!isset($config[1]) || is_array($config[1])) {
            $callable = $config[0];
            $arguments = $config[1] ?? [];
        } else {
            $callable = [$this->resolveInstance($config), $config[1]];
            $arguments = $config[2] ?? [];
        }

        return [
            'callback' => $callable,
            'arguments' => $arguments,
        ];
    }

    /**
     * @param array $callback - callback config returned from ConfigResolver::resolveCallback() method
     *
     * @return mixed
     */
    public function call(array $callback)
    {
        return call_user_func_array($callback['callback'], $this->processArguments($callback['arguments']));
    }

    /**
     * @param array $arguments
     *
     * @return array
     */
    public function processArguments(array $arguments) : array
    {
        foreach ($arguments as $key => $value) {
            if (is_string($value) && 0 === strpos($value, '@')) {
                $name = substr($value, 1);

                if (isset($this->contextCallbacks[$name])) {
                    $arguments[$key] = call_user_func($this->contextCallbacks[$name]);
                }
            }
        }

        return $arguments;
    }

    /**
     * @param VariationInterface $variation
     *
     * @return bool
     */
    public function addCallback(VariationInterface $variation)
    {
        $closure = (function () {
            if (!$this->isValid()) {
                $this->doRewind();
            }

            return $this->getCurrent();
        })->bindTo($variation, $variation);
        $this->contextCallbacks[$variation->getName()] = $closure;

        return true;
    }

    protected function resolveInstance(array $config)
    {
        $instance = $config[0];

        if (!is_string($instance)) {
            throw new InvalidConfigurationException(sprintf('Expected type "string" for callback class, found "%s"', gettype($instance)));
        }

        if (!class_exists($instance)) {
            throw new \InvalidArgumentException(sprintf('Class %s does not exist', $instance));
        }
        $reflection = new \ReflectionClass($instance);
        $method = $reflection->getMethod($config[1]);

        if (!$method->isStatic()) {
            $instance = new $instance();
        }

        return $instance;
    }
}


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

namespace RedKiteCms\Content\BlockManager;

use RedKiteCms\Bridge\Dispatcher\Dispatcher;
use RedKiteCms\Bridge\Monolog\DataLogger;
use RedKiteCms\EventSystem\BlockEvents;
use RedKiteCms\EventSystem\Event\Block\BlockApprovedEvent;
use RedKiteCms\EventSystem\Event\Block\BlockApprovedRemovalEvent;
use RedKiteCms\EventSystem\Event\Block\BlockApprovingEvent;
use RedKiteCms\EventSystem\Event\Block\BlockApprovingRemovalEvent;
use RedKiteCms\Tools\FilesystemTools;
use RedKiteCms\Tools\JsonTools;

/**
 * Class BlockManagerApprover is the object assigned to approve a block contribution
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\BlockManager
 */
class BlockManagerApprover extends BlockManager
{
    /**
     * Approves a contribution
     *
     * @param string $sourceDir
     * @param array $options
     * @param string $username
     *
     * @return array The approved block
     */
    public function approve($sourceDir, array $options, $username)
    {
        $this->init($sourceDir, $options, $username);

        $sourceFilename = sprintf('%s/blocks/%s.json', $this->contributorDir, $options['blockname']);
        $targetFilename = sprintf('%s/blocks/%s.json', $this->productionDir, $options['blockname']);

        Dispatcher::dispatch(
            BlockEvents::BLOCK_APPROVING,
            new BlockApprovingEvent($this->serializer, $sourceFilename, $targetFilename)
        );

        $blockValues = JsonTools::jsonDecode(FilesystemTools::readFile($sourceFilename));
        $blockValues["history"] = array();
        FilesystemTools::writeFile($targetFilename, json_encode($blockValues));

        $slotDefinitionContribution = $this->getSlotDefinition($this->getContributorDir());
        $this->saveSlotDefinition($this->productionDir, $slotDefinitionContribution);

        Dispatcher::dispatch(
            BlockEvents::BLOCK_APPROVED,
            new BlockApprovedEvent($this->serializer, $sourceFilename, $targetFilename)
        );

        DataLogger::log(
            sprintf(
                'Block "%s" has been approved on the "%s" slot on page "%s" for the "%s_%s" language',
                $options["blockname"],
                $options["slot"],
                $options["page"],
                $options["language"],
                $options["country"]
            )
        );

        return $blockValues;
    }

    /**
     * Approves the removal of the given contribution
     *
     * @param string $sourceDir
     * @param array $options
     * @param string $username
     */
    public function approveRemoval($sourceDir, array $options, $username)
    {
        $this->init($sourceDir, $options, $username);
        $targetFilename = sprintf('%s/blocks/%s.json', $this->productionDir, $options['blockname']);
        if (!file_exists($targetFilename)) {
            // @codeCoverageIgnoreStart
            return;
            // @codeCoverageIgnoreEnd
        }

        Dispatcher::dispatch(
            BlockEvents::BLOCK_APPROVING_REMOVAL,
            new BlockApprovingRemovalEvent($this->serializer, $targetFilename)
        );

        $this->filesystem->remove($targetFilename);

        $slotDefinition = $this->getSlotDefinition($this->productionDir);
        $blocks = $slotDefinition["blocks"];
        $key = array_search($options['blockname'], $blocks);
        unset($blocks[$key]);
        $slotDefinition["blocks"] = $blocks;
        $this->saveSlotDefinition($this->productionDir, $slotDefinition, $username);

        Dispatcher::dispatch(
            BlockEvents::BLOCK_APPROVED_REMOVAL,
            new BlockApprovedRemovalEvent($this->serializer, $targetFilename)
        );

        DataLogger::log(
            sprintf(
                'Block "%s" has been approved for removal on the "%s" slot on page "%s" for the "%s_%s" language',
                $options["blockname"],
                $options["slot"],
                $options["page"],
                $options["language"],
                $options["country"]
            )
        );
    }
}


<?php
/**
 * MySQL
 * User: jonathanbak
 * Date: 2017. 2. 1.
 */

namespace MySQLiLib;

class MySQLDb extends DbAbstract
{
    private $result_total_rows = array();
    private $result_current_row = array();

    public function connect($host, $user, $password, $dbName, $dbPort = '3306')
    {
        $connection = @mysqli_connect($host, $user, $password, $dbName, $dbPort);
        if (!$connection) {
            throw new Exception(mysqli_connect_error(), mysqli_connect_errno());
        }
        return $connection;
    }

    public function query($query, $params = array())
    {
        if(count($params)>0) $query = $this->parseCondition($query, $params);
        $this->result = mysqli_query($this->connection, $query);

        if(mysqli_errno($this->connection)){
            throw new Exception(mysqli_error($this->connection), mysqli_errno($this->connection));
        }

        return $this->result;
    }

    public function error()
    {
        return mysqli_error($this->connection);
    }

    public function errorNo()
    {
        return mysqli_errno($this->connection);
    }

    /**
     * 한행 가져오기
     * @param $query
     * @param array $params
     * @return bool|mixed|null
     * @throws Exception
     */
    public function fetch($query, $params = array())
    {
        if(count($params)>0) $query = $this->parseCondition($query, $params);
        $mdKey = md5($query);
        if(!isset($this->result_query[$mdKey])){
            $this->result_query[$mdKey] = $this->query($query);
            $this->result_total_rows[$mdKey] = $this->result_query[$mdKey]->num_rows;
            $this->result_current_row[$mdKey] = 0;
        }else{
            $this->result_current_row[$mdKey]++;
            if($this->result_total_rows[$mdKey] <= $this->result_current_row[$mdKey]) {
                unset($this->result_query[$mdKey]);
                unset($this->result_current_row[$mdKey]);
                unset($this->result_total_rows[$mdKey]);
            }
        }

        if( isset($this->result_query[$mdKey]) && is_a($this->result_query[$mdKey], 'mysqli_result') ) return $this->result_query[$mdKey]->fetch_assoc() ;

        return isset($this->result_query[$mdKey])? isset($this->result_query[$mdKey]) : null;
    }

    public function fetchOne($query, $params = array())
    {
        if(count($params)>0) $query = $this->parseCondition($query, $params);
        $result = $this->query($query);
        return $result->fetch_assoc();
    }

    public function close()
    {
        $this->result_query = array();

        return mysqli_close($this->connection);
    }

    /**
     * 여러행 가져오기
     * @param $query
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function fetchAll($query, $params = array())
    {
        $rows = array();
        while($row = $this->fetch($query, $params)){
            $rows[] = $row;
        }
        return $rows;
    }

    /**
     * 마지막 입력 번호 가져오기 (auto increment column)
     * @return mixed|null
     * @throws Exception
     */
    public function lastInsertId()
    {
        $row = $this->fetch("select last_insert_id() as lastId");
        return $row ? array_pop($row) : null;
    }
}


<?php
/**
 * (c) Joffrey Demetz <joffrey.demetz@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace JDZ\Filesystem;

/**
 * Filesystem Helper
 *
 * @author Joffrey Demetz <joffrey.demetz@gmail.com>
 */
abstract class Helper
{
  /**
   * Holds an array of translations
   *
   * Defaults are in french
   *
   * @var   array
   */
  protected static $translations = [
    'UNKNOWN_ERROR'       => 'Erreur de type inconnu',
    'CANNOT_FIND_SOURCE'  => 'Impossible de trouver la source',
    'ALREADY_EXISTS'      => 'Existe',
    'NOT_A_FOLDER'        => 'Le chemin n\'est pas un dossier',
    'FAILED_CREATING'     => 'Échec de la création',
    'FAILED_DELETING'     => 'Échec de la suppression',
    'FAILED_RENAMING'     => 'Échec du renommage',
    'FAILED_CHMOD'        => 'Impossible de modifier les permissions du fichier',
    'FAILED_MOVE_UPLOAD'  => 'Impossible de déplacer le fichier uploadé',

    // 'CANNOT_FIND_SOURCE' => 'Impossible de trouver la source',
    // 'FAILED_COPYING_FILE' => 'Échec de la copie',
    // 'FAILED_DELETING_FILE' => 'Échec de la suppression',
    // 'FILE_CANNOT_FIND_SOURCE' => 'Impossible de trouver le fichier source',
    // 'UNABLE_TO_FIND_SOURCE_FILE' => 'Impossible de trouver ou de lire le fichier',
    // 'FAILED_RENAMING_FILE' => 'Échec du renommage',
    // 'UNABLE_TO_READ_FILE' => 'Impossible d\'ouvrir le fichier',
    // 'UNABLE_TO_MODIFY_FILE_PERMISSIONS' => 'Impossible de modifier les permissions du fichier.',
    // 'UNABLE_TO_MODIFY_MOVE_UPLOADED_FILE' => 'Impossible de déplacer le fichier uploadé.',
    // 'FAILED_FINDING_SOURCE_FOLDER' => 'Impossible de trouver le répertoire source',
    // 'FOLDER_ALREADY_EXISTS' => 'Le répertoire existe déjà',
    // 'FAILED_CREATING_FOLDER' => 'Impossible de créer le répertoire cible',
    // 'FAILED_READING_SOURCE_FOLDER' => 'Impossible d\'ouvrir le répertoire source',
    // 'FOLDER_LOOP' => 'Boucle infinie détectée',
    // 'FOLDER_PATH_IS_NOT_IN_OPEN_BASEDIR' => 'Le chemin n\'est pas dans les chemins open_basedir',
    // 'FAILED_DELETING_FOLDER' => 'Impossible de supprimer le répertoire.',
    // 'FOLDER_CANNOT_DELETE_ROOT' => 'Vous ne pouvez pas supprimer un répertoire de base.',
    // 'FAILED_RENAMING_FOLDER' => 'Échec du renommage',
    // 'FOLDER_PATH_IS_NOT_A_FOLDER' => 'Le chemin n\'est pas un répertoire.',
    // 'INVALID_ZIP_DATA' => 'Données ZIP invalides',

    // 'ARCHIVE_UNABLE_TO_LOAD' => 'Impossible de charger l\'archive',
    // 'ARCHIVE_UNABLE_TO_READ' => 'Impossible de lire l\'archive (%s)',
    // 'ARCHIVE_UNABLE_TO_WRITE' => 'Impossible d\'écrire l\'archive (%s)',
    // 'ARCHIVE_UNABLE_TO_WRITE_FILE' => 'Impossible d\'écrire le fichier (%s)',
    // 'ARCHIVE_UNABLE_TO_WRITE_ENTRY' => 'Impossible d\'écrire l\'entrée (%s)',
    // 'ARCHIVE_UNABLE_TO_DECOMPRESS' => 'Impossible de décompresser les données',
    // 'ARCHIVE_UNABLE_TO_CREATE_DESTINATION' => 'Impossible de créer la destination',
    // 'ARCHIVE_UNABLE_TO_READ_ENTRY' => 'Impossible de lire l\'entrée',
    // 'ARCHIVE_UNABLE_TO_OPEN_ARCHIVE' => 'Impossible d\'ouvrir l\'archive',
    // 'ARCHIVE_ZIP_INFO_FAILED' => 'Échec de l\'obtention de l\'information ZIP',
  ];

  /**
   * Set the translations
   *
   * @param   array   $translations     Key/value pairs of translations
   * @return  void
   */
  public static function setTranslations(array $translations=[])
  {
    self::$translations = array_merge(self::$translations, $translations);
  }

  /**
   * Translation
   *
   * @param   string  $key  The translation key
   * @return  string  Translated string or "Unknown Error" if not found
   */
  public static function getTranslation($key)
  {
    $key = strtoupper($key);
    if ( isset(self::$translations[$key]) ){
      return self::$translations[$key];
    }

    return self::$translations['UNKNOWN_ERROR'];
  }
}


<?php

namespace Esockets\Protocol\Base;

use Esockets\Base\CallbackEventListener;
use Esockets\Base\Event;
use Esockets\Base\Exception\ReadException;

/**
 * Пакетный буфер чтения.
 * Решает 2 проблемы:
 *  - чтение пакетов по порядку,
 *  - слежение за потерянными пакетами.
 */
class ReadPacketBuffer implements PacketBufferInterface
{
    const READ_TIMEOUT = 10; // 5 seconds

    private $lastCompletedId = 0;
    private $buffer = [];
    private $meta = [];

    private $eventRequestPacket;

    public function __construct()
    {
        $this->eventRequestPacket = new Event();
    }

    /**
     * @inheritDoc
     */
    public function reset()
    {
        $this->lastCompletedId = 0;
        $this->buffer = [];
        $this->meta = [];
    }

    /**
     * Назначет обработчик события, когда нужно запросить пакет.
     *
     * @param callable $callback
     *
     * @return CallbackEventListener
     */
    public function onPacketRequest(callable $callback): CallbackEventListener
    {
        return $this->eventRequestPacket->attachCallbackListener($callback);
    }

    /**
     * Добавляет прочитанный пакет в буфер.
     * Вернёт true, если пакет был добавлен в буфер,
     * и false, если пакет готов к чтению и не был добавле в буфер.
     *
     * @param int $id
     * @param bool $isPartedPacket
     * @param mixed $data
     * @param mixed $meta дополнительная meta информация к пакету
     *
     * @return bool
     */
    public function addPacket(int $id, bool $isPartedPacket, bool $isEndPart, $data, $meta = null): bool
    {
//        echo 'received  ', $id, PHP_EOL;
        if ($isPartedPacket || $id > $this->lastCompletedId + 1) {
            // частичные пакеты в любом случае добавляем в буфер чтения
            // или чтение нескольких пакетов пропущено
            // заполняем пропущенные пакеты флажками
            for ($i = $this->lastCompletedId + 1; $i < $id; $i++) {
                if (!isset($this->buffer[$i])) {
                    $this->buffer[$i] = false;
                    $this->meta[$i] = [
                        'time' => time(),
                        'part' => $isPartedPacket,
                        'end' => $isPartedPacket && $isEndPart,
                        'meta' => null
                    ];
                }
            }
            // записываем в буфер текущий пакет
            $this->buffer[$id] = $data;
            $this->meta[$id] = [
                'time' => time(),
                'part' => $isPartedPacket,
                'end' => $isPartedPacket && $isEndPart,
                'meta' => $meta
            ];
            $result = true;
        } elseif ($id === $this->lastCompletedId + 1) {
            // если чтение пакетов идёт по порядку, то все ок
            $this->lastCompletedId++;
            $result = false;
        } else {
            // duplicate of packet
            ; // nothing
            $result = true;
        }
        return $result;
    }

    /**
     * Читает пакет из буфера.
     * Метод вернёт null если читать нечего.
     * Вернёт массив с данными пакета и его мета информацией:
     *  ['data', 'meta']
     *
     * @return array|null
     * @throws \Exception
     */
    public function getPacketIfExists()
    {
        $result = null;
        $ne = 0;
        // проверка пакетов с тайм-аутом
        foreach ($this->meta as $packetId => &$data) {
            if ($this->buffer[$packetId] !== false) {
                continue;
            }
            $ne++;
            if ($data['time'] < time() - self::READ_TIMEOUT) {
                // устанавливаем количество попыток
                if (isset($data['try'])) {
                    if ($data['try'] > 10) {
                        // если за 10 попыток не удалось получить пакет
                        // помечаем пакет как удалённый
                        $data['deleted'] = true;
                        throw new ReadException(
                            'Could not receive data packet with id ' . $packetId,
                            ReadException::ERROR_PROTOCOL
                        );
                    }
                    $data['try']++;
                } else {
                    $data['try'] = 1;
                }

                // дёргаем обработчик для отправки запроса пакета
                $this->eventRequestPacket->call($packetId);
                usleep(1000);

                // обновляем время последнего запроса пакета
                $data['time'] = time();
            } else {
                break;
            }
            unset($data);
        }
        if ($ne > 0) {

//            echo 'not enough', $ne, PHP_EOL;
        }

        $nextId = $this->lastCompletedId + 1;
        if (array_key_exists($nextId, $this->buffer) && $this->buffer[$nextId] !== false) {
            // если можно прочитать следующий по порядку пакет
            if ($this->meta[$nextId]['part']) {
                // если пакет является частью
                // пройдёмся по буферу и выясним, есть ли все части идущие за этим пакетом
                for ($i = $nextId + 1; array_key_exists($i, $this->buffer); $i++) {
                    if (
                        $this->buffer[$i] === false
                    ) {
                        // если пакет на текущей итерации ещё не получен,
                        // то дальнейшие поиски бессмысленны, выходим из цикла
                        break;
                    } elseif ($this->meta[$i]['part'] && $this->meta[$i]['end']) {
                        // если наткнулись на последний частичный пакет, значит до этого момента пакеты были частями
                        // собереём их по порядку, и выйдем из цикла вернув результат - собранный пакет
                        $packet = '';
                        $meta = $this->meta[$nextId]['meta'];
                        for ($j = $nextId; $j <= $i; $j++) {
                            $packet .= $this->buffer[$j];
                            unset($this->buffer[$j]);
                            unset($this->meta[$j]);
                        }
                        // установим id успешно прочитанного последнего пакета-части
                        $this->lastCompletedId = $i;
                        $result = [$packet, $meta];
                        break;
                    } else {
                    }
                }
            } else {
                // если пакет нормальный и готов к чтению
                $result = [$this->buffer[$nextId], $this->meta[$nextId]['meta']];
                unset($this->buffer[$nextId]);
                unset($this->meta[$nextId]);
                $this->lastCompletedId = $nextId;
            }
        }
        return $result;
    }
}


<?php
namespace Clusterpoint\Response;

use Iterator;
use Countable;
use Clusterpoint\Testing\ConnectionFaker;
use Clusterpoint\Contracts\ResponseInterface;
use Clusterpoint\Contracts\ConnectionInterface;
use Clusterpoint\Exceptions\ClusterpointException;

/**
 *
 * Response Class, holds common behaivior of Batch and Single Classes.
 *
 * @category   Clusterpoint 4.0 PHP Client API
 * @package    clusterpoint/php-client-api-v4
 * @copyright  Copyright (c) 2016 Clusterpoint (http://www.clusterpoint.com)
 * @author     Marks Gerasimovs <marks.gerasimovs@clusterpoint.com>
 * @license    http://opensource.org/licenses/MIT    MIT
 */
class Response implements Iterator, Countable, ResponseInterface
{
	/**
	 * Holds response results and meta info.
	 *
	 * @var object
	 */
	protected $scope;

	/**
	 * Counter for \Iterator
	 *
	 * @var int
	 */
	protected $position = 0;

	/**
	 * Construct object to operate response data.
	 *
	 * @param  object $raw_response
	 * @param  object $connection
	 * @return void
	 */
	public function __construct($raw_response, ConnectionInterface $connection)
	{
		$response = json_decode($raw_response);
		$this->scope = new Scope($response);
		$this->scope->rawResponse = $raw_response;
		$this->scope->query = isset($connection->query) ? $connection->query : null;
		$this->connection = clone($connection);
		if ($this instanceof Single) {
			$this->scope->retrieved = false;
			$this->scope->results = isset($response->results) ? isset($response->results[0]) ? (array)$response->results[0] : array() : array();
			if ($connection->method == "GET") {
				$this->scope->retrieved = true;
				$this->_id = count($this->scope->results) > 0 ? substr($connection->action, 1, -1) : false;
			}
		}
		$this->connection->resetSelf();
		if (isset($this->scope->error)) {
			foreach ($this->scope->error as $error) {
				if (!$connection instanceof ConnectionFaker) {
					switch ($error->code) {
						case 2824:
							//  Requested document does not exist.
							break;

						default:
							throw new ClusterpointException($error->message, isset($error->code) ? $error->code : 2417);
							break;
					}
				}
			}
		}
	}

	/**
	 * Rewind the Iterator to the first element
	 *
	 * @return object
	 */
	public function rewind()
	{
		return reset($this->scope->results);
	}

	/**
	 * Return the current element
	 *
	 * @return object
	 */
	public function current()
	{
		return current($this->scope->results);
	}

	/**
	 * Return the key of the current element
	 *
	 * @return int
	 */
	public function key()
	{
		return key($this->scope->results);
	}

	/**
	 * Move forward to next element
	 *
	 * @return object
	 */
	public function next()
	{
		return next($this->scope->results);
	}

	/**
	 * Checks if current position is valid
	 *
	 * @return bool
	 */
	public function valid()
	{
		return key($this->scope->results) !== null;
	}

	/**
	 * Return the amount of elements in results
	 *
	 * @return int
	 */
	public function count()
	{
		return count($this->scope->results);
	}

	/**
	 * Returns the position of the last document that was returned
	 *
	 * @return int
	 */
	public function to()
	{
		return $this->scope->to;
	}

	/**
	 * Returns the position of the first document that was returned
	 *
	 * @return int
	 */
	public function from()
	{
		return $this->scope->from;
	}

	/**
	 * Returns the total number of hits - i.e. the number of documents in a storage that match the request
	 *
	 * @return int
	 */
	public function hits()
	{
		return $this->scope->hits;
	}

	/**
	 * Returns the left amount of documents, within the returned results.
	 *
	 * @return int
	 */
	public function more()
	{
		return $this->scope->more;
	}

	/**
	 * Returns array of errors occured.
	 *
	 * @return array
	 */
	public function error()
	{
		return $this->scope->error;
	}

	/**
	 * Returns the number of documents returned.
	 *
	 * @return int
	 */
	public function found()
	{
		return $this->scope->found;
	}

	/**
	 * Returns the time that it took to process the request in the CPS engine
	 *
	 * @return float
	 */
	public function seconds()
	{
		return $this->scope->seconds;
	}

	/**
	 * Returns the response JSON string.
	 *
	 * @return string
	 */
	public function rawResponse()
	{
		return $this->scope->rawResponse;
	}

	public function collectionStatus()
	{
		return $this->scope->collection_status;
	}

	/**
	 * Returns the string with executed Query. Alias for getQuery()
	 *
	 * @return string
	 */
	public function executedQuery()
	{
		return $this->scope->query;
	}

	/**
	 * Returns the string with executed Query.
	 *
	 * @return string
	 */
	public function getQuery()
	{
		return $this->scope->query;
	}

	public function shards()
	{
		return $this->scope->shards;
	}

	public function describe()
	{
		$descriptionFields = array(
			'name',
			'code_name',
			'visual_name',
			'shards',
			'replicas',
			'feature_v4',
			'feature_hyperreplicated',
			'support_access',
			'overrides'
		);

		$result = array();

		foreach ($descriptionFields as $field) {
			if (isset($this->scope->$field)) {
				$result[$field] = $this->scope->$field;
			}
		}

		return $result;
	}

	/**
	 * Returns results as the array.
	 *
	 * @return string
	 */
	public function toArray()
	{
		return json_decode(json_encode($this->scope->results), true);
	}

	/**
	 * Returns results as JSON string.
	 *
	 * @param bool $pretty
	 * @return string
	 */
	public function toJSON($pretty = false)
	{
		if ($pretty) {
			return json_encode($this->scope->results, JSON_PRETTY_PRINT);
		}
		return json_encode($this->scope->results);
	}
}


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

namespace RedKiteCms\Content\Block;

use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Exception\General\RuntimeException;
use Symfony\Component\Finder\Finder;

/**
 * This is the object implements the factory assigned to create blocks
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\Block
 */
class BlockFactory
{
    /**
     * @type array
     */
    private static $blocks = array();

    /**
     * Boots the factory
     *
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     */
    public static function boot(ConfigurationHandler $configurationHandler)
    {
        $pluginDirs = $configurationHandler->pluginFolders();
        foreach ($pluginDirs as $pluginDir) {
            self::$blocks += self::parse($pluginDir);
        }
    }

    /**
     * Returns the available blocks
     *
     * @return string
     */
    public static function getBlockClass($type)
    {
        if (!array_key_exists($type, self::$blocks)) {
            return '';
        }

        return self::$blocks[$type];
    }

    /**
     * Returns the available blocks
     *
     * @return array
     */
    public static function getAvailableBlocks()
    {
        return self::$blocks;
    }

    /**
     * {@inheritdoc}
     */
    public static function createBlock($type)
    {
        if (!array_key_exists($type, self::$blocks)) {
            throw new RuntimeException(
                sprintf('The plugin %s is not registered: the block has not been created', $type)
            );
        }

        $class = self::$blocks[$type];

        return self::instantiateBlock($class);
    }

    /**
     * {@inheritdoc}
     */
    public static function createAllBlocks()
    {
        $blocks = array();
        foreach (self::$blocks as $blockClass) {
            $blocks[] = self::instantiateBlock($blockClass);
        }

        return $blocks;
    }

    private static function instantiateBlock($class)
    {
        $reflectionClass = new \ReflectionClass($class);

        return $reflectionClass->newInstance();
    }

    private static function parse($pluginDir)
    {
        $blocks = array();
        $blocksDir = $pluginDir . '/Block';
        $finder = new Finder();
        $folders = $finder->directories()->depth(0)->in($blocksDir);
        foreach ($folders as $folder) {
            $blocks = array_merge($blocks, self::fetchBlocks($folder));
        }

        return $blocks;
    }

    private static function fetchBlocks($folder)
    {
        $blocks = array();
        $finder = new Finder();
        $files = $finder->files()->depth(0)->name('*Block.php')->in($folder . '/Core');
        $folderName = basename($folder);
        foreach ($files as $file) {
            $blockName = basename($file, 'Block.php');
            $blocks[$blockName] = sprintf('RedKiteCms\Block\%s\Core\%sBlock', $folderName, $blockName);
        }

        return $blocks;
    }
}


<?php

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

namespace In2pire\Cli\Input;

use Symfony\Component\Console\Input\ArgvInput as ConsoleArgvInput;
use In2pire\Cli\Input\InputOption;

class ArgvInput extends ConsoleArgvInput
{
    /**
     * Returns true if flag is enabled and not empty.
     *
     * @param string $name
     *   Option name.
     *
     * @return boolean
     *   True if the flag is contained in raw parameters and its value is not
     *   empty.
     */
    public function hasFlag($name)
    {
        $option = $this->definition->getOption($name);

        if (!$option->isFlag()) {
            throw new \InvalidArgumentException(sprintf('The "--%s" option is not a flag.', $name));
        }

        return !empty($this->options[$name]);
    }

    /**
     * @inheritdoc
     */
    protected function parse()
    {
        parent::parse();

        // Transform flags' value.
        foreach ($this->definition->getOptions() as $option) {
            if ($option instanceof InputOption && $option->isFlag()) {
                $name = $option->getName();

                if (!array_key_exists($name, $this->options)) {
                    $this->options[$name] = false;
                } elseif (null === $this->options[$name]) {
                    $this->options[$name] = true;
                }
            }
        }
    }
}


<?php

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

/**
 * MiniProgramServiceProvider.php.
 *
 * This file is part of the wechat.
 *
 * (c) mingyoung <mingyoungcheung@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace EasyWeChat\Foundation\ServiceProviders;

use EasyWeChat\MiniProgram\AccessToken;
use EasyWeChat\MiniProgram\Encryption\Encryptor;
use EasyWeChat\MiniProgram\Material\Temporary;
use EasyWeChat\MiniProgram\MiniProgram;
use EasyWeChat\MiniProgram\Notice\Notice;
use EasyWeChat\MiniProgram\QRCode\QRCode;
use EasyWeChat\MiniProgram\Server\Guard;
use EasyWeChat\MiniProgram\Sns\Sns;
use EasyWeChat\MiniProgram\Staff\Staff;
use EasyWeChat\MiniProgram\Stats\Stats;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Class MiniProgramServiceProvider.
 */
class MiniProgramServiceProvider implements ServiceProviderInterface
{
    /**
     * Registers services on the given container.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param Container $pimple A container instance
     */
    public function register(Container $pimple)
    {
        $pimple['mini_program.access_token'] = function ($pimple) {
            return new AccessToken(
                $pimple['config']['mini_program']['app_id'],
                $pimple['config']['mini_program']['secret'],
                $pimple['cache']
            );
        };

        $pimple['mini_program.encryptor'] = function ($pimple) {
            return new Encryptor(
                $pimple['config']['mini_program']['app_id'],
                $pimple['config']['mini_program']['token'],
                $pimple['config']['mini_program']['aes_key']
            );
        };

        $pimple['mini_program.server'] = function ($pimple) {
            $server = new Guard($pimple['config']['mini_program']['token']);
            $server->debug($pimple['config']['debug']);
            $server->setEncryptor($pimple['mini_program.encryptor']);

            return $server;
        };

        $pimple['mini_program.staff'] = function ($pimple) {
            return new Staff($pimple['mini_program.access_token']);
        };

        $pimple['mini_program.notice'] = function ($pimple) {
            return new Notice($pimple['mini_program.access_token']);
        };

        $pimple['mini_program.material_temporary'] = function ($pimple) {
            return new Temporary($pimple['mini_program.access_token']);
        };

        $pimple['mini_program.stats'] = function ($pimple) {
            return new Stats(
                $pimple['mini_program.access_token'],
                $pimple['config']['mini_program']
            );
        };

        $pimple['mini_program.sns'] = function ($pimple) {
            return new Sns(
                $pimple['mini_program.access_token'],
                $pimple['config']['mini_program']
            );
        };

        $pimple['mini_program.qrcode'] = function ($pimple) {
            return new QRCode(
                $pimple['mini_program.access_token'],
                $pimple['config']['mini_program']
            );
        };

        $pimple['mini_program'] = function ($pimple) {
            return new MiniProgram($pimple);
        };
    }
}


<?php
namespace eMacros\Runtime\Method;

use eMacros\Runtime\GenericFunction;

class MethodInvoke extends GenericFunction {
	/**
	 * Method name
	 * @var string
	 */
	public $method;

	public function __construct($method = null) {
		$this->method = $method;
	}

	/**
	 * Invokes a method with the given arguments
	 * Usage: (->format (new Datetime) "Y-m-d")
	 * Returns: mixed
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
	public function execute(array $arguments) {
		if (empty($arguments)) throw new \BadFunctionCallException('MethodInvoke: No parameters found.');

		if (is_null($this->method)) {
			if (!isset($arguments[1])) throw new \BadFunctionCallException('MethodInvoke: No instance defined.');
			//check method type
			if (!is_string($arguments[0]))
				throw new \InvalidArgumentException(sprintf("MethodInvoke: A value of type string was expected as first argument but %s found instead.", gettype($arguments[0])));
			//check istance type
			if (!is_object($arguments[1]))
				throw new \InvalidArgumentException(sprintf("MethodInvoke: A value of type object was expected but %s found instead.", gettype($arguments[1])));
			$method = $arguments[0];
			$instance = $arguments[1];
			$parameters = array_slice($arguments, 2);
		}
		else {
			if (!is_object($arguments[0]))
				throw new \InvalidArgumentException(sprintf("MethodInvoke: A value of type object was expected but %s found instead.", gettype($arguments[0])));
			$method = $this->method;
			$instance = $arguments[0];
			$parameters = array_slice($arguments, 1);
		}

		//check method existence
		if (!method_exists($instance, $method)) {
			if (!method_exists($instance, '__call')) throw new \InvalidArgumentException(sprintf("MethodInvoke: Method '$method' was not found on instance of '%s'.", get_class($instance)));
			return call_user_func([$instance, '__call'], $method, $parameters);
		}

		//check method access and required parameters
		$rm = new \ReflectionMethod($instance, $method);
		if (!$rm->isPublic()) throw new \BadMethodCallException(sprintf("Method '%s' does not have public access.", $method));
		if ($rm->getNumberOfRequiredParameters() > count($parameters))
			throw new \BadMethodCallException(sprintf("Method '%s' expects at least %d argument(s).", $method, $rm->getNumberOfRequiredParameters()));
		return call_user_func_array(array($instance, $method), $parameters);
	}
}
?>