<?php
/*
 * Copyright (c) 2015 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.1.0
 * @ignore
 */
namespace Peach\DF\JsonCodec;

use Peach\Util\ArrayMap;
use Peach\DF\Utf8Codec;

/**
 * デコード対象の文字列とデコードオプションを持つクラスです.
 *
 * @ignore
 */
class Context
{
    /**
     * デコード対象の文字列を Unicode 符号点の配列に分解するための Utf8Codec です.
     *
     * @var Utf8Codec;
     */
    private $utf8Codec;

    /**
     * 出力方法をカスタマイズするためのオプションです.
     * @var ArrayMap
     */
    private $options;

    /**
     * decode 対象の Unicode 文字列 (Unicode 符号点の配列) です.
     * @var array
     */
    private $unicodeList;

    /**
     * メンバ変数 $text のバイト数です.
     * @var int
     */
    private $count;

    /**
     * 現在の index です.
     * @var int
     */
    private $index;

    /**
     * 現在の index が参照している文字です.
     * @var string
     */
    private $current;

    /**
     * 現在の行番号です. decode に失敗した際にエラーの発生場所を提示するために使用します.
     * @var int
     */
    private $row;

    /**
     * 現在の列番号です. decode に失敗した際にエラーの発生場所を提示するために使用します.
     * @var int
     */
    private $col;

    /**
     * 指定されたデコード対象文字列とデコードオプションを持つ Context インスタンスを構築します.
     *
     * @param string $text デコード対象文字列
     * @param ArrayMap $options デコードオプション
     */
    public function __construct($text, ArrayMap $options)
    {
        $this->utf8Codec   = new Utf8Codec();
        $this->unicodeList = $this->utf8Codec->decode($text);
        $this->options     = $options;
        $this->count       = count($this->unicodeList);
        $this->index       = 0;
        $this->row         = 1;
        $this->col         = 1;
        $this->current     = $this->computeCurrent();
    }

    /**
     * 指定されたオプションが ON かどうかを調べます.
     *
     * @param  int $code オプション (JsonCodec で定義されている定数)
     * @return bool      指定されたオプションが ON の場合は true, それ以外は false
     */
    public function getOption($code)
    {
        return $this->options->get($code, false);
    }

    /**
     * 次の文字が存在するかどうかを判定します.
     *
     * @return bool
     */
    public function hasNext()
    {
        return ($this->index < $this->count);
    }

    /**
     * この Context が現在指し示している 1 文字を計算します.
     * このメソッドは, このオブジェクトの現在位置 (行数・列数) をデバッグ出力する機能の都合により
     *  "\r\n" の文字列を 1 文字としてカウントします.
     *
     * @return string
     */
    private function computeCurrent()
    {
        if (!$this->hasNext()) {
            return null;
        }
        $index   = $this->index;
        $current = $this->encodeIndex($index);
        if ($current === "\r" && $this->encodeIndex($index + 1) === "\n") {
            return "\r\n";
        }
        return $current;
    }

    /**
     * 指定された Unicode 符号点を文字列に変換します.
     *
     * @param int $point
     * @return string
     */
    public function encodeCodepoint($point)
    {
        return $this->utf8Codec->encode($point);
    }

    /**
     * 指定された相対位置の Unicode 符号点を文字列に変換します.
     * @param int $index
     * @return string
     */
    private function encodeIndex($index)
    {
        return ($index < $this->count) ? $this->encodeCodepoint($this->unicodeList[$index]) : null;
    }

    /**
     * この Context が現在指し示している文字を返します.
     *
     * @return string
     */
    public function current()
    {
        return $this->current;
    }

    /**
     * この Context の現在位置の Unicode 符号点を返します.
     *
     * @return int 現在の文字の Unicode 符号点. もしも現在の文字が存在しない場合は null
     */
    public function currentCodePoint()
    {
        return $this->hasNext() ? $this->unicodeList[$this->index] : null;
    }

    /**
     * この Context が指し示す位置でデコードに失敗したことをあらわす DecodeException を返します.
     *
     * @param string $message
     * @return DecodeException
     */
    public function createException($message)
    {
        return new DecodeException("{$message} at line {$this->row}, column {$this->col}");
    }

    /**
     * index を 1 進めます. 次の文字を返します.
     * @return string
     */
    public function next()
    {
        static $breakCode = array("\r", "\n", "\r\n");
        if (!$this->hasNext()) {
            throw $this->createException("Cannnot read next");
        }
        $result = $this->current;
        if (in_array($result, $breakCode)) {
            $this->row++;
            $this->col = 1;
        } else {
            $this->col++;
        }
        $this->index += ($result === "\r\n") ? 2 : 1;
        $current = $this->computeCurrent();
        $this->current = $current;
        return $current;
    }

    /**
     * この Context の現在位置から, 指定された文字数分の文字列を返します.
     * @param  int $count
     * @return string
     */
    public function getSequence($count)
    {
        $result = $this->current;
        for ($i = 1; $i < $count; $i++) {
            $result .= $this->encodeIndex($this->index + $i);
        }
        return $result;
    }

    /**
     * 指定された文字数だけ index を進めます.
     * @param int $count 文字数
     */
    public function skip($count)
    {
        if ($this->count - $this->index < $count) {
            throw $this->createException("Cannot skip {$count} characters");
        }

        $this->index += $count;
        $this->current = $this->computeCurrent();
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa\Query
 * @author    Hong Zhang <phossa@126.com>
 * @copyright 2015 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa\Query\Clause;

/**
 * AliasTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     AliasInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait AliasTrait
{
    /**
     * subquery alias
     *
     * @var    string
     * @access protected
     */
    protected $alias;

    /**
     * {@inheritDoc}
     */
    public function alias(/*# string */ $alias)
    {
        $this->alias = $alias;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function hasAlias()/*#: bool */
    {
        return null !== $this->alias;
    }

    /**
     * {@inheritDoc}
     */
    public function getAlias()/*#: string */
    {
        // auto generate a random one
        if (!$this->hasAlias()) {
            $this->alias = substr(md5(microtime(true)),0,3);
        }
        return $this->alias;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: sicmouse
 * Date: 2018/9/1
 * Time: 下午7:08
 */

namespace DdvPhp\DdvRestfulApi\Middleware\Laravel;

use Closure;
use Illuminate\Http\Response;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use DdvPhp\DdvRestfulApi;
use DdvPhp\DdvRestfulApi\Lib\HttpRequestStream;
use Illuminate\Http\Request;
use DdvPhp\DdvRestfulApi\Interfaces\RequestInfo as RequestInfoInterface;

class RestfulApi
{
    /**
     * @param Request $request
     * @param Closure $next
     * @param null $guard
     * @return Response|mixed
     * @throws DdvRestfulApi\Exception\RequestParseError
     */
    public function handle(Request $request, Closure $next, $guard = null)
    {
        if (empty($request->ddvHttpRequestInfo) || (!($request->ddvHttpRequestInfo instanceof RequestInfoInterface))) {
            RequestInfo::createHttpRequestInfo($request);
        }
        if (!self::isRender($request)) {
            return $next($request);
        }

        $r = array(
            //错误识别码
            'errorId' => 'OK',
            //消息
            'message' => '',
            //代码
            'code' => 0,
            //数据
            'data' => null,
            //列表
            'lists' => array(),
            //分页
            'page' => null
        );

        /**
         * @var Response $response
         */
        $response = $next($request);
        if (isset($response->original)) {
            if (class_exists('DdvPhp\DdvPage')) {
                // 分页
                if (class_exists('Illuminate\Pagination\LengthAwarePaginator') && $response->original instanceof \Illuminate\Pagination\LengthAwarePaginator) {
                    $response->original = new \DdvPhp\DdvPage($response->original);
                }
                // 如果是\DdvPhp\DdvPage
                if ($response->original instanceof \DdvPhp\DdvPage) {
                    $response->original = $response->original->toArray();
                }
            }

            $content = $response->getContent();
            if (is_array($response->original)) {
                $r = array_merge($r, $response->original);
            } else if (is_string($response->original)) {
                try {
                    $r = array_merge($r, json_decode($response->original, true));
                } catch (\Exception $e) {
                    return $response;
                }
            } else {
                try {
                    $r = array_merge($r, json_decode((string)$response->original, true));
                } catch (\Exception $e) {
                    try {
                        $r = array_merge($r, json_decode((string)$content, true));
                    } catch (\Exception $e) {
                        if (!empty($response->original)) {
                            return $response;
                        }
                    }
                }
            }
        }
        if (empty($r)) {
            return $response;
        }

        if (empty($r['statusCode'])) {
            if (method_exists($response, 'getStatusCode')) {
                $r['statusCode'] = $response->getStatusCode();
            }
        }
        if (empty($r['errorId'])) {
            $r['errorId'] = empty($response->statusTexts[$r['statusCode']]) ? $r['message'] : $response->statusTexts[$r['statusCode']];
        }
        $r['data'] = empty($r['data']) ? (object)array() : $r['data'];
        $r['page'] = empty($r['page']) ? (object)array() : $r['page'];

        $statusCode = $r['statusCode'];
        if ($statusCode>= 600 || $statusCode < 100){
            $statusCode = 500;
        }

        $response->original = $r;
        $response->setStatusCode($statusCode, $r['message']);
        $response->setContent(json_encode($r));
        $response->header('content-type', 'application/json', true);
        return $response;
    }

    public static function isDebug()
    {
        $isDebug = defined('ENVIRONMENT') && ENVIRONMENT === 'development';
        $isDebug = $isDebug || (function_exists('config') && config('app.debug', false)) || (function_exists('env') && env('APP_DEBUG'));
        return $isDebug;
    }

    protected static function isHas($str, $find)
    {
        return strpos($str, $find) !== false;
    }

    /**
     * RenderByLaravel an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @return boolean
     */
    public static function isRender($request)
    {
        return true;
        $accept = $request->header('accept') ?? '';
        if (static::isHas($accept, 'json') || static::isHas($accept, 'api')) {
            return true;
        } else if (static::isHas($accept, 'html') || static::isHas($accept, 'xml') || static::isHas($accept, 'text')) {
            return false;
        } else if ($request->header('x-ddv-restful-api')) {
            return true;
        } else if ($request->header('authorization')) {
            foreach ($request->headers->keys() as $value) {
                if (static::isHas($accept, 'x-ddv-')) {
                    return true;
                }
            }
        }
        return false;
    }

    public static function convertExceptionToJsonResponse($exception)
    {
        $flattenException = FlattenException::create($exception);
        $code = $flattenException->getCode();
        if (method_exists($exception, 'getErrorId')) {
            $errorId = $exception->getErrorId();
        } else {
            $errorId = empty(Response::$statusTexts[$code]) ? 'UNKNOWN_ERROR' : Response::$statusTexts[$code];
        }
        if ($exception instanceof HttpExceptionInterface) {
            $statusCode = $flattenException->getStatusCode();
        } else if (isset(Response::$statusTexts[$code])) {
            $statusCode = $code;
        }
        if (empty($statusCode)) {
            $statusCode = empty($code) ? 500 : $code;
        }
        if (!isset(Response::$statusTexts[$code]) && $errorId) {
            $code = $statusCode;
            Response::$statusTexts[$statusCode] = $errorId;
            $statusCode = 500;
        }
        $r = [
            'statusCode' => $statusCode,
            'code' => $code,
            'errorId' => $errorId,
            'message' => $flattenException->getMessage()
        ];
        if (static::isDebug()) {
            $r['debug'] = [
                'type' => $flattenException->getClass(),
                'class' => $flattenException->getClass(),
                'line' => $flattenException->getLine(),
                'file' => $flattenException->getFile(),
                'trace' => $flattenException->getTrace(),
                'isError' => $exception instanceof \ErrorException,
                'isIgnoreError' => false,
            ];
        }
        if (method_exists($exception, 'getResponseData')) {
            $r = array_merge($exception->getResponseData(), $r);
        }

        if ($statusCode>= 600 || $statusCode < 100){
            $statusCode = 500;
        }

        $response = new Response();
        $response->setStatusCode($statusCode, $errorId);
        foreach ($flattenException->getHeaders() as $key => $values) {
            $response->headers->set($key, $values);
        }
        $response->setContent($r);
        return $response;
    }

}


<?php
/**
 * AnimeDb package.
 *
 * @author    Peter Gribanov <info@peter-gribanov.ru>
 * @copyright Copyright (c) 2014, Peter Gribanov
 * @license   http://opensource.org/licenses/MIT
 */

namespace AnimeDb\Bundle\CacheTimeKeeperBundle\Service;

use AnimeDb\Bundle\CacheTimeKeeperBundle\Service\CacheKeyBuilder\EtagHasherInterface;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\HttpFoundation\Response;

class CacheKeyBuilder
{
    /**
     * @var string
     */
    const IDENTIFIER_SEPARATOR = '|';

    /**
     * @var string
     */
    const IDENTIFIER_PREFIX = ':';

    /**
     * @var EtagHasherInterface
     */
    protected $etag_hasher;

    /**
     * @var Registry|null
     */
    protected $doctrine;

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

    /**
     * @param Registry $doctrine
     *
     * @return CacheKeyBuilder
     */
    public function setDoctrine(Registry $doctrine)
    {
        $this->doctrine = $doctrine;

        return $this;
    }

    /**
     * @param object $entity
     *
     * @return string|null
     */
    public function getEntityAlias($entity)
    {
        if (!($this->doctrine instanceof Registry)) {
            return null;
        }

        $class = get_class($entity);

        $namespaces = $this
            ->doctrine
            ->getManager()
            ->getConfiguration()
            ->getEntityNamespaces();

        foreach ($namespaces as $ns_alias => $ns) {
            if (strpos($class, $ns) === 0) {
                return $ns_alias.':'.ltrim(str_replace($ns, '', $class), '\\');
            }
        }

        return null;
    }

    /**
     * @param object $entity
     *
     * @return string|null
     */
    public function getEntityIdentifier($entity)
    {
        if (!($this->doctrine instanceof Registry)) {
            return null;
        }

        $ids = $this
            ->doctrine
            ->getManager()
            ->getClassMetadata(get_class($entity))
            ->getIdentifierValues($entity);

        return $ids ? self::IDENTIFIER_PREFIX.implode(self::IDENTIFIER_SEPARATOR, $ids) : null;
    }

    /**
     * @param Response $response
     *
     * @return string
     */
    public function getEtag(Response $response)
    {
        return $this->etag_hasher->hash($response);
    }
}


<?php

namespace AscensoDigital\PerfilBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * Created by PhpStorm.
 * User: claudio
 * Date: 20-01-16
 * Time: 19:18
 */
class ADPerfilExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritDoc}
     * @throws \Exception
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $config = $this->processConfiguration(new Configuration(), $configs);
        $allConfig=$this->loadBundleFiltros($config);
        $container->setParameter('ad_perfil.config', $allConfig);

        $container->setParameter('ad_perfil.perfil_class',$config['perfil_class']);
        $container->setParameter('ad_perfil.session_name',$config['session_name']);
        $container->setParameter('ad_perfil.route_redirect',$config['route_redirect']);

        $container->setParameter('ad_perfil.navegacion.homepage_route',$config['navegacion']['homepage_route']);
        $container->setParameter('ad_perfil.navegacion.homepage_name',$config['navegacion']['homepage_name']);
        $container->setParameter('ad_perfil.navegacion.homepage_icono',$config['navegacion']['homepage_icono']);
        $container->setParameter('ad_perfil.navegacion.homepage_color',$config['navegacion']['homepage_color']);
        $container->setParameter('ad_perfil.navegacion.homepage_title',$config['navegacion']['homepage_title']);
        $container->setParameter('ad_perfil.navegacion.homepage_subtitle',$config['navegacion']['homepage_subtitle']);

        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }

    public function getAlias()
    {
        return 'ad_perfil';
    }

    private function loadBundleFiltros($config){
        $filtro_permiso=[
            'type' => 'Symfony\Bridge\Doctrine\Form\Type\EntityType',
            'table_alias' => 'adp_prm',
            'field' => 'id',
            'operator' => 'in',
            'query_builder_perfil' => false,
            'query_builder_user' => false,
            'query_builder_method' => 'getQueryBuilderOrderNombre',
            'options' => [
                'label' => 'Permiso',
                'class' => 'AscensoDigital\PerfilBundle\Entity\Permiso',
                'multiple' => true
            ]];
        $config['filtros']['adperfil_permiso']=$filtro_permiso;

        $filtro_perfil=[
            'type' => 'Symfony\Bridge\Doctrine\Form\Type\EntityType',
            'table_alias' => $config['perfil_table_alias'],
            'field' => 'id',
            'operator' => 'in',
            'query_builder_perfil' => true,
            'query_builder_user' => false,
            'query_builder_method' => 'getQueryBuilderOrderRole',
            'options' => [
                'label' => 'Perfil',
                'class' => $config['perfil_class'],
                'multiple' => true
            ]];
        $config['filtros']['adperfil_perfil']=$filtro_perfil;
        return $config;
    }

    /**
     * Allow an extension to prepend the extension configurations.
     *
     * @param ContainerBuilder $container
     * @throws \Exception
     */
    public function prepend(ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('ad_perfil.easyadmin.yml');
    }
}


<?php

namespace AscensoDigital\PerfilBundle\Command;

use AscensoDigital\PerfilBundle\Entity\PerfilXPermiso;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class AsociarSuperAdminCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('adperfil:permiso:super-admin')
            ->setDescription('Asocia los permisos para configurar el sistema al perfil del argumento')
            ->addArgument('perfil_id',InputArgument::REQUIRED,'Id del perfil que podrá configurar el sistema');
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $perfilManager=$this->getContainer()->get('ad_perfil.perfil_manager');
        $perfil=$perfilManager->find($input->getArgument('perfil_id'));
        if(is_null($perfil)){
            throw new \RuntimeException('El perfil ingresado no esta registrado en nuestra base de datos');
        }
        $em=$this->getContainer()->get('doctrine')->getManager();
        $permisos=$em->getRepository('ADPerfilBundle:Permiso')->findByNombreParcial('ad_perfil-');
        foreach ($permisos as $permiso) {
            /** @var PerfilXPermiso $pxp */
            $pxp=$em->getRepository('ADPerfilBundle:PerfilXPermiso')->findOneBy(['perfil' => $perfil->getId(), 'permiso' => $permiso->getId()]);
            if(!$pxp){
                $pxp= new PerfilXPermiso();
                $pxp->setPermiso($permiso)
                    ->setPerfil($perfil)
                    ->setAcceso(true);
            }
            else {
                $pxp->setAcceso(true);
            }
            $em->persist($pxp);
        }
        $em->flush();
    }
}


<?php

namespace zauberfisch\NamespaceTemplates\Form;

use zauberfisch\NamespaceTemplates\View\SSViewer;

class CheckboxSetField extends \CheckboxSetField {
	/**
	 * Returns an array of templates to use for rendering {@link FieldHolder}.
	 *
	 * @return array
	 */
	public function getTemplates() {
		return $this->__templates($this->getTemplate());
	}

	/**
	 * Returns an array of templates to use for rendering {@link FieldHolder}.
	 *
	 * @return array
	 */
	public function getFieldHolderTemplates() {
		return $this->__templates(
			$this->getFieldHolderTemplate(),
			'_holder'
		);
	}

	/**
	 * Returns an array of templates to use for rendering {@link SmallFieldHolder}.
	 *
	 * @return array
	 */
	public function getSmallFieldHolderTemplates() {
		return $this->__templates(
			$this->getSmallFieldHolderTemplate(),
			'_holder_small'
		);
	}

	/**
	 * Generate an array of class name strings to use for rendering this form field into HTML.
	 *
	 * @param string $customTemplate
	 * @param string $customTemplateSuffix
	 *
	 * @return array
	 */
	protected function __templates($customTemplate = null, $customTemplateSuffix = null) {
		$templates = SSViewer::get_templates_by_class($this->class, $customTemplateSuffix, \FormField::class);
		//$templates = \SSViewer::get_templates_by_class($this->class, '', __CLASS__);
		if (!$templates) {
			throw new \Exception("No template found for {$this->class}");
		}
		if($customTemplate) {
			array_unshift($templates, $customTemplate);
		}
		return $templates;
	}
}


<?php
namespace Yoanm\BehatUtilsExtension\Context\Initializer;

use Behat\Behat\Context\Context;
use Behat\Behat\Context\Initializer\ContextInitializer;
use Behat\Behat\EventDispatcher\Event\ExampleTested;
use Behat\Behat\EventDispatcher\Event\ScenarioTested;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Yoanm\BehatUtilsExtension\Context\BehatContextSubscriberInterface;

/**
 * Class BehatContextSubscriberInitializer
 * /!\ /!\ Contexts will be aware of Behat events only from ScenarioTested::BEFORE to ScenarioTested::AFTER only /!\ /!\
 *
 * This is due to the fact that context are (re)-created for each scenario or example
 * So contexts will have access to the followings event workflow (depending of the type of the scenario) :
 *
 * - Basic scenario :
 *      - ScenarioTested
 *          - BEFORE
 *          - AFTER_SETUP
 *      - BackgroundTested
 *          - BEFORE
 *          - AFTER_SETUP
 *      - StepTested
 *          - BEFORE
 *          - AFTER_SETUP
 *          - BEFORE_TEARDOWN
 *          - AFTER
 *      - BackgroundTested
 *          - BEFORE_TEARDOWN
 *          - AFTER
 *      - ScenarioTested
 *          - BEFORE_TEARDOWN
 *          - AFTER
 *
 * - Scenario outline :
 *      - ExampleTested
 *          - BEFORE
 *          - AFTER_SETUP
 *      - BackgroundTested
 *          - BEFORE
 *          - AFTER_SETUP
 *      - StepTested
 *          - BEFORE
 *          - AFTER_SETUP
 *          - BEFORE_TEARDOWN
 *          - AFTER
 *      - BackgroundTested
 *          - BEFORE_TEARDOWN
 *          - AFTER
 *      - ExampleTested
 *          - BEFORE_TEARDOWN
 *          - AFTER
 */
class BehatContextSubscriberInitializer implements ContextInitializer, EventSubscriberInterface
{
    /** @var EventDispatcherInterface */
    private $behatEventDispatcher;
    /** @var BehatContextSubscriberInterface[] */
    private $registeredContextList = [];

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

    /**
     * {@inheritdoc}
     */
    public function initializeContext(Context $context)
    {
        if (!$context instanceof BehatContextSubscriberInterface) {
            return;
        }
        // This method is called before each scenario/example, so (an instance of) context
        // is probably already registered
        // To avoid any problem, keep a trace of registered contexts instance
        // and remove it at scenario or example end
        // (See clearBehatContextSubscriber method)
        $this->behatEventDispatcher->addSubscriber($context);
        $this->registeredContextList[] = $context;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            ScenarioTested::AFTER => 'clearBehatContextSubscriber',
            ExampleTested::AFTER => 'clearBehatContextSubscriber',
        ];
    }

    /**
     * Clear contexts subscriber after each scenario/example
     */
    public function clearBehatContextSubscriber()
    {
        foreach ($this->registeredContextList as $context) {
            $this->behatEventDispatcher->removeSubscriber($context);
        }
        $this->registeredContextList = [];
    }
}


<?php

namespace Asoc\Dadatata\Tool;

use Asoc\Dadatata\ToolInterface;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\ProcessBuilder;

class Tesseract implements ToolInterface
{
    /**
     * @var
     */
    private $bin;
    /**
     * @var
     */
    private $version;

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

    /**
     * @param array $directories Additional directories to search for the executable
     *
     * @return mixed
     */
    public static function create($directories = [])
    {
        $finder = new ExecutableFinder();
        $bin    = $finder->find('tesseract', null, $directories);

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

        $tool = new static($bin);

        return $tool;
    }

    /**
     * @return ProcessBuilder|TesseractBuilder
     */
    public function getProcessBuilder()
    {
        $pb = new TesseractBuilder([$this->bin]);

        return $pb;
    }

    /**
     * @return null|false|string null = not available, false = failed to retrieve, string = version
     */
    public function getVersion()
    {
        if (null === $this->version) {
            $pb      = new TesseractBuilder([$this->bin]);
            $process = $pb->version()->getProcess();
            $process->run();
            if (preg_match('/tesseract\s([\d\.]+)/', $process->getErrorOutput(), $version)) {
                $this->version = $version[1];
            } else {
                $this->version = false;
            }
        }

        return $this->version;
    }

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


<?php

namespace SimplyCodedSoftware\IntegrationMessaging\Http;

use SimplyCodedSoftware\IntegrationMessaging\Config\ConfigurationException;
use SimplyCodedSoftware\IntegrationMessaging\Http\MessageConverter\StringMessageConverter;

/**
 * Class MessageConverterFactory
 * @package SimplyCodedSoftware\IntegrationMessaging\Http
 * @author Dariusz Gafka <dgafka.mail@gmail.com>
 */
class CompositeConverterFactory
{
    /**
     * @var array|HttpMessageConverter[]
     */
    private $httpMessageConverters;

    /**
     * MessageConverterFactory constructor.
     * @param array|HttpMessageConverter[] $httpMessageConverters
     */
    public function __construct(array $httpMessageConverters)
    {
        $this->httpMessageConverters = $httpMessageConverters;
    }

    /**
     * @param string[] $converterNames
     *
     * @return HttpMessageConverter
     * @throws ConfigurationException
     * @throws \SimplyCodedSoftware\IntegrationMessaging\MessagingException
     */
    public function getMessageConvertersWithNames(array $converterNames) : HttpMessageConverter
    {
        $messageConverters = [];

        foreach ($converterNames as $converterName) {
            $converter = $this->getConverterWithName($converterName);

            if (!$converter) {
                throw ConfigurationException::create("No converter found with name {$converterName}");
            }

            $messageConverters[] = $converter;
        }

        if ($this->canUseDefaultConverter($converterNames)) {
            $messageConverters[] = StringMessageConverter::createWithoutConfigurationVariables();
        }

        return CompositeHttpMessageConverter::createWithConverters($messageConverters);
    }

    /**
     * @param array $converterNames
     * @return bool
     */
    private function canUseDefaultConverter(array $converterNames): bool
    {
        return empty($converterNames);
    }

    /**
     * @param string $converterName
     * @return null|HttpMessageConverter
     */
    private function getConverterWithName(string $converterName)
    {
        foreach ($this->httpMessageConverters as $httpMessageConverter) {
            if ($httpMessageConverter->getConverterName() === $converterName) {
                return $httpMessageConverter;
                break;
            }
        }

        return null;
    }
}


<?php

namespace yii2module\cleaner\console\controllers;

use yii2lab\extension\console\base\Controller;
use yii2module\cleaner\domain\helpers\ClearHelper;
use yii2lab\extension\console\helpers\Output;
use yii2lab\extension\console\helpers\input\Select;

/**
 * Cleaner module.
 */
class DefaultController extends Controller
{

	/**
	 * Clear assets, runtime, cache, test output
	 */
	public function actionIndex($option = null)
	{
		// todo: вынести в конфиг домена
		$allNames = [
			'web/assets',
			'runtime',
			'runtime/cache',
			'tests/_output',
		];
		$answer = Select::display('Select objects', $allNames, 1);
		$result = ClearHelper::run($answer);
		if($result) {
			Output::items($result, "Clear completed: " . count($result) . " objects");
		} else {
			Output::block("Not fount object for clear!");
		}
	}

}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa\Query
 * @author    Hong Zhang <phossa@126.com>
 * @copyright 2015 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa\Query\Statement;

use Phossa\Query\Builder\BuilderInterface;

/**
 * ParameterAwareTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     ParameterAwareInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait ParameterAwareTrait
{
    /**
     * Binding values
     *
     * @var    array
     * @access protected
     */
    protected $bindings = [];

    /**
     * {@inheritDoc}
     */
    public function getBindings()/*# : array */
    {
        return $this->bindings;
    }

    /**
     * Flush bindings
     *
     * @return self
     * @access protected
     */
    protected function resetBindings()
    {
        $this->bindings = [];
        return $this;
    }

    /**
     * Replace placeholders in the SQL with '?' or real value
     *
     * @param  string $sql
     * @param  array $settings current settings
     * @return string replaced sql
     * @access protected
     */
    protected function bindValues(
        /*# string */ $sql,
        array $settings
    )/*# : string */ {
        $bindings = &$this->bindings;
        $escape   = $this->getEscapeCallable($settings['escapeFunction']);
        $params   = $this->getBuilder()->getPlaceholderMapping();

        // real function
        $function = function($v) use ($settings, &$bindings, $escape) {
            // positioend parameters
            if ($settings['positionedParam']) {
                $bindings[] = $v;
                return '?';

            // named parameters
            } elseif ($settings['namedParam'] && isset($v[0]) && ':' == $v[0]) {
                return $v;

            // use value, but NOT escaping int or float
            } elseif (is_numeric($v) && !is_string($v)) {
                return $v;

            // use value, but escape it @todo boolean?
            } else {
                return $escape($v);
            }
        };

        // replace placeholders with '?' or real value
        return preg_replace_callback(
            '/\b__PH_[0-9]++__\b/',
            function($m) use (&$params, $function) {
                return $function($params[$m[0]]);
            }, $sql);
    }

    /**
     * Get the database escape callable
     *
     * @param  null|callable $escapeFunction defult escape function
     * @return callable
     * @access protected
     */
    protected function getEscapeCallable($escapeFunction)/*# : callable */
    {
        if (null === $escapeFunction) {
            return function($v) {
                return "'" . str_replace("'", "\\'", (string) $v) . "'";
            };
        }
        return $escapeFunction;
    }

    /**
     * Generate and return a placeholder for the value
     *
     * @param  mixed $value
     * @return string the placeholder
     * @access protected
     */
    protected function getPlaceholder($value)/*# : string */
    {
        return $this->getBuilder()->generatePlaceholder($value);
    }

    /**
     * Return the builder
     *
     * @return BuilderInterface
     * @access public
     */
    abstract public function getBuilder()/*# : BuilderInterface */;
}


<?php
namespace Gmedia\PipedriveFinisher;

use Neos\Flow\Annotations as Flow;
use Neos\Form\Core\Model\AbstractFinisher as NeosFormAbstractFinisher;
use Neos\Form\Exception\FinisherException;
use Gmedia\PipedriveFinisher\Utility\Api as PipedriveApi;

abstract class AbstractFinisher extends NeosFormAbstractFinisher
{

  const OMITTED_OPTIONS = array(
    'testMode',
    'identifier',
  );

  protected function getIdentifier() {
    $scope = $this->scope;
    $customIdentifier = $this->parseOption('identifier');

    if($customIdentifier) {
      $identifier = "Pipedrive." . $customIdentifier;
    } else {
      $identifier = "Pipedrive." . $scope . "Finisher";
    }

    return $identifier;
  }

  /**
   * Runs the API request for the given data
   *
   * @return bool
   * @throws FinisherException
   */
  protected function callAPI($data) {
    $apiUtility = new PipedriveApi($this->apiEndpoint);
    $apiUtility->setData($data);

    $formState = $this->finisherContext->getFormRuntime()->getFormState();

    $response = $apiUtility->execute();

    if($response->data->id) {
      $formState->setFormValue($this->getIdentifier() . ".ID", $response->data->id);
      return true;
    } else {
      throw new FinisherException("Something went wrong while calling the API!");
    }
  }

}


<?php

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

namespace amylian\yii\base\common;

use yii\base\UnknownPropertyException;
use yii\base\UnknownMethodException;

/**
 *
 * @author andreas
 */
trait InstanceWrapperTrait
{

    /**
     * Returns the wrapped object
     *
     * @param bool $autoCreate Create the object if it has not been created
     * @return object|null Wrapped object or null if it has not been created
     */
    abstract function getWrappedInst($autoCreate = true): ?object;

    /**
     * Checks if the wrapped object has been created
     *
     * @return bool
     */
    public function isWrappedInstInitialized(): bool
    {
        return $this->getWrappedInst(false) !== null;
    }

    public function __get($propertyName)
    {

        $t = $this;
        try {
            if ($t instanceof \yii\base\Component) {
                return parent::__get($propertyName, $value);
            }
        } catch (UnknownPropertyException $exc1) {
            try {
                return $this->getPropertyFromWrappedInst($propertyName, $value);
            } catch (UnknownMethodException $exc2) {
                throw new UnknownMethodException($exc1->getMessage() . ' and ' . $exc2);
            }
        }
    }

    public function __set($propertyName, $value)
    {
        $t = $this;
        try {
            if ($t instanceof \yii\base\Component) {
                return parent::__set($propertyName, $value);
            }
        } catch (UnknownPropertyException $exc1) {
            try {
                $this->setPropertyInWrappedInst($propertyName, $value);
            } catch (UnknownMethodException $exc2) {
                throw new UnknownMethodException($exc1->getMessage() . ' and ' . $exc2);
            }
        }
    }

    public function __call($method, $args)
    {
        $t = $this;
        try {
            if ($t instanceof \yii\base\Component) {
                return parent::__call($method, $args);
            }
        } catch (UnknownMethodException $exc1) {
            try {
                $this->callMethodInWrappedInst($method, $args);
            } catch (UnknownMethodException $exc2) {
                throw new UnknownMethodException($exc1->getMessage() . ' and ' . $exc2);
            }
        }
    }

    /**
     * Calls the method in the wrapped instance
     *
     * This method is used internally in order to call a method
     * of the wrapped interface. Usually this function is called
     * by the magic function __call if the Wrapper does implement
     * the called method.
     *
     * @param type $method
     * @param type $args
     */
    public function callMethodInWrappedInst($method, $args)
    {
        $i = $this->getWrappedInst();
        if (method_exists($i, $method)) {
            return call_user_method_array($method, $i, $args);
        }
        throw new UnknownMethodException('Calling unknown method: ' . get_class($i) . "::$method()");
    }

    public function getPropertyFromWrappedInst($propertyName)
    {
        $w = $this->getWrappedInst();
        if (property_exists($w, $propertyName)) {
            return $w->$propertyName;
        } else {
            $fn = 'get' . ucfirst($propertyName);
            if (method_exists($w, $fn)) {
                return $w->$fn;
            } else {
                throw new UnknownPropertyException('Getting unknown property: ' . get_class($w) . '::' . $propertyName);
            }
        }
    }

    public function setPropertyInWrappedInst($propertyName, $value)
    {
        $w = $this->getWrappedInst();
        if (property_exists($w, $propertyName)) {
            $w->$propertyName = $value;
        } else {
            $fn = 'set' . ucfirst($propertyName);
            if (method_exists($w, $fn)) {
                $w->$fn($value);
            } else {
                throw new UnknownPropertyException('Setting unknown property: ' . get_class($w) . '::' . $propertyName);
            }
        }
    }

}


<?php

/*
 * This file is part of the YepsuaSmarTwigBundle.
 *
 * (c) Omar Yepez <omar.yepez@yepsua.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Yepsua\SmarTwigBundle\Form\Type;

use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class DatepickerType extends WidgetType {

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        parent::setDefaultOptions($resolver);

        $resolver->setDefaults(array(
            'widget'         => 'single_text',
            'widget_options'  => array(
              'showButtonPanel' => true,
              'changeMonth'=> true,
              'changeYear'=>  true
            ),
        ));

        $resolver->setAllowedValues(array(
            'input'     => array(
                'datetime',
                'string',
                'timestamp',
                'array',
            ),
            'widget'    => array(
                'single_text',
            ),
        ));

    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'date';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'ui_datepicker';
    }
}


<?php

namespace Dhii\Data\Object;

use InvalidArgumentException;
use Psr\Container\ContainerInterface;
use stdClass;
use ArrayAccess;

/**
 * Functionality for retrieval of the data store.
 *
 * @since [*next-version*]
 */
trait DataStoreAwareContainerTrait
{
    /**
     * The data store.
     *
     * @since [*next-version*]
     *
     * @var array|ArrayAccess|ContainerInterface|stdClass|null
     */
    protected $dataStore;

    /**
     * Retrieves a pointer to the data store.
     *
     * @since [*next-version*]
     *
     * @return array|ArrayAccess|stdClass|ContainerInterface|null The data store.
     */
    protected function _getDataStore()
    {
        return $this->dataStore;
    }

    /**
     * Assigns a data store to this instance.
     *
     * @since [*next-version*]
     *
     * @param array|ArrayAccess|stdClass|ContainerInterface|null $dataStore A container.
     *
     * @throws InvalidArgumentException If internal data store is invalid.
     */
    protected function _setDataStore($dataStore)
    {
        if (!is_null($dataStore)) {
            $dataStore = $this->_normalizeContainer($dataStore);
        }

        $this->dataStore = $dataStore;
    }

    /**
     * Normalizes a container.
     *
     * @since [*next-version*]
     *
     * @param array|ArrayAccess|stdClass|ContainerInterface $container The container to normalize.
     *
     * @throws InvalidArgumentException If the container is invalid.
     *
     * @return array|ArrayAccess|stdClass|ContainerInterface A readable container.
     */
    abstract protected function _normalizeContainer($container);
}


<?php
/*
 * Copyright (c) 2014 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.0.0
 */
namespace Peach\DT;
use Peach\Util\Map;

/**
 * 日時の値調整を行うクラスです.
 * このクラスは Date, Datetime, Timestamp の初期化処理のみで使用されることを
 * 想定しています.
 *
 * @ignore
 */
class FieldAdjuster
{
    /**
     * 調整対象のフィールドです.
     * @var int
     */
    private $key;

    /**
     * 調整対象フィールドの上位のフィールドです.
     * (例えば「時」に対する「日」、「秒」に対する「分」など
     * @var int
     */
    private $upperKey;

    /**
     * 調整対象フィールドがとりうる最小の値です.
     * @var int
     */
    private $min;

    /**
     * 調整対象フィールドがとりうる最大の値です.
     * @var int
     */
    private $max;

    /**
     * 新しい FieldAdjuster を構築します.
     *
     * @param int $key
     * @param int $upperKey
     * @param int $min
     * @param int $max
     * @codeCoverageIgnore
     */
    public function __construct($key, $upperKey, $min, $max)
    {
        $this->key      = $key;
        $this->upperKey = $upperKey;
        $this->min      = $min;
        $this->max      = $max;
    }

    /**
     * 指定された値の繰り上がり処理を行います.
     * この関数は Time::adjust() から呼び出されます.
     *
     * @param Map $fields 調整対象のフィールド一覧
     * @ignore
     */
    public function moveUp(Map $fields)
    {
        $key        = $this->key;
        $upperKey   = $this->upperKey;
        $max        = $this->max;
        $min        = $this->min;
        $field      = $fields->get($key);
        $upperField = $fields->get($upperKey);

        $range  = $max - $min + 1;
        $amount = intval(($field - $min) / $range);
        $fields->put($upperKey, $upperField + $amount);
        $fields->put($key, ($field - $min) % $range + $min);
    }

    /**
     * 指定された値の繰り下がり処理を行います.
     * この関数は Time::adjust() から呼び出されます.
     *
     * @param Map $fields 調整対象のフィールド一覧
     * @ignore
     */
    public function moveDown(Map $fields)
    {
        $key        = $this->key;
        $upperKey   = $this->upperKey;
        $max        = $this->max;
        $min        = $this->min;
        $field      = $fields->get($key);
        $upperField = $fields->get($upperKey);

        $range  = $max - $min + 1;
        $amount = intval(($min - $field - 1) / $range) + 1;
        $fields->put($upperKey, $upperField - $amount);
        $fields->put($key, $max - ($min - $field - 1) % $range);
    }
}


<?php

namespace HD\Api\Client;

use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zend\ServiceManager\ServiceManager;

use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\EventManager;
use Zend\Filter\Word\UnderscoreToCamelCase;

use HD\Api\Client\Http\ClientInterface;

class Client implements ServiceManagerAwareInterface, EventManagerAwareInterface
{
    /*
     * EventManager
     */
    protected $events;

    /**
     * Http\Client
     *
     * @var Client
     */
    private $httpClient;

    /**
     * Api Namespace
     */

    private $apiNamespace;

    /**
     * @var ServiceManager
     */
    protected $serviceManager;

    /**
     * Set Api Namespace
     * @param string $nnamespace
     */
    public function setApiNamespace($namespace)
    {
        $this->apiNamespace = $namespace;
    }

    public function getApiNamespace()
    {
        return $this->apiNamespace;
    }

    public function api($resource)
    {
        $filter = new UnderscoreToCamelCase();
        $resource = $filter->filter($resource);

        $em = $this->getEventManager();
        $em->trigger('api', $this);

        $service = $this->getServiceManager()->get($this->getApiNamespace() . '\Api\\' . $resource);
        $service->setClient($this);
        return $service;
    }

    /**
     * Authenticate a user for all next requests
     *
     * @param string      $tokenOrLogin  GitHub private token/username/client ID
     * @param null|string $password      GitHub password/secret
     * @param string $authMethod
     */
    public function authenticate($authMethod, $options)
    {
        $sm = $this->getServiceManager();
        $authListener = $sm->get($authMethod);
        $authListener->setOptions($options);

        $this->getHttpClient()->getEventManager()->attachAggregate($authListener);
    }

    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;
    }

    public function getServiceManager()
    {
        return $this->serviceManager;
    }

    /**
     * @return HttpClient
     */
    public function getHttpClient()
    {
        if (null === $this->httpClient) {
            $this->httpClient = $this->getServiceManager()->get('HD\Api\Client\HttpClient');
            $errorListener = $this->getServiceManager()->get('HD\Api\Client\Listener\Error');
            $eventManager = $this->httpClient->getEventManager();
            $eventManager->attachAggregate($errorListener);
        }
        return $this->httpClient;
    }

    /**
     * Set HttpClient
     * @param HttpClientInterface $httpClient
     */
    public function setHttpClient($httpClient)
    {
        $this->httpClient = $httpClient;
        return $this;
    }

    /**
     * Set Event Manager
     *
     * @param EventManagerInterface $events
     * @return Client
     */
    public function setEventManager(EventManagerInterface $events)
    {
        $events->setIdentifiers(array(
            __CLASS__,
            get_called_class(),
        ));
        $this->events = $events;
        return $this;
    }

    /**
     * Get Event Manager
     * @return EventManager
     */
    public function getEventManager()
    {
        if (null === $this->events) {
            $this->setEventManager(new EventManager());
        }
        return $this->events;
    }
}


<?php

namespace CoRex\Support\System;

use CoRex\Support\Str;
use CoRex\Support\System\Console\Style;
use CoRex\Support\System\Console\Table;

class Console
{
    /**
     * Test value used in unit testing.
     *
     * @var mixed
     */
    public static $testValue;

    private static $lineLength = 80;
    private static $silent = false;

    /**
     * Set silent.
     *
     * @param boolean $silent Default true.
     */
    public static function setSilent($silent = true)
    {
        self::$silent = $silent;
    }

    /**
     * Get silent.
     *
     * @return boolean
     */
    public static function getSilent()
    {
        return self::$silent;
    }

    /**
     * Set length of line.
     *
     * @param integer $lineLength
     */
    public static function setLineLength($lineLength)
    {
        self::$lineLength = $lineLength;
    }

    /**
     * Get length of line.
     *
     * @return integer
     */
    public static function getLineLength()
    {
        return self::$lineLength;
    }

    /**
     * Write messages.
     *
     * @param string|array $messages
     * @param string $style Default '' which means 'normal'.
     * @param integer $length Default 0 which means not fixed length. $messages NOT shortened.
     * @param string $suffix Default ''.
     */
    public static function write($messages, $style = '', $length = 0, $suffix = '')
    {
        if (self::$silent) {
            return;
        }
        if (!is_array($messages)) {
            $messages = [(string)$messages];
        }
        if (count($messages) > 0) {
            foreach ($messages as $message) {
                if ($length > 0) {
                    $message = str_pad($message, $length, ' ', STR_PAD_RIGHT);
                }
                print(Style::applyStyle($message, $style));
                if ($suffix != '') {
                    print($suffix);
                }
            }
        }
    }

    /**
     * Write messages with linebreak.
     *
     * @param string|array $messages
     * @param string $style Default '' which means normal.
     * @param integer $length Default 0 which means not fixed length.
     */
    public static function writeln($messages, $style = '', $length = 0)
    {
        self::write($messages, $style, $length, "\n");
    }

    /**
     * Write header (title + separator).
     *
     * @param string $title
     * @param string $style Default 'title'.
     */
    public static function header($title, $style = 'title')
    {
        $title = str_pad($title, self::$lineLength, ' ', STR_PAD_RIGHT);
        self::writeln($title, $style);
        self::separator('=');
    }

    /**
     * Write separator-line.
     *
     * @param string $character Default '-'.
     */
    public static function separator($character = '-')
    {
        self::writeln(str_repeat($character, self::$lineLength));
    }

    /**
     * Write info messages.
     *
     * @param string|array $messages
     * @param boolean $linebreak Default false.
     * @param integer $length Default 0 which means not fixed length.
     */
    public static function info($messages, $linebreak = true, $length = 0)
    {
        $separator = $linebreak ? "\n" : '';
        self::write($messages, 'info', $length, $separator);
    }

    /**
     * Write error messages.
     *
     * @param string|array $messages
     * @param boolean $linebreak Default false.
     * @param integer $length Default 0 which means not fixed length.
     */
    public static function error($messages, $linebreak = true, $length = 0)
    {
        $separator = $linebreak ? "\n" : '';
        self::write($messages, 'error', $length, $separator);
    }

    /**
     * Write comment messages.
     *
     * @param string|array $messages
     * @param boolean $linebreak Default false.
     * @param integer $length Default 0 which means not fixed length.
     */
    public static function comment($messages, $linebreak = true, $length = 0)
    {
        $separator = $linebreak ? "\n" : '';
        self::write($messages, 'comment', $length, $separator);
    }

    /**
     * Write warning messages.
     *
     * @param string|array $messages
     * @param boolean $linebreak Default false.
     * @param integer $length Default 0 which means not fixed length.
     */
    public static function warning($messages, $linebreak = true, $length = 0)
    {
        $separator = $linebreak ? "\n" : '';
        self::write($messages, 'warning', $length, $separator);
    }

    /**
     * Write title messages.
     *
     * @param string|array $messages
     * @param boolean $linebreak Default false.
     * @param integer $length Default 0 which means not fixed length.
     */
    public static function title($messages, $linebreak = true, $length = 0)
    {
        $separator = $linebreak ? "\n" : '';
        self::write($messages, 'title', $length, $separator);
    }

    /**
     * Write block messages.
     *
     * @param string|array $messages
     * @param string $style
     */
    public static function block($messages, $style)
    {
        if (is_string($messages)) {
            $messages = [$messages];
        }
        if (count($messages) > 0) {
            self::writeln(str_repeat(' ', self::$lineLength), $style);
            foreach ($messages as $message) {
                $message = ' ' . $message;
                while (strlen($message) < self::$lineLength) {
                    $message .= ' ';
                }
                self::writeln($message, $style);
            }
            self::writeln(str_repeat(' ', self::$lineLength), $style);
        }
    }

    /**
     * Ask question.
     *
     * @param string $question
     * @param mixed $defaultValue Default null.
     * @param boolean $secret Default false.
     * @return string
     */
    public static function ask($question, $defaultValue = null, $secret = false)
    {
        $value = '';
        while (trim($value) == '') {
            self::writeln('');
            self::write(' ' . $question, 'info');
            if ($defaultValue !== null) {
                self::write(' [');
                self::write($defaultValue, 'comment');
                self::write(']');
            }
            self::writeln(':');
            if ($secret) {
                self::write(' > ');
                if (self::$testValue === null) {
                    // @codeCoverageIgnoreStart
                    system('stty -echo');
                    $value = trim(fgets(STDIN));
                    system('stty echo');
                    // @codeCoverageIgnoreEnd
                } else {
                    $value = self::$testValue;
                }
            } else {
                if (self::$testValue === null) {
                    // @codeCoverageIgnoreStart
                    $value = readline(' > ');
                    // @codeCoverageIgnoreEnd
                } else {
                    $value = self::$testValue;
                }
            }
            if (trim($value) == '') {
                // @codeCoverageIgnoreStart
                $value = $defaultValue;
                // @codeCoverageIgnoreEnd
            }
            if (trim($value) == '') {
                // @codeCoverageIgnoreStart
                self::writeln('');
                self::block('[ERROR] A value is required', 'error');
                // @codeCoverageIgnoreEnd
            }
            self::writeln('');
        }
        return trim($value);
    }

    /**
     * Confirm question.
     *
     * @param string $question
     * @param boolean $allowShort Allow to use "y" / "n".
     * @param boolean $defaultValue Default false.
     * @return boolean
     */
    public static function confirm($question, $allowShort, $defaultValue = false)
    {
        $value = $defaultValue ? 'yes' : 'no';
        $value = self::ask($question . ' (yes/no)', $value);
        return $value == 'yes' || ($value == 'y' && $allowShort);
    }

    /**
     * Ask for secret.
     *
     * @param string $question
     * @return string
     */
    public static function secret($question)
    {
        return self::ask($question, null, true);
    }

    /**
     * List choices and ask for choice.
     *
     * @param string $question
     * @param array $choices
     * @param mixed $defaultValue Default null.
     * @return string
     */
    public static function choice($question, array $choices, $defaultValue = null)
    {
        $value = '';
        while (trim($value) == '') {

            // Write prompt.
            self::writeln('');
            self::write(' ' . $question, 'info');
            if ($defaultValue !== null) {
                // @codeCoverageIgnoreStart
                self::write(' [');
                self::write((string)$defaultValue, 'comment');
                self::write(']');
                // @codeCoverageIgnoreEnd
            }
            self::writeln(':');

            // Write choices.
            if (count($choices) > 0) {
                foreach ($choices as $index => $choice) {
                    self::write('  [');
                    self::write((string)($index + 1), 'comment');
                    self::writeln('] ' . $choice);
                }
            }

            // Input.
            if (self::$testValue === null) {
                // @codeCoverageIgnoreStart
                $value = readline(' > ');
                // @codeCoverageIgnoreEnd
            } else {
                $value = self::$testValue;
            }
            if (trim($value) == '') {
                // @codeCoverageIgnoreStart
                $value = $defaultValue;
                // @codeCoverageIgnoreEnd
            }
            if (!isset($choices[intval($value) - 1])) {
                // @codeCoverageIgnoreStart
                self::writeln('');
                self::block('[ERROR] Value "' . $value . '" is invalid', 'error');
                $value = '';
                // @codeCoverageIgnoreEnd
            } elseif (trim($value) == '') {
                // @codeCoverageIgnoreStart
                self::writeln('');
                self::block('[ERROR] A value is required', 'error');
                // @codeCoverageIgnoreEnd
            }
            self::writeln('');
        }
        return trim($value);
    }

    /**
     * Show table.
     *
     * @param array $rows
     * @param array $headers Default [].
     */
    public static function table(array $rows, array $headers = [])
    {
        $table = new Table();
        $table->setRows($rows);
        if (count($headers) > 0) {
            $table->setHeaders($headers);
        }
        $output = $table->render();
        self::writeln($output);
    }

    /**
     * Write words.
     *
     * @param array $words
     * @param string $style Default ''.
     * @param string $separator Default ', '.
     */
    public static function words(array $words, $style = '', $separator = ', ')
    {
        self::write(implode($separator, $words), $style);
    }

    /**
     * Throw error-message as exception.
     *
     * @param string $message
     * @throws \Exception
     */
    public static function throwError($message)
    {
        throw new \Exception(Style::applyStyle($message, 'error'));
    }

    /**
     * Properties.
     *
     * @param array $data
     * @param string $separator Default ':'.
     */
    public static function properties(array $data, $separator = ':')
    {
        $keys = array_keys($data);
        $maxLength = max(array_map('strlen', $keys));
        if (count($data) > 0) {
            foreach ($data as $key => $value) {
                $key = Str::padRight($key, $maxLength);
                self::write($key);
                self::write(' ');
                if (Str::length($separator) > 0) {
                    self::write($separator . ' ');
                }
                self::writeln($value);
            }
        }
    }
}


<?php
namespace Functional\Yoanm\BehatUtilsExtension\BehatContext;

use Behat\Behat\Context\Context;
use Behat\Behat\EventDispatcher\Event\AfterBackgroundTested;
use Behat\Behat\EventDispatcher\Event\AfterScenarioTested;
use Behat\Behat\EventDispatcher\Event\BackgroundTested;
use Behat\Behat\EventDispatcher\Event\BeforeOutlineTested;
use Behat\Behat\EventDispatcher\Event\BeforeScenarioTested;
use Behat\Behat\EventDispatcher\Event\ExampleTested;
use Behat\Behat\EventDispatcher\Event\GherkinNodeTested;
use Behat\Behat\EventDispatcher\Event\ScenarioTested;
use Behat\Behat\EventDispatcher\Event\StepTested;
use Behat\Gherkin\Node\BackgroundNode;
use Behat\Gherkin\Node\ExampleNode;
use Behat\Gherkin\Node\ScenarioNode;
use Behat\Gherkin\Node\StepNode;
use Behat\Testwork\EventDispatcher\Event\AfterTested;
use Behat\Testwork\EventDispatcher\Event\BeforeTested;
use Yoanm\BehatUtilsExtension\Context\BehatContextSubscriberInterface;
use Yoanm\BehatUtilsExtension\Subscriber\BehatStepLoggerSubscriber;

class BehatStepLoggerContext implements Context, BehatContextSubscriberInterface
{
    const BEHAT_STEP_LOG_LISTENER_SCENARIO_TAG = 'enable-behat-step-log-listener';

    /** @var bool */
    private $listenEvent = false;
    /** @var string */
    private $logFile;

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

    /** @var null|ScenarioNode|ExampleNode */
    private $currentScenario;
    /** @var null|BackgroundNode */
    private $currentBackground;
    /** @var null|StepNode */
    private $currentStep;

    /** @var bool */
    private $expectScenarioEndEventEntry = false;
    /** @var bool */
    private $expectExampleEndEventEntry = false;
    /** @var bool */
    private $expectBackgroundEndEventEntry = false;
    /** @var bool */
    private $expectStepEndEventEntry = false;

    /**
     * @Given /^A log entry must exist for current (?P<type>(?:|background|scenario|example)) start event$/
     */
    public function aLogEntryMustHaveExistedForCurrentSpecialNodeStartEvent($type)
    {
        if ($type == 'background') {
            $this->assertLogFileMatchBackground(true);
        } elseif ($type == 'scenario') {
            $this->assertLogFileMatchScenario(true);
        } elseif ($type == 'example') {
            $this->assertLogFileMatchExample(true);
        } else {
            throw new \Exception(sprintf('"%s" not handled !', $type));
        }
    }

    /**
     * @Then /^I will have a log entry regarding current (?P<type>(?:background|scenario|example)) end event$/
     */
    public function iWillHaveALogEntryRegardingNodeEndEvent($type)
    {
        switch ($type) {
            case 'background':
                $this->expectBackgroundEndEventEntry = true;
                break;
            case 'scenario':
                $this->expectScenarioEndEventEntry = true;
                break;
            case 'example':
                $this->expectExampleEndEventEntry = true;
                break;
            default:
                throw new \Exception(sprintf('"%s" not handled !', $type));
        }
    }

    /**
     * @Given A log entry must exist for current step start event and I will have the one regarding end event
     */
    public function aLogEntryMustExistForCurrentStepNodeStartEndEvent()
    {
        $this->assertLogFileMatchStep(true);
        $this->expectStepEndEventEntry = true;
    }

    /**
     * @param BeforeScenarioTested|BeforeOutlineTested $event
     */
    public function setUp(BeforeTested $event, $name)
    {
        if (in_array(
            self::BEHAT_STEP_LOG_LISTENER_SCENARIO_TAG,
            array_merge(
                $event->getScenario()->getTags(),
                $event->getFeature()->getTags()
            )
        )) {
            //Auto listen
            $this->listenEvent = true;
        }
    }

    /**
     * @param GherkinNodeTested $event
     */
    public function setNodeContext(GherkinNodeTested $event)
    {
        if ($this->listenEvent) {
            $isAfter = $event instanceof AfterTested;
            switch (true) {
                case $event instanceof ScenarioTested:
                case $event instanceof ExampleTested:
                    $this->currentScenario = $isAfter ? null : $event->getScenario();
                    break;
                case $event instanceof BackgroundTested:
                    $this->currentBackground = $isAfter ? null : $event->getBackground();
                    break;
                case $event instanceof StepTested:
                    $this->currentStep = $isAfter ? null : $event->getStep();
                    break;
            }
        }
    }

    /**
     * @param GherkinNodeTested $event
     * @param string            $name
     */
    public function checkEndEventExpectation(GherkinNodeTested $event, $name)
    {
        if ($this->listenEvent) {
            if ($event instanceof StepTested) {
                if (true === $this->expectStepEndEventEntry) {
                    $this->assertLogFileMatchStep(false);
                }
                $this->expectStepEndEventEntry = false; /* log entry checked so assertion ok */
            } elseif ($event instanceof BackgroundTested) {
                if (true === $this->expectBackgroundEndEventEntry) {
                    $this->assertLogFileMatchBackground(false);
                }
                $this->expectBackgroundEndEventEntry = false; /* log entry checked so assertion ok */
            } else {
                if (ExampleTested::AFTER === $name) {
                    if (true === $this->expectExampleEndEventEntry) {
                        $this->assertLogFileMatchExample(false);
                    }
                    $this->expectExampleEndEventEntry = false; /* log entry checked so assertion ok */
                } else {
                    if (true === $this->expectScenarioEndEventEntry) {
                        $this->assertLogFileMatchScenario(false);
                    }
                    $this->expectScenarioEndEventEntry = false; /* log entry checked so assertion ok */
                }
            }
        }
    }

    /**
     * @param GherkinNodeTested $event
     */
    public function tearDown(GherkinNodeTested $event)
    {
        if ($this->listenEvent) {
            // Check that all required expectations have been validated
            if ($event instanceof AfterScenarioTested) {
                \PHPUnit_Framework_Assert::assertFalse(
                    $this->expectScenarioEndEventEntry,
                    'Scenario end event entry expected but not checked !'
                );
                \PHPUnit_Framework_Assert::assertFalse(
                    $this->expectExampleEndEventEntry,
                    'Example end event entry expected but not checked !'
                );
            }

            if ($event instanceof AfterBackgroundTested
                || $event instanceof AfterScenarioTested
            ) {
                \PHPUnit_Framework_Assert::assertFalse(
                    $this->expectBackgroundEndEventEntry,
                    'Background end event entry expected but not checked !'
                );
            }

            // Following must be always true
            \PHPUnit_Framework_Assert::assertFalse(
                $this->expectStepEndEventEntry,
                'Step end event entry expected but not checked !'
            );
        }
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        // Set high priority to have it at beginning
        $hightPriority = 999999999;
        // Set low priority to have it at end
        $lowPriority = $hightPriority*-1;
        return [
            //Set and check at beginning
            ScenarioTested::BEFORE => [
                ['setUp', $hightPriority],
                ['setNodeContext', $hightPriority],
            ],
            ExampleTested::BEFORE => [
                ['setUp', $hightPriority],
                ['setNodeContext', $hightPriority],
            ],

            BackgroundTested::BEFORE => [
                ['setNodeContext', $hightPriority],
            ],
            StepTested::BEFORE => [
                ['setNodeContext', $hightPriority],
            ],

            StepTested::AFTER => [
                ['checkEndEventExpectation', $hightPriority],
                ['tearDown', $hightPriority],
                ['setNodeContext', $lowPriority],
            ],
            BackgroundTested::AFTER => [
                ['checkEndEventExpectation', $hightPriority],
                ['tearDown', $hightPriority],
                ['setNodeContext', $lowPriority],
            ],

            ScenarioTested::AFTER => [
                ['checkEndEventExpectation', $hightPriority],
                ['tearDown', $hightPriority],
                ['setNodeContext', $lowPriority],
            ],
            ExampleTested::AFTER => [
                ['checkEndEventExpectation', $hightPriority],
                ['tearDown', $hightPriority],
                ['setNodeContext', $lowPriority],
            ],
        ];
    }

    /**
     * @param string     $type
     * @param bool       $isStart
     * @param array|null $extra
     * @param string     $message
     */
    protected function assertLogFileMatch($type, $isStart, array $extra = null, $message = '')
    {
        if (is_array($extra)) {
            $key = array_keys($extra)[0];
            $value = reset($extra);
            $extra = sprintf(
                ' {"%s":%s,',
                $key,
                json_encode($value)
            );
        }
        \PHPUnit_Framework_Assert::assertRegExp(
            sprintf(
                '/^.*behatUtils\.DEBUG: \[BehatStepLoggerSubscriber\] \[%s\]\[%s\]%s.*$/m',
                $type,
                $isStart ? BehatStepLoggerSubscriber::HEADER_ACTION_IN : BehatStepLoggerSubscriber::HEADER_ACTION_OUT,
                preg_quote($extra, '/')
            ),
            file_get_contents($this->logFile),
            $message
        );
    }

    /**
     * @param bool $isStart
     */
    private function assertLogFileMatchStep($isStart)
    {
        $this->assertLogFileMatch(
            BehatStepLoggerSubscriber::HEADER_NODE_STEP,
            $isStart,
            ['text' => $this->currentStep->getText()],
            sprintf(
                '%s step event log entry not found !',
                $isStart ? 'Start' : 'End'
            )
        );
    }

    /**
     * @param bool $isStart
     */
    private function assertLogFileMatchBackground($isStart)
    {
        $this->assertLogFileMatch(
            BehatStepLoggerSubscriber::HEADER_NODE_BACKGROUND,
            $isStart,
            ['title' => $this->currentBackground->getTitle()],
            sprintf(
                '%s background event log entry not found !',
                $isStart ? 'Start' : 'End'
            )
        );
    }

    /**
     * @param bool $isStart
     */
    private function assertLogFileMatchScenario($isStart)
    {
        $this->assertLogFileMatch(
            BehatStepLoggerSubscriber::HEADER_NODE_SCENARIO,
            $isStart,
            ['title' => $this->currentScenario->getTitle()],
            sprintf(
                '%s scenario event log entry not found !',
                $isStart ? 'Start' : 'End'
            )
        );
    }

    /**
     * @param bool $isStart
     */
    private function assertLogFileMatchExample($isStart)
    {
        $this->assertLogFileMatch(
            BehatStepLoggerSubscriber::HEADER_NODE_EXAMPLE,
            $isStart,
            ['tokens' => $this->currentScenario->getTokens()],
            sprintf(
                '%s example event log entry not found !',
                $isStart ? 'Start' : 'End'
            )
        );
    }
}


<?php

namespace sndsgd;

use \sndsgd\fs\Dir;
use \sndsgd\fs\File;

/**
 * Filesystem utility methods
 */
class Fs
{
    const BYTES_PER_KB = 1024;
    const BYTES_PER_MB = 1048576;
    const BYTES_PER_GB = 1073741824;
    const BYTES_PER_TB = 1099511627776;
    const BYTES_PER_PB = 1125899906842624;
    const BYTES_PER_EB = 1152921504606846976;

    # bitmask values for use in sndsgd\fs\entity\EntityInterface::test()
    const EXISTS = 1;
    const DIR = 2;
    const FILE = 4;
    const READABLE = 8;
    const WRITABLE = 16;
    const EXECUTABLE = 32;

    /**
     * Format a bytesize into a human readable string
     * Note: precision will be ignored for results less than a KB
     *
     * @param int $bytes The number fo bytes to format
     * @param int $precision The number of decimal places to round to
     * @param string $point Decimal point
     * @param string $sep Thousands separator
     * @return string
     */
    public static function formatSize(
        int $bytes,
        int $precision = 0,
        string $point = ".",
        string $sep = ","
    ): string
    {
        $i = 0;
        $sizes = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB"];
        while ($bytes > 1024) {
            $bytes /= 1024;
            $i++;
        }

        if ($i === 0) {
            $precision = 0;
        }

        return number_format($bytes, $precision, $point, $sep)." ".$sizes[$i];
    }

    /**
     * Remove wonky characters from a path name
     *
     * @param string $name The basename to sanitize
     * @return string
     */
    public static function sanitizeName(string $name): string
    {
        $basename = basename($name);
        $dir = ($basename === $name) ? null : dirname($name);
        $basename = preg_replace("/[^a-zA-Z0-9-_.]/", "_", $basename);
        return ($dir === null) ? $basename : "$dir/$basename";
    }

    /**
     * Convenience method to get a directory instance with a normalized path
     *
     * @param string $path
     * @return \sndsgd\fs\entity\DirEntity
     */
    public static function dir(string $path): fs\entity\DirEntity
    {
        return (new fs\entity\DirEntity($path))->normalize();
    }

    /**
     * Convenience method to get a file instance with a normalized path
     *
     * @param string $path
     * @return \sndsgd\fs\entity\FileEntity
     */
    public static function file(string $path): fs\entity\FileEntity
    {
        return (new fs\entity\FileEntity($path))->normalize();
    }

    /**
     * Create an entity from an instance of \SplFileInfo
     *
     * @param \SplFileInfo $info
     * @return \sndsgd\fs\entity\EntityInterface
     */
    public static function createFromSplFileInfo(\SplFileInfo $info)
    {
        $realpath = $info->getRealPath();
        if ($info->isFile()) {
            return new fs\entity\FileEntity($realpath);
        }
        return new fs\entity\DirEntity($realpath);
    }
}


<?php

/**
 * @author      José Lorente <jose.lorente.martin@gmail.com>
 * @license     The MIT License (MIT)
 * @copyright   José Lorente
 * @version     1.0
 */

namespace jlorente\location\controllers;

use jlorente\location\db\State;
use jlorente\location\models\SearchState;
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\web\Response;

/**
 * StateController implements the CRUD actions for State model.
 *
 * @author José Lorente <jose.lorente.martin@gmail.com>
 */
class StateController extends CrudController
{

    use LocationControllerTrait;

    /**
     * Lists all State models.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SearchState(Yii::$app->request->get());
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
                    'searchModel' => $searchModel
                    , 'dataProvider' => $dataProvider
        ]);
    }

    /**
     * Displays a single State model.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
                    'model' => $this->findModel($id)
        ]);
    }

    /**
     * Creates a new State model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     *
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new State(Yii::$app->request->get());
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing State model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing State model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the State model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     *
     * @param integer $id
     * @return State the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = State::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * Gets a json list of the countries in the database.
     *
     * @return array
     */
    public function actionList()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $parents = $this->getDepDropParents();
        if (empty($parents[0])) {
            $output = [];
        } else {
            $searchModel = new SearchState(['country_id' => $parents[0]]);
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
            $dataProvider->setPagination(false);
            $dataProvider->getSort()->defaultOrder = ['name' => SORT_ASC];
            $output = ArrayHelper::toArray($dataProvider->getModels(), ['id', 'name']);
        }
        return [
            'output' => $output
        ];
    }

}


<?php

namespace Peyote;

/**
 * The JOIN clause builder.
 *
 * @package    Peyote
 * @author     Dave Widmer <dave@davewidmer.net>
 */
class Join implements \Peyote\Builder, \Peyote\Mixin
{
	/**
	 * @var array  The internal list of joins
	 */
	private $joins = array();

	/**
	 * @var array  The currently active join
	 */
	private $active_join = null;

	/**
	 * Add a join.
	 *
	 * @param  string $table  The table name
	 * @param  string $type   The type of join
	 * @return \Peyote\Join
	 */
	public function addJoin($table, $type = null)
	{
		$this->active_join = array($table, $type);
		return $this;
	}

	/**
	 * Creates an ON join.
	 *
	 * @throws \Peyote\Exception
	 *
	 * @param  string $column1  The column from the first table
	 * @param  string $op       The operator
	 * @param  string $column2  The column from the second table
	 * @return \Peyote\Join
	 */
	public function on($column1, $op, $column2)
	{
		if ($this->active_join === null)
		{
			throw new \Peyote\Exception("You need to start a join before calling \Peyote\Join::on()");
		}

		list($table, $type) = $this->active_join;
		$this->active_join = null;
		$this->joins[] = array("ON", $table, $type, $column1, $op, $column2);
		return $this;
	}

	/**
	 * Create a USING join.
	 *
	 * @throws \Peyote\Exception
	 *
	 * @param  string $column  The column to join on
	 * @return \Peyote\Join
	 */
	public function using($column)
	{
		if ($this->active_join === null)
		{
			throw new \Peyote\Exception("You need to start a join before calling \Peyote\Join::using()");
		}

		list($table, $type) = $this->active_join;
		$this->active_join = null;
		$this->joins[] = array("USING", $table, $type, $column);
		return $this;
	}

	/**
	 * Gets all of the methods that should be passed as "mixin" methods.
	 *
	 * @return array
	 */
	public function getMethods()
	{
		return array('on', 'using');
	}

	/**
	 * Compiles the query into raw SQL
	 *
	 * @return  string
	 */
	public function compile()
	{
		if (empty($this->joins))
		{
			return "";
		}

		$joins = array();
		foreach ($this->joins as $join)
		{
			if ($join[0] === "ON")
			{
				$joins[] = $this->compileOn($join);
			}
			else
			{
				$joins[] = $this->compileUsing($join);
			}
		}

		return join(" ", $joins);
	}

	/**
	 * Compiles an ON join.
	 *
	 * @param  array $join  The on join to compile
	 * @return string
	 */
	private function compileOn(array $join)
	{
		$sql = array();
		list($on, $table, $type, $c1, $op, $c2) = $join;

		if ($type !== null)
		{
			$sql[] = $type;
		}

		array_push($sql, "JOIN", $table, "ON", $c1, $op, $c2);
		return join(' ', $sql);
	}

	/**
	 * Compiles a JOIN USING clause
	 *
	 * @param  array $join  The join to compile
	 * @return string
	 */
	private function compileUsing(array $join)
	{
		$sql = array();
		list($using, $table, $type, $column) = $join;

		if ($type !== null)
		{
			$sql[] = $type;
		}

		array_push($sql, "JOIN", $table, "USING({$column})");
		return join(' ', $sql);
	}

}


<?php

namespace Spiffy\View\Twig;

use Spiffy\View;
use Twig_Environment;

class TwigResolver implements View\ViewResolver
{
    /**
     * @var Twig_Environment
     */
    protected $twig;

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

    /**
     * @param Twig_Environment $twig
     * @param string $suffix
     */
    public function __construct(Twig_Environment $twig, $suffix = '.twig')
    {
        $this->twig = $twig;
        $this->suffix = $suffix;
    }

    /**
     * {@inheritDoc}
     */
    public function resolve($nameOrModel)
    {
        if ($nameOrModel instanceof View\Model) {
            $nameOrModel = $nameOrModel->getTemplate();
        }
        return $this->twig->loadTemplate($nameOrModel . $this->suffix);
    }
}


<?php

/**
 * This file is part of the Minion package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @license MIT License
 */

namespace Minion;

/**
 * {@internal Tool used onl by Minion. May be but it is NOT RECOMMENDED to be used outside package }}
 *
 * Class Utils.
 *
 * @package Minion
 * @author Damian Szczerbiński <dszczer@gmail.com>
 */
abstract class Utils
{
    /**
     * @internal
     *
     * Check if template path is valid (template exists).
     *
     * @param \Twig_Environment $env      Twig environment
     * @param string            $template Template path
     *
     * @return bool
     */
    public static function templateExists(\Twig_Environment $env, $template) {
        try {
            $env->loadTemplate($template);
        } catch(\Twig_Error_Loader $err) {
            return false;
        } catch(\Twig_Error_Syntax $err) {
            return true;
        }

        return true;
    }

    /**
     * @internal
     *
     * Fix path to match runtime system requirements, for e.g. directory separator.
     *
     * @param string $path Path to fix
     *
     * @return string Fixed path
     */
    public static function fixPath($path) {
        // fix directory separators
        $fixed = \mb_ereg_replace('[\\\\\\/]+', DIRECTORY_SEPARATOR, $path);

        return \file_exists($fixed) ? \realpath($fixed) : $fixed;
    }

    /**
     * @internal
     *
     * @param string $path Absolute or relative path to template file
     * @param array  $data Array with data visible inside file scope
     *
     * @return string Compiled template content
     *
     * @throws \InvalidArgumentException Path is not valid or does not exist
     */
    public static function renderPhpTemplate($path, array $data = []) {
        \ob_start();
        \extract($data);
        $real = \realpath($path);

        if($real === false)
            throw new \InvalidArgumentException("Path '$path' is not valid or does not exist");

        include $real;

        return \ob_get_clean();
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa\Query
 * @author    Hong Zhang <phossa@126.com>
 * @copyright 2015 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa\Query\Clause;

/**
 * OrderByTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     OrderByInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait OrderByTrait
{
    /**
     * ORDER BYs
     *
     * @var    array
     * @access protected
     */
    protected $clause_orderby = [];

    /**
     * {@inheritDoc}
     */
    public function orderByDesc(
        /*# string */ $col,
        /*# bool */ $rawMode = false,
        /*# sting */ $desc = 'DESC'
    ) {
        $this->clause_orderby[] = [
            $rawMode ?: $this->isRaw($col), $col, $desc
        ];
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function orderByAsc(/*# string */ $col)
    {
        return $this->orderByDesc($col, false, 'ASC');
    }

    /**
     * {@inheritDoc}
     */
    public function orderByRaw(/*# string */ $orderby)
    {
        return $this->orderByDesc($orderby, true);
    }

    /**
     * Build ORDER BY
     *
     * @return array
     * @access protected
     */
    protected function buildOrderBy()/*# : array */
    {
        $result = [];
        foreach ($this->clause_orderby as $ord) {
            $result[] = $ord[0] ? $ord[1] :
                ($this->quote($ord[1]) . ' ' . $ord[2]);
        }
        return $result;
    }

    /* utilities from UtilityTrait */
    abstract protected function isRaw(/*# string */ $string)/*# : bool */;
    abstract protected function quote(/*# string */ $str)/*# : string */;
}


<?php
/*
 * Copyright (c) 2014 @trashtoy
 * https://github.com/trashtoy/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.0.0
 */
namespace Peach\DT;
use Peach\Util\Map;
use Peach\Util\ArrayMap;

/**
 * TIMESTAMP 型の時間オブジェクトです.
 * このクラスは年・月・日・時・分・秒のフィールドをサポートします.
 */
class Timestamp extends Datetime
{
    /**
     * 秒を表す整数です.
     * @var int
     */
    protected $second = 0;

    /**
     * 実行時の Timestamp オブジェクトを返します.
     *
     * @param Clock $clock 現在時刻を取得するための Clock オブジェクト
     * @return Timestamp   現在時刻をあらわす Timestamp
     */
    public static function now(Clock $clock = null)
    {
        if ($clock === null) {
            return self::now(DefaultClock::getInstance());
        }

        return $clock->getTimestamp();
    }

    /**
     * 指定されたテキストを解析して Timestamp オブジェクトに変換します.
     * $format が指定されていない場合は {@link W3cDatetimeFormat::getInstance}
     * を使って解析を行います.
     * ("YYYY-MM-DD hh:mm:ss" 形式の文字列を受理します.
     * 日付と時刻のセパレータは, 数字以外の ASCII 1 文字であれば何でも構いません.)
     *
     * @param  string    $text   変換対象の文字列
     * @param  Format    $format 変換に使用するフォーマット
     * @return Timestamp         変換結果
     */
    public static function parse($text, Format $format = null)
    {
        if (!isset($format)) {
            $format = W3cDatetimeFormat::getInstance();
        }
        return $format->parseTimestamp($text);
    }

    /**
     * 与えられた時刻を表現する Timestamp オブジェクトを構築します.
     *
     * @param int $year  年
     * @param int $month 月
     * @param int $date  日
     * @param int $hour  時
     * @param int $min   分
     * @param int $sec   秒
     */
    public function __construct($year, $month, $date, $hour, $min, $sec)
    {
        $fields = new ArrayMap();
        $fields->put(self::$YEAR,   intval($year));
        $fields->put(self::$MONTH,  intval($month));
        $fields->put(self::$DATE,   intval($date));
        $fields->put(self::$HOUR,   intval($hour));
        $fields->put(self::$MINUTE, intval($min));
        $fields->put(self::$SECOND, intval($sec));
        $this->init($fields);
    }

    /**
     * このオブジェクトの型 {@link Time::TYPE_TIMESTAMP} を返します.
     * @return int Time::TYPE_TIMESTAMP
     */
    public function getType()
    {
        return self::TYPE_TIMESTAMP;
    }

    /**
     * @ignore
     */
    protected function init(Map $fields)
    {
        parent::init($fields);
        $this->second = $fields->get(self::$SECOND);
    }

    /**
     * この時間と指定された時間を比較します.
     *
     * @param  Time $time 比較対象の時間
     * @return int        この時間のほうが過去の場合は負の値, 未来の場合は正の値, それ以外は 0
     * @ignore
     */
    protected function compareFields(Time $time)
    {
        $c = parent::compareFields($time);
        if (!isset($c) || $c != 0) {
            return $c;
        }
        $className = __CLASS__;
        if ($time instanceof $className) {
            return $this->second - $time->second;
        } else {
            $s = $time->get("second");
            return ($s !== $this->second) ? $this->second - $s : 0;
        }
    }

    /**
     * 時刻の不整合を調整します.
     * @ignore
     */
    protected function adjust(Map $fields)
    {
        parent::adjust($fields);
        $adjuster = $this->getAdjuster();
        $second   = $fields->get(self::$SECOND);
        if ($second < 0) {
            $adjuster->moveDown($fields);
        } else if (59 < $second) {
            $adjuster->moveUp($fields);
        } else {
            return;
        }

        $this->adjust($fields);
    }

    /**
     * (non-PHPdoc)
     * @see Time::newInstance()
     * @ignore
     */
    protected function newInstance(Map $fields)
    {
        $year  = $fields->get(self::$YEAR);
        $month = $fields->get(self::$MONTH);
        $date  = $fields->get(self::$DATE);
        $hour  = $fields->get(self::$HOUR);
        $min   = $fields->get(self::$MINUTE);
        $sec   = $fields->get(self::$SECOND);
        return new self($year, $month, $date, $hour, $min, $sec);
    }

    /**
     * @ignore
     */
    protected function handleFormat(Format $format)
    {
        return $format->formatTimestamp($this);
    }

    /**
     * このオブジェクトの時刻部分の文字列を "hh:mm:ss" 形式で返します.
     * @return string "hh:mm:ss" 形式の文字列
     */
    public function formatTime()
    {
        $format = parent::formatTime();
        $sec    = str_pad($this->second, 2, '0', STR_PAD_LEFT);
        return $format . ":" . $sec;
    }

    /**
     * このオブジェクトを Timestamp 型にキャストします.
     * 返り値はこのオブジェクトのクローンです.
     *
     * @return Timestamp このオブジェクトの Timestamp 表現
     */
    public function toTimestamp()
    {
        return new Timestamp($this->year, $this->month, $this->date, $this->hour, $this->minute, $this->second);
    }

    /**
     * このクラスのフィールドを調整するための FieldAdjuster を返します.
     * @return FieldAdjuster
     * @codeCoverageIgnore
     */
    private function getAdjuster()
    {
        static $adjuster = null;
        if ($adjuster === null) {
            $adjuster = new FieldAdjuster(self::$SECOND, self::$MINUTE, 0, 59);
        }
        return $adjuster;
    }
}


<?php

namespace RickySu\Tagcache\Adapter;

use RickySu\Tagcache\Adapter\TagcacheAdapter;

class File extends TagcacheAdapter
{
    protected $CacheBaseDir;

    public function __construct($NameSpace, $Options)
    {
        parent::__construct($NameSpace, $Options);
        $this->CacheBaseDir = $Options['cache_dir'];
    }

    protected function getCacheFile($Key)
    {
        $KeyHash = md5($this->buildKey($Key));
        $CachePath = $this->CacheBaseDir . DIRECTORY_SEPARATOR . 'FileCache' . DIRECTORY_SEPARATOR . $KeyHash{0} . DIRECTORY_SEPARATOR . $KeyHash{1} . DIRECTORY_SEPARATOR . $KeyHash{2};
        if (!file_exists($CachePath)) {
            mkdir($CachePath, 0777, true);
        }

        return "$CachePath/$KeyHash";
    }

    /**
     * Store Value to File.
     * @param string $Key
     */
    protected function setRaw($Key, $Val, $expire = 0)
    {
        $CacheFile = $this->getCacheFile($Key);

        return file_put_contents($CacheFile, serialize($Val)) > 0;
    }

    /**
     * Delete Value From File
     * @param  string  $Key
     * @return boolean
     */
    protected function deleteRaw($Key)
    {
        $CacheFile = $this->getCacheFile($Key);
        if (file_exists($CacheFile)) {
            return unlink($CacheFile);
        }

        return true;
    }

    /**
     * Read Value From File
     * @param string $Key
     */
    protected function getRaw($Key)
    {
        $CacheFile = $this->getCacheFile($Key);
        if (!file_exists($CacheFile)) {
            return false;
        }

        return unserialize(file_get_contents($CacheFile));
    }

}