<?php
/*
 * Copyright (c) 2016 @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.2.0
 */
namespace Peach\Http\Header;

use Peach\Util\Arrays;

/**
 * 1 行分の Set-Cookie ヘッダーをあらわすクラスです.
 */
class CookieItem
{
    /**
     * Cookie 名をあらわす文字列です.
     *
     * @var string
     */
    private $name;

    /**
     * Cookie 値をあらわす文字列です.
     *
     * @var string
     */
    private $value;

    /**
     * この cookie が持つ属性をあらわします.
     *
     * @var CookieOptions
     */
    private $options;

    /**
     * 指定されたキーおよび値の cookie を持つ CookieItem オブジェクトを構築します.
     *
     * @param string $name           cookie のキー
     * @param string $value          cookie の値
     * @param CookieOptions $options その cookie が持つ属性
     */
    public function __construct($name, $value, CookieOptions $options = null)
    {
        $this->name    = $name;
        $this->value   = $value;
        $this->options = $options;
    }

    /**
     * Set-Cookie ヘッダーの値 ("Set-Cookie: " に続く文字列部分) を書式化します.
     *
     * @return string Set-Cookie ヘッダーの値部分
     */
    public function format()
    {
        $data = $this->formatData();
        return ($this->options === null) ? $data : implode("; ", Arrays::concat($data, $this->options->formatOptions()));
    }

    /**
     * 出力の先頭の "key=value" 部分を書式化します.
     *
     * @return string "key=value" 形式の文字列
     */
    private function formatData()
    {
        $name  = rawurlencode($this->name);
        $value = rawurlencode($this->value);
        return "{$name}={$value}";
    }
}


<?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.2.0
 */
namespace Peach\Http;

use Peach\Http\Header\NoField;
use Peach\Http\Header\Status;
use Peach\Util\ArrayMap;

/**
 * HTTP レスポンスをあらわすクラスです.
 */
class Response
{
    /**
     * HeaderField 型オブジェクトを格納する ArrayMap です.
     * @var ArrayMap
     */
    private $headerList;

    /**
     * HTTP レスポンスのメッセージボディ部分を表す Body オブジェクトです.
     * @var Body
     */
    private $body;

    /**
     * 空の Response インスタンスを構築します.
     *
     * @codeCoverageIgnore
     */
    public function __construct()
    {
        $this->headerList = new ArrayMap();
        $this->body       = null;
    }

    /**
     * 指定された名前のヘッダーを取得します.
     * 存在しない場合は null を返します.
     *
     * @param  string $name ヘッダー名
     * @return HeaderField   指定されたヘッダーに該当する HeaderField オブジェクト
     */
    public function getHeader($name)
    {
        $header = $this->headerList->get(strtolower($name));
        return ($header instanceof HeaderField) ? $header : NoField::getInstance();
    }

    /**
     * この Response が持つヘッダーの一覧を取得します.
     * 返り値の配列に対する操作はこのオブジェクトに影響しません.
     *
     * @return HeaderField[] この Response にセットされている HeaderField の一覧
     */
    public function getHeaderList()
    {
        return $this->headerList->asArray();
    }

    /**
     * 指定されたヘッダーをこの Response に設定します.
     *
     * @param HeaderField $item
     */
    public function setHeader(HeaderField $item)
    {
        $name = strtolower($item->getName());
        $this->headerList->put($name, $item);
    }

    /**
     * 指定された名前の HeaderField が存在するかどうか調べます.
     * @param  string $name ヘッダー名
     * @return bool         指定された名前の HeaderField が存在する場合のみ true
     */
    public function hasHeader($name)
    {
        return $this->headerList->containsKey(strtolower($name));
    }

    /**
     * この Response が malformed (奇形) かどうかを判断します.
     *
     * @todo 実装する
     * @return bool このオブジェクトが表現する Response が malformed (奇形) と判定される場合に true, それ以外は false
     */
    public function isMalformed()
    {
        if (!$this->validateStatusHeader()) {
            return true;
        }

        return false;
    }

    /**
     * この Response の :status 擬似ヘッダーが適切かどうかを調べます.
     *
     * @return bool
     */
    private function validateStatusHeader()
    {
        if (!$this->hasHeader(":status")) {
            return false;
        }
        $status = $this->getHeader(":status");
        return ($status instanceof Status);
    }

    /**
     * 指定された Body オブジェクトをセットします.
     * @param Body $body
     */
    public function setBody(Body $body)
    {
        $this->body = $body;
    }

    /**
     * このオブジェクトにセットされている Body オブジェクトを返します.
     * セットされていない場合は null を返します.
     *
     * @return Body
     */
    public function getBody()
    {
        return $this->body;
    }
}


<?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;

/**
 * {@link http://www.w3.org/TR/NOTE-datetime W3CDTF} と時間オブジェクトの相互変換を行うフォーマットです.
 * 本来の W3CDTF は日付と時刻の間に "T" が入りますが (例: "YYYY-MM-DDThh:mm:ss")
 * このクラスは SQL などで用いられる慣用表現 (例: "YYYY-MM-DD hh:mm:ss") のパースもできます.
 *
 * parse メソッドは, 文字列の先頭が W3CDTF の書式にマッチするかどうかで妥当性をチェックします.
 * "2012-05-21T07:30:00" のような文字列は
 * parseDate, parseDatetime, parseTimestamp のすべてのメソッドで受け付けますが,
 * "2012-05-21" のような文字列は parseDate だけしか受け付けません.
 *
 * このクラスはタイムゾーンを適切に扱うことが出来ます.
 * parse 系メソッドでは, 時間オブジェクトに変換する際に内部のタイムゾーンに合わせて時刻を調整します.
 * 例えばシステム時刻が UTC+9 として, GMT の時間文字列 "2012-05-20T22:30Z" を parse した場合
 * 9 時間進ませた時間オブジェクト (new Datetime(2012, 5, 21, 7, 30) に等価) を生成します.
 *
 * 時間オブジェクトを書式化する際は, 出力用の時差に合わせた文字列を生成します.
 * 例えば内部のタイムゾーンが UTC+9, 出力用のタイムゾーンが UTC+5 に設定されているものとします.
 * この場合, 内部のタイムゾーンと出力用のタイムゾーンの時差が -4 時間となるため,
 * new Datetime(2012, 5, 21, 7, 30) の時間オブジェクトを書式化した結果は
 * "2012-05-21T03:30+5:00" となります.
 */
class W3cDatetimeFormat implements Format
{
    /**
     * タイムゾーンを扱うのみ TRUE となります
     * @var bool
     */
    private $usingTz;

    /**
     * システム時刻の時差です (単位は分)
     * @var int
     */
    private $internalOffset;

    /**
     * フォーマットの時差です (単位は分)
     * @var int
     */
    private $externalOffset;

    /**
     * 日付文字列のパターンです.
     * "YYYY-MM-DD" のような形式にマッチします.
     *
     * @var string
     */
    private static $datePattern = "[0-9]{4}[^0-9][0-9]{2}[^0-9][0-9]{2}";

    /**
     * タイムゾーンの文字列のパターンです. 以下の形式にマッチします.
     *
     * - "Z"
     * - "-hh:mm"
     * - "+hh:mm"
     * - 空文字列
     *
     * @var string
     */
    private static $timeZonePattern = "(Z|[\\-\\+][0-9]{2}:[0-9]{2})?";

    /**
     * 指定されたタイムゾーンの条件で, 新しいフォーマットを構築します.
     * タイムゾーンを扱わない場合は, コンストラクタの代わりに
     * {@link W3cDatetimeFormat::getInstance} を使って下さい.
     *
     * 引数 $externalOffset を指定することで,
     * 書式化する際のタイムゾーンの値を設定することが出来ます.
     * (デフォルトはシステム時刻のタイムゾーンとなります)
     * さらに $internalOffset を指定することで,
     * システム時刻のタイムゾーンとして任意の値を指定することも出来ます.
     *
     * $externalOffset と $internalOffset を省略した場合, デフォルト値としてシステム時刻の設定
     * ({@link Util::getTimeZoneOffset}) と同じ値が指定されます.
     * UTC+1 以上の時差を設定する場合は負の値,
     * UTC-1 以下の時差を設定する場合は正の値を指定してください.
     *
     * 以下に, $externalOffset と $internalOffset の組み合わせによる動作例を示します.
     *
     * <code>
     * // 書式・システム時刻共に UTC+9
     * $f1 = new W3cDatetimeFormat(-540, -540);
     *
     * // 書式は GMT, システム時刻は UTC+9
     * $f2 = new W3cDatetimeFormat(0,    -540);
     *
     * // 書式は UTC+9, システム時刻は GMT
     * $f3 = new W3cDatetimeFormat(-540,    0);
     *
     * // 2012-05-21T07:30 の時間オブジェクトを生成
     * $d = new Datetime(2012, 5, 21, 7, 30);
     * var_dump($d->format($f1)); // "2012-05-21T07:30+09:00"
     * var_dump($d->format($f2)); // "2012-05-20T22:30Z"      (UTC+9 の時刻を GMT として書式化)
     * var_dump($d->format($f3)); // "2012-05-21T16:30+09:00" (GMT の時刻を UTC+9 として書式化)
     * </code>
     *
     * @param int  $externalOffset フォーマットの時差 (単位は分, 省略した場合はシステム設定の値を使用)
     * @param int  $internalOffset システム時刻の時差 (単位は分, 省略した場合はシステム設定の値を使用)
     */
    public function __construct($externalOffset = null, $internalOffset = null)
    {
        // @codeCoverageIgnoreStart
        if ($externalOffset === false) {
            $this->usingTz        = false;
            $this->externalOffset = null;
            $this->internalOffset = null;
            return;
        }
        // @codeCoverageIgnoreEnd

        $this->usingTz        = true;
        $this->externalOffset = Util::cleanTimeZoneOffset($externalOffset);
        $this->internalOffset = Util::cleanTimeZoneOffset($internalOffset);
    }

    /**
     * デフォルトのインスタンスを返します.
     * このメソッドから生成されたオブジェクトは, parse の際にタイムゾーンを一切考慮しません.
     * また, 書式化する際にタイムゾーン文字列を付与しません.
     *
     * @return W3cDatetimeFormat タイムゾーンに対応しないインスタンス
     * @codeCoverageIgnore
     */
    public static function getInstance()
    {
        static $instance = null;
        if ($instance === null) {
            $instance = new self(false);
        }
        return $instance;
    }

    /**
     * "YYYY-MM-DD" 形式の文字列を解析します.
     *
     * @param  string $format 解析対象の文字列
     * @return Date           解析結果
     * @see Format::parseDate()
     */
    public function parseDate($format)
    {
        $dp = self::$datePattern;
        if (preg_match("/^{$dp}/", $format)) {
            $year  = substr($format, 0, 4);
            $month = substr($format, 5, 2);
            $date  = substr($format, 8, 2);
            return new Date($year, $month, $date);
        } else {
            throw $this->createFormatException($format, "YYYY-MM-DD");
        }
    }

    /**
     * "YYYY-MM-DDThh:mm" 形式の文字列を解析します.
     * 文字列の末尾にタイムゾーン (+hh:mm や -hh:mm など) を含む場合は, システム時刻への変換を行います.
     *
     * @param  string $format 解析対象の文字列
     * @return Datetime       解析結果
     * @see Format::parseDatetime()
     */
    public function parseDatetime($format)
    {
        $dp     = self::$datePattern;
        $tzp    = self::$timeZonePattern;
        $result = null;
        if (!preg_match("/^{$dp}[^0-9][0-9]{2}:[0-9]{2}{$tzp}/", $format, $result)) {
            throw $this->createFormatException($format, "YYYY-MM-DD hh:mm[timezone]");
        }

        $year   = substr($format, 0,  4);
        $month  = substr($format, 5,  2);
        $date   = substr($format, 8,  2);
        $hour   = substr($format, 11, 2);
        $min    = substr($format, 14, 2);
        $obj    = new Datetime($year, $month, $date, $hour, $min);
        return ($this->usingTz && isset($result[1])) ?
            $this->adjustFromParse($obj, $result[1]) : $obj;
    }

    /**
     * "YYYY-MM-DDThh:mm:ss" 形式の文字列を解析します.
     *
     * @param  string $format 解析対象の文字列
     * @return Timestamp      解析結果
     * @see Format::parseTimestamp()
     */
    public function parseTimestamp($format)
    {
        $dp     = self::$datePattern;
        $tzp    = self::$timeZonePattern;
        $result = null;
        if (!preg_match("/^{$dp}[^0-9][0-9]{2}:[0-9]{2}:[0-9]{2}{$tzp}/", $format, $result)) {
            throw $this->createFormatException($format, "YYYY-MM-DD hh:mm:ss");
        }

        $year   = substr($format, 0,  4);
        $month  = substr($format, 5,  2);
        $date   = substr($format, 8,  2);
        $hour   = substr($format, 11, 2);
        $min    = substr($format, 14, 2);
        $sec    = substr($format, 17, 2);
        $obj    = new Timestamp($year, $month, $date, $hour, $min, $sec);
        return ($this->usingTz && isset($result[1])) ?
            $this->adjustFromParse($obj, $result[1]) : $obj;
    }

    /**
     * 指定された時間オブジェクトを "YYYY-MM-DD" 形式の文字列に変換します.
     *
     * @param  Date $d 解析対象の Date オブジェクト
     * @return string  "YYYY-MM-DD" 形式の文字列
     * @see    Format::formatDate()
     */
    public function formatDate(Date $d)
    {
        return $d->__toString();
    }

    /**
     * 指定された時間オブジェクトを "YYYY-MM-DDThh:mm" 形式の文字列に変換します.
     * このインスタンスがタイムゾーンに対応している場合, 末尾にタイムゾーン文字列も付加します.
     *
     * @param  Datetime $d 変換対象の Datetime オブジェクト
     * @return string      "YYYY-MM-DDThh:mm" 形式の文字列
     * @see    Format::formatDatetime()
     */
    public function formatDatetime(Datetime $d)
    {
        $a = $this->adjustFromFormat($d, false);
        return $this->formatDate($a->toDate()) . "T" . $a->formatTime() . $this->formatTimezone();
    }

    /**
     * 指定された時間オブジェクトを "YYYY-MM-DDThh:mm:ss" 形式の文字列に変換します.
     * このインスタンスがタイムゾーンに対応している場合, 末尾にタイムゾーン文字列も付加します.
     *
     * @param  Timestamp $d 変換対象の Timestamp オブジェクト
     * @return string       "YYYY-MM-DDThh:mm:ss" 形式の文字列
     * @see    Format::formatTimestamp()
     */
    public function formatTimestamp(Timestamp $d)
    {
        return $this->formatDatetime($d);
    }

    /**
     * 指定された文字列が想定されたフォーマットでないことをあらわす
     * InvalidArgumentException を生成します.
     *
     * @param string $format
     * @param string $expected
     * @return \InvalidArgumentException
     */
    private function createFormatException($format, $expected)
    {
        return new \InvalidArgumentException("Illegal format({$format}). Expected: {$expected}");
    }

    /**
     * タイムゾーン文字列をパースして, 時差を分単位で返します.
     * NULL が指定された場合 (タイムゾーン文字列がなかった場合),
     * このオブジェクトに設定されている externalOffset の値を返します.
     *
     * @param  string $tz NULL, "Z", または "+h:mm", "-h:mm" 形式の文字列
     * @return int
     */
    private function parseTimezone($tz)
    {
        if ($tz === "Z") {
            return 0;
        }

        $coronIndex = strpos($tz, ":");
        $sign       = substr($tz, 0, 1);
        $hour       = substr($tz, 1, $coronIndex - 1);
        $minute     = substr($tz, $coronIndex + 1);
        $offset     = $hour * 60 + $minute;
        return ($sign === "-") ? $offset : - $offset;
    }

    /**
     * フォーマットのタイムゾーンと, 時間オブジェクトのタイムゾーンを元に
     * 指定された時間オブジェクトの補正処理を行います.
     *
     * @param  Datetime $d  補正対象の時間オブジェクト
     * @param  string   $tz タイムゾーン文字列
     * @return Datetime     補正結果の時間オブジェクト
     */
    private function adjustFromParse(Datetime $d, $tz)
    {
        $externalOffset = $this->parseTimezone($tz);
        return $d->add("minute", $externalOffset - $this->internalOffset);
    }

    /**
     * このオブジェクトがタイムゾーンを利用する場合は,
     * 引数の時間オブジェクトを補正した結果を返します.
     * タイムゾーンを利用しない場合は引数をそのまま返します.
     * このメソッドは各種 format メソッドから呼ばれます.
     *
     * @param  Datetime $d 補正対象の時間オブジェクト
     * @return Datetime    補正結果
     */
    private function adjustFromFormat(Datetime $d)
    {
        return $this->usingTz ? $d->add("minute", $this->internalOffset - $this->externalOffset) : $d;
    }

    /**
     * タイムゾーンを書式化します.
     * @return string
     */
    private function formatTimezone()
    {
        if (!$this->usingTz) {
            return "";
        }
        if ($this->externalOffset === 0) {
            return "Z";
        }

        $ext    = $this->externalOffset;
        $format = (0 < $ext) ? "-" : "+";
        $offset = abs($ext);
        $hour   = intval($offset / 60);
        $minute = intval($offset % 60);
        $format .= str_pad($hour,   2, '0', STR_PAD_LEFT);
        $format .= ':';
        $format .= str_pad($minute, 2, '0', STR_PAD_LEFT);
        return $format;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: claudio
 * Date: 05-04-16
 * Time: 11:01
 */

namespace AscensoDigital\PerfilBundle\DataFixtures\ORM;

use AscensoDigital\PerfilBundle\Entity\ReporteCriterio;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;

class LoadReporteCriterioData extends Fixture
{

    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $periodo= $manager->getRepository('ADPerfilBundle:ReporteCriterio')->findOneBy(['nombre' => 'periodo']);
        if(!$periodo) {
            $periodo = new ReporteCriterio();
            $periodo->setNombre('periodo')
                ->setTitulo('Período');
            $manager->persist($periodo);
        }
        $this->setReference('rpc-periodo', $periodo);
        $manager->flush();
    }
}


<?php

namespace Asoc\Dadatata;

use Asoc\Dadatata\Exception\FailedToGenerateVariantException;
use Asoc\Dadatata\Exception\FilterDoesNotSupportInputException;
use Asoc\Dadatata\Exception\NoFilterDefinedForVariantException;
use Asoc\Dadatata\Filter\OptionsInterface;
use Asoc\Dadatata\Model\ThingInterface;

class AggregateVariator implements VariatorInterface
{
    /**
     * @var VariatorInterface[]
     */
    private $variators;

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

    public function generate(ThingInterface $thing, $variant, $sourcePath, OptionsInterface $options = null)
    {
        foreach ($this->variators as $variator) {
            if (!$variator->hasSupportFor($variant)) {
                continue;
            }

            try {
                return $variator->generate($thing, $variant, $sourcePath, $options);
            } catch (FilterDoesNotSupportInputException $e) {
                // intenionally silenced, we try the next variator
            } catch (FailedToGenerateVariantException $e) {
                // intenionally silenced, we try the next variator
            } catch (NoFilterDefinedForVariantException $e) {
                // intenionally silenced, we try the next variator
            }
        }

        throw new FailedToGenerateVariantException('None of the variators were able to generate the requested variant');
    }

    /**
     * @return array
     */
    public function getSupportedVariants()
    {
        $supported = [];
        foreach ($this->variators as $variator) {
            $supported = array_merge($supported, $variator->getSupportedVariants());
        }

        return $supported;
    }

    /**
     * @param string $variant Variant name
     *
     * @return bool
     */
    public function hasSupportFor($variant)
    {
        foreach ($this->variators as $variator) {
            if ($variator->hasSupportFor($variant)) {
                return true;
            }
        }

        return false;
    }
}


<?php

/**
 * This file is part of Sylex project.
 *
 *  (c) Саша Стаменковић <umpirsky@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylex;

use Silex\Application as SilexApplication;
use Silex\ServiceProviderInterface;

/**
 * Provides Sylex controller resolver.
 *
 * @author Саша Стаменковић <umpirsky@gmail.com>
 */
class ServiceProvider implements ServiceProviderInterface
{
    /**
     * {@inheritdoc}
     */
    public function register(SilexApplication $app)
    {
        $app['resolver'] = $app->share(function () use ($app) {
            return new ControllerResolver($app, $app['logger']);
        });
    }

    /**
     * {@inheritdoc}
     */
    public function boot(SilexApplication $app)
    {
    }
}


<?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;

/**
 * TableConstraintTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     TableConstraintInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait TableConstraintTrait
{
    use ColDefinitionTrait;

    /**
     * table constraints
     *
     * @var    array
     * @access protected
     */
    protected $tbl_constraint = [];

    /**
     * {@inheritDoc}
     */
    public function primaryKey(
        array $colNames,
        /*# string */ $extraClause = ''
    ) {
        $this->tbl_constraint['primary'] = [$colNames, $extraClause];
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function uniqueKey(array $colNames, /*# string */ $extraClause = '')
    {
        if (!isset($this->tbl_constraint['unique'])) {
            $this->tbl_constraint['unique'] = [];
        }
        $this->tbl_constraint['unique'][] = [$colNames, $extraClause];
        return $this;
    }

    /**
     * Create a constraint
     *
     * @param  string $string
     * @return self
     * @access public
     */
    public function constraint(/*# string */ $string)
    {
        if (!isset($this->tbl_constraint['other'])) {
            $this->tbl_constraint['other'] = [];
        }
        $this->tbl_constraint['other'][] = $string;
        return $this;
    }

    /**
     * Build table constraints
     *
     * @return array
     * @access protected
     */
    protected function buildTblConst()/*# : array */
    {
        $result = $this->buildCol();

        // primary
        if (isset($this->tbl_constraint['primary'])) {
            $p = $this->tbl_constraint['primary'];
            $result[] = 'PRIMARY KEY (' .
                join(', ', $this->quoteIndex($p[0])) . ')' .
                (empty($p[1]) ? '' : " $p[1]");
        }

        // unique
        if (isset($this->tbl_constraint['unique'])) {
            foreach ($this->tbl_constraint['unique'] as $uniq) {
                $result[] = 'UNIQUE (' .
                    join(', ', $this->quoteIndex($uniq[0])) . ')' .
                    (empty($uniq[1]) ? '' : " $uniq[1]");
            }
        }

        // other constraints
        if (isset($this->tbl_constraint['other'])) {
            foreach ($this->tbl_constraint['other'] as $const) {
                $result[] = $const;
            }
        }

        return $result;
    }

    /**
     * quote the index names in the array
     *
     * @param  array $cols
     * @return array
     * @access protected
     */
    protected function quoteIndex(array $cols)/*# : array */
    {
        $q = [];
        foreach ($cols as $col) {
            $q[] = $this->quoteLeading($col);
        }
        return $q;
    }

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


<?php

namespace Asoc\Dadatata\Filter\Zbar;

use Asoc\Dadatata\Exception\ProcessingFailedException;
use Asoc\Dadatata\Filter\FilterInterface;
use Asoc\Dadatata\Filter\OptionsInterface;
use Asoc\Dadatata\Model\ImageInterface;
use Asoc\Dadatata\Model\ThingInterface;
use Symfony\Component\Process\ProcessBuilder;

class Extract implements FilterInterface
{
    /**
     * @var string
     */
    private $bin;

    public function __construct($bin = '/usr/bin/zbarimg')
    {
        $this->bin = $bin;
    }

    /**
     * @param OptionsInterface $options
     */
    public function setOptions(OptionsInterface $options)
    {
    }

    /**
     * @param ThingInterface                              $thing
     * @param string                                      $sourcePath
     * @param \Asoc\Dadatata\Filter\OptionsInterface|null $options
     *
     * @throws \Asoc\Dadatata\Exception\ProcessingFailedException
     * @return array Paths to generated files
     */
    public function process(ThingInterface $thing, $sourcePath, OptionsInterface $options = null)
    {
        $tmpPath = tempnam(sys_get_temp_dir(), 'Dadatata');

        $pb = new ProcessBuilder(
            [
                $this->bin
            ]
        );
        $pb->add('--xml');
        $pb->add($sourcePath);
        $process = $pb->getProcess();

        $code = $process->run();
        if ($code !== 0) {
            throw ProcessingFailedException::create(
                'Failed to extract barcodes',
                $code,
                $process->getOutput(),
                $process->getErrorOutput()
            );
        }

        file_put_contents($tmpPath, $process->getOutput());

        return [$tmpPath];
    }

    /**
     * @param ThingInterface $thing
     *
     * @return boolean
     */
    public function canHandle(ThingInterface $thing)
    {
        return $thing instanceof ImageInterface;
    }
}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\caching\Cache;

/**
 * UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.
 *
 * UrlManager is configured as an application component in [[\yii\base\Application]] by default.
 * You can access that instance via `Yii::$app->urlManager`.
 *
 * You can modify its configuration by adding an array to your application config under `components`
 * as it is shown in the following example:
 *
 * ```php
 * 'urlManager' => [
 *     'enablePrettyUrl' => true,
 *     'rules' => [
 *         // your rules go here
 *     ],
 *     // ...
 * ]
 * ```
 *
 * @property string $baseUrl The base URL that is used by [[createUrl()]] to prepend to created URLs.
 * @property string $hostInfo The host info (e.g. "http://www.example.com") that is used by
 * [[createAbsoluteUrl()]] to prepend to created URLs.
 * @property string $scriptUrl The entry script URL that is used by [[createUrl()]] to prepend to created
 * URLs.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class UrlManager extends Component
{
    /**
     * @var boolean whether to enable pretty URLs. Instead of putting all parameters in the query
     * string part of a URL, pretty URLs allow using path info to represent some of the parameters
     * and can thus produce more user-friendly URLs, such as "/news/Yii-is-released", instead of
     * "/index.php?r=news/view&id=100".
     */
    public $enablePrettyUrl = false;
    /**
     * @var boolean whether to enable strict parsing. If strict parsing is enabled, the incoming
     * requested URL must match at least one of the [[rules]] in order to be treated as a valid request.
     * Otherwise, the path info part of the request will be treated as the requested route.
     * This property is used only when [[enablePrettyUrl]] is true.
     */
    public $enableStrictParsing = false;
    /**
     * @var array the rules for creating and parsing URLs when [[enablePrettyUrl]] is true.
     * This property is used only if [[enablePrettyUrl]] is true. Each element in the array
     * is the configuration array for creating a single URL rule. The configuration will
     * be merged with [[ruleConfig]] first before it is used for creating the rule object.
     *
     * A special shortcut format can be used if a rule only specifies [[UrlRule::pattern|pattern]]
     * and [[UrlRule::route|route]]: `'pattern' => 'route'`. That is, instead of using a configuration
     * array, one can use the key to represent the pattern and the value the corresponding route.
     * For example, `'post/<id:\d+>' => 'post/view'`.
     *
     * For RESTful routing the mentioned shortcut format also allows you to specify the
     * [[UrlRule::verb|HTTP verb]] that the rule should apply for.
     * You can do that  by prepending it to the pattern, separated by space.
     * For example, `'PUT post/<id:\d+>' => 'post/update'`.
     * You may specify multiple verbs by separating them with comma
     * like this: `'POST,PUT post/index' => 'post/create'`.
     * The supported verbs in the shortcut format are: GET, HEAD, POST, PUT, PATCH and DELETE.
     * Note that [[UrlRule::mode|mode]] will be set to PARSING_ONLY when specifying verb in this way
     * so you normally would not specify a verb for normal GET request.
     *
     * Here is an example configuration for RESTful CRUD controller:
     *
     * ```php
     * [
     *     'dashboard' => 'site/index',
     *
     *     'POST <controller:[\w-]+>s' => '<controller>/create',
     *     '<controller:[\w-]+>s' => '<controller>/index',
     *
     *     'PUT <controller:[\w-]+>/<id:\d+>'    => '<controller>/update',
     *     'DELETE <controller:[\w-]+>/<id:\d+>' => '<controller>/delete',
     *     '<controller:[\w-]+>/<id:\d+>'        => '<controller>/view',
     * ];
     * ```
     *
     * Note that if you modify this property after the UrlManager object is created, make sure
     * you populate the array with rule objects instead of rule configurations.
     */
    public $rules = [];
    /**
     * @var string the URL suffix used when in 'path' format.
     * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
     * This property is used only if [[enablePrettyUrl]] is true.
     */
    public $suffix;
    /**
     * @var boolean whether to show entry script name in the constructed URL. Defaults to true.
     * This property is used only if [[enablePrettyUrl]] is true.
     */
    public $showScriptName = true;
    /**
     * @var string the GET parameter name for route. This property is used only if [[enablePrettyUrl]] is false.
     */
    public $routeParam = 'r';
    /**
     * @var Cache|string the cache object or the application component ID of the cache object.
     * Compiled URL rules will be cached through this cache object, if it is available.
     *
     * After the UrlManager object is created, if you want to change this property,
     * you should only assign it with a cache object.
     * Set this property to false if you do not want to cache the URL rules.
     */
    public $cache = 'cache';
    /**
     * @var array the default configuration of URL rules. Individual rule configurations
     * specified via [[rules]] will take precedence when the same property of the rule is configured.
     */
    public $ruleConfig = ['class' => 'yii\web\UrlRule'];

    private $_baseUrl;
    private $_scriptUrl;
    private $_hostInfo;
    private $_ruleCache;

    /**
     * Initializes UrlManager.
     */
    public function init()
    {
        parent::init();

        if (!$this->enablePrettyUrl || empty($this->rules)) {
            return;
        }
        if (is_string($this->cache)) {
            $this->cache = Yii::$app->get($this->cache, false);
        }
        if ($this->cache instanceof Cache) {
            $cacheKey = __CLASS__;
            $hash = md5(json_encode($this->rules));
            if (($data = $this->cache->get($cacheKey)) !== false && isset($data[1]) && $data[1] === $hash) {
                $this->rules = $data[0];
            } else {
                $this->rules = $this->buildRules($this->rules);
                $this->cache->set($cacheKey, [$this->rules, $hash]);
            }
        } else {
            $this->rules = $this->buildRules($this->rules);
        }
    }

    /**
     * Adds additional URL rules.
     *
     * This method will call [[buildRules()]] to parse the given rule declarations and then append or insert
     * them to the existing [[rules]].
     *
     * Note that if [[enablePrettyUrl]] is false, this method will do nothing.
     *
     * @param array $rules the new rules to be added. Each array element represents a single rule declaration.
     * Please refer to [[rules]] for the acceptable rule format.
     * @param boolean $append whether to add the new rules by appending them to the end of the existing rules.
     */
    public function addRules($rules, $append = true)
    {
        if (!$this->enablePrettyUrl) {
            return;
        }
        $rules = $this->buildRules($rules);
        if ($append) {
            $this->rules = array_merge($this->rules, $rules);
        } else {
            $this->rules = array_merge($rules, $this->rules);
        }
    }

    /**
     * Builds URL rule objects from the given rule declarations.
     * @param array $rules the rule declarations. Each array element represents a single rule declaration.
     * Please refer to [[rules]] for the acceptable rule formats.
     * @return UrlRuleInterface[] the rule objects built from the given rule declarations
     * @throws InvalidConfigException if a rule declaration is invalid
     */
    protected function buildRules($rules)
    {
        $compiledRules = [];
        $verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
        foreach ($rules as $key => $rule) {
            if (is_string($rule)) {
                $rule = ['route' => $rule];
                if (preg_match("/^((?:($verbs),)*($verbs))\\s+(.*)$/", $key, $matches)) {
                    $rule['verb'] = explode(',', $matches[1]);
                    // rules that do not apply for GET requests should not be use to create urls
                    if (!in_array('GET', $rule['verb'])) {
                        $rule['mode'] = UrlRule::PARSING_ONLY;
                    }
                    $key = $matches[4];
                }
                $rule['pattern'] = $key;
            }
            if (is_array($rule)) {
                $rule = Yii::createObject(array_merge($this->ruleConfig, $rule));
            }
            if (!$rule instanceof UrlRuleInterface) {
                throw new InvalidConfigException('URL rule class must implement UrlRuleInterface.');
            }
            $compiledRules[] = $rule;
        }
        return $compiledRules;
    }

    /**
     * Parses the user request.
     * @param Request $request the request component
     * @return array|boolean the route and the associated parameters. The latter is always empty
     * if [[enablePrettyUrl]] is false. False is returned if the current request cannot be successfully parsed.
     */
    public function parseRequest($request)
    {
        if ($this->enablePrettyUrl) {
            $pathInfo = $request->getPathInfo();
            /* @var $rule UrlRule */
            foreach ($this->rules as $rule) {
                if (($result = $rule->parseRequest($this, $request)) !== false) {
                    return $result;
                }
            }

            if ($this->enableStrictParsing) {
                return false;
            }

            Yii::trace('No matching URL rules. Using default URL parsing logic.', __METHOD__);

            $suffix = (string) $this->suffix;
            if ($suffix !== '' && $pathInfo !== '') {
                $n = strlen($this->suffix);
                if (substr_compare($pathInfo, $this->suffix, -$n, $n) === 0) {
                    $pathInfo = substr($pathInfo, 0, -$n);
                    if ($pathInfo === '') {
                        // suffix alone is not allowed
                        return false;
                    }
                } else {
                    // suffix doesn't match
                    return false;
                }
            }

            return [$pathInfo, []];
        } else {
            Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
            $route = $request->getQueryParam($this->routeParam, '');
            if (is_array($route)) {
                $route = '';
            }

            return [(string) $route, []];
        }
    }

    /**
     * Creates a URL using the given route and query parameters.
     *
     * You may specify the route as a string, e.g., `site/index`. You may also use an array
     * if you want to specify additional query parameters for the URL being created. The
     * array format must be:
     *
     * ```php
     * // generates: /index.php?r=site/index&param1=value1&param2=value2
     * ['site/index', 'param1' => 'value1', 'param2' => 'value2']
     * ```
     *
     * If you want to create a URL with an anchor, you can use the array format with a `#` parameter.
     * For example,
     *
     * ```php
     * // generates: /index.php?r=site/index&param1=value1#name
     * ['site/index', 'param1' => 'value1', '#' => 'name']
     * ```
     *
     * The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
     *
     * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
     * as an absolute route.
     *
     * @param string|array $params use a string to represent a route (e.g. `site/index`),
     * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
     * @return string the created URL
     */
    public function createUrl($params)
    {
        $params = (array) $params;
        $anchor = isset($params['#']) ? '#' . $params['#'] : '';
        unset($params['#'], $params[$this->routeParam]);

        $route = trim($params[0], '/');
        unset($params[0]);

        $baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $this->getScriptUrl() : $this->getBaseUrl();

        if ($this->enablePrettyUrl) {
            $cacheKey = $route . '?' . implode('&', array_keys($params));

            /* @var $rule UrlRule */
            $url = false;
            if (isset($this->_ruleCache[$cacheKey])) {
                foreach ($this->_ruleCache[$cacheKey] as $rule) {
                    if (($url = $rule->createUrl($this, $route, $params)) !== false) {
                        break;
                    }
                }
            } else {
                $this->_ruleCache[$cacheKey] = [];
            }

            if ($url === false) {
                $cacheable = true;
                foreach ($this->rules as $rule) {
                    if (!empty($rule->defaults) && $rule->mode !== UrlRule::PARSING_ONLY) {
                        // if there is a rule with default values involved, the matching result may not be cached
                        $cacheable = false;
                    }
                    if (($url = $rule->createUrl($this, $route, $params)) !== false) {
                        if ($cacheable) {
                            $this->_ruleCache[$cacheKey][] = $rule;
                        }
                        break;
                    }
                }
            }

            if ($url !== false) {
                if (strpos($url, '://') !== false) {
                    if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) {
                        return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
                    } else {
                        return $url . $baseUrl . $anchor;
                    }
                } else {
                    return "$baseUrl/{$url}{$anchor}";
                }
            }

            if ($this->suffix !== null) {
                $route .= $this->suffix;
            }
            if (!empty($params) && ($query = http_build_query($params)) !== '') {
                $route .= '?' . $query;
            }

            return "$baseUrl/{$route}{$anchor}";
        } else {
            $url = "$baseUrl?{$this->routeParam}=" . urlencode($route);
            if (!empty($params) && ($query = http_build_query($params)) !== '') {
                $url .= '&' . $query;
            }

            return $url . $anchor;
        }
    }

    /**
     * Creates an absolute URL using the given route and query parameters.
     *
     * This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
     *
     * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
     * as an absolute route.
     *
     * @param string|array $params use a string to represent a route (e.g. `site/index`),
     * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
     * @param string $scheme the scheme to use for the url (either `http` or `https`). If not specified
     * the scheme of the current request will be used.
     * @return string the created URL
     * @see createUrl()
     */
    public function createAbsoluteUrl($params, $scheme = null)
    {
        $params = (array) $params;
        $url = $this->createUrl($params);
        if (strpos($url, '://') === false) {
            $url = $this->getHostInfo() . $url;
        }
        if (is_string($scheme) && ($pos = strpos($url, '://')) !== false) {
            $url = $scheme . substr($url, $pos);
        }

        return $url;
    }

    /**
     * Returns the base URL that is used by [[createUrl()]] to prepend to created URLs.
     * It defaults to [[Request::baseUrl]].
     * This is mainly used when [[enablePrettyUrl]] is true and [[showScriptName]] is false.
     * @return string the base URL that is used by [[createUrl()]] to prepend to created URLs.
     * @throws InvalidConfigException if running in console application and [[baseUrl]] is not configured.
     */
    public function getBaseUrl()
    {
        if ($this->_baseUrl === null) {
            $request = Yii::$app->getRequest();
            if ($request instanceof Request) {
                $this->_baseUrl = $request->getBaseUrl();
            } else {
                throw new InvalidConfigException('Please configure UrlManager::baseUrl correctly as you are running a console application.');
            }
        }

        return $this->_baseUrl;
    }

    /**
     * Sets the base URL that is used by [[createUrl()]] to prepend to created URLs.
     * This is mainly used when [[enablePrettyUrl]] is true and [[showScriptName]] is false.
     * @param string $value the base URL that is used by [[createUrl()]] to prepend to created URLs.
     */
    public function setBaseUrl($value)
    {
        $this->_baseUrl = rtrim($value, '/');
    }

    /**
     * Returns the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
     * It defaults to [[Request::scriptUrl]].
     * This is mainly used when [[enablePrettyUrl]] is false or [[showScriptName]] is true.
     * @return string the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
     * @throws InvalidConfigException if running in console application and [[scriptUrl]] is not configured.
     */
    public function getScriptUrl()
    {
        if ($this->_scriptUrl === null) {
            $request = Yii::$app->getRequest();
            if ($request instanceof Request) {
                $this->_scriptUrl = $request->getScriptUrl();
            } else {
                throw new InvalidConfigException('Please configure UrlManager::scriptUrl correctly as you are running a console application.');
            }
        }

        return $this->_scriptUrl;
    }

    /**
     * Sets the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
     * This is mainly used when [[enablePrettyUrl]] is false or [[showScriptName]] is true.
     * @param string $value the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
     */
    public function setScriptUrl($value)
    {
        $this->_scriptUrl = $value;
    }

    /**
     * Returns the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
     * @return string the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
     * @throws InvalidConfigException if running in console application and [[hostInfo]] is not configured.
     */
    public function getHostInfo()
    {
        if ($this->_hostInfo === null) {
            $request = Yii::$app->getRequest();
            if ($request instanceof \yii\web\Request) {
                $this->_hostInfo = $request->getHostInfo();
            } else {
                throw new InvalidConfigException('Please configure UrlManager::hostInfo correctly as you are running a console application.');
            }
        }

        return $this->_hostInfo;
    }

    /**
     * Sets the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
     * @param string $value the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
     */
    public function setHostInfo($value)
    {
        $this->_hostInfo = rtrim($value, '/');
    }
}


<?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 Yii;
use yii\filters\AccessControl;
use yii\filters\ContentNegotiator;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\web\Controller;

/**
 * Base controller class for all the backend module controllers.
 *
 * @author José Lorente <jose.lorente.martin@gmail.com>
 */
class CrudController extends Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'view', 'create', 'update', 'delete'],
                        'allow' => true,
                        'roles' => ['@']
                    ]
                    , [
                        'actions' => ['list']
                        , 'allow' => true
                        , 'roles' => ['@']
                    ]
                    , [
                        'actions' => ['list']
                        , 'allow' => true
                        , 'roles' => ['?']
                    ]
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ]
            , 'content' => [
                'class' => ContentNegotiator::className()
                , 'only' => ['list']
                , 'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                ]
            ]
        ];
    }

    /**
     * Get a filtered array of valid values set by depdrop.
     *
     * @return array
     */
    protected function getDepDropParents($post = 'depdrop_parents')
    {
        $parents = Yii::$app->request->post($post);
        $filteredParents = [];
        foreach ($parents as $key => $parent) {
            if (is_numeric($parent)) {
                $filteredParents[$key] = $parent;
            } else {
                return [];
            }
        }
        return $filteredParents;
    }

}


<?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\BeforeBackgroundTested;
use Behat\Behat\EventDispatcher\Event\BeforeOutlineTested;
use Behat\Behat\EventDispatcher\Event\BeforeScenarioTested;
use Behat\Behat\EventDispatcher\Event\BeforeStepTested;
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;
use Yoanm\BehatUtilsExtension\Subscriber\ListenerPriority;

class BehatEventsContext implements Context, BehatContextSubscriberInterface
{
    const BEHAT_STEP_EVENT_LISTENER_SCENARIO_TAG = 'enable-behat-step-event-listener';

    /** @var GherkinNodeTested[] */
    private $behatStepEvents = [];
    /** @var bool */
    private $listenEvent = false;

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

    /** @var bool */
    private $expectScenarioEndEvent = false;
    /** @var bool */
    private $expectExampleEndEvent = false;
    /** @var bool */
    private $expectBackgroundEndEvent = false;
    /** @var bool */
    private $expectStepEndEvent = false;

    /**
     * @Given I listen for behat steps event
     */
    public function iListenForBehatStepsEvent()
    {
        $this->listenEvent = true;
        $this->resetEventList();
    }

    /**
     * @Given /^I should have caught event regarding current (?P<type>(?:background|scenario|example)) start event$/
     */
    public function iShouldHaveCaughtEventRegardingNodeStart($type)
    {
        $eventData = $this->shiftEvent();
        $this->assertStartEventInstanceOf($eventData, $type);
        $this->assertEventArgs($eventData, $type, true);
    }

    /**
     * @Then /^I will catch event regarding current (?P<type>(?:background|scenario|example)) end event$/
     */
    public function iWillCaughtEventRegardingNodeEnd($type)
    {
        switch (strtoupper($type)) {
            case BehatStepLoggerSubscriber::HEADER_NODE_BACKGROUND:
                $this->expectBackgroundEndEvent = true;
                break;
            case BehatStepLoggerSubscriber::HEADER_NODE_SCENARIO:
                $this->expectScenarioEndEvent = true;
                break;
            case BehatStepLoggerSubscriber::HEADER_NODE_EXAMPLE:
                $this->expectExampleEndEvent = true;
                break;
            default:
                throw new \InvalidArgumentException(sprintf('"%s" not handled !', $type));
        }
    }

    /**
     * @Given I should have caught event regarding current step start event and will have the end event
     */
    public function iShouldHaveCaughtEventRegardingCurrentStepStartAndEnd()
    {
        // Shift an event that is the AfterTested event from previous node
        $this->shiftEvent();
        /** @var BeforeStepTested $event */
        $eventData = $this->shiftEvent();
        $this->assertStartEventInstanceOf($eventData, 'step');
        $this->assertEventArgs($eventData, 'step', true);
        $this->expectStepEndEvent = true;
    }

    /**
     * @param BeforeScenarioTested|BeforeOutlineTested $event
     */
    public function setUp(BeforeTested $event)
    {
        if (in_array(
            self::BEHAT_STEP_EVENT_LISTENER_SCENARIO_TAG,
            array_merge(
                $event->getScenario()->getTags(),
                $event->getFeature()->getTags()
            )
        )) {
            //Auto listen
            $this->iListenForBehatStepsEvent();
        } else {
            $this->resetEventList();
        }
    }

    /**
     * @param GherkinNodeTested $event
     */
    public function storeEvent(GherkinNodeTested $event, $name)
    {
        if (true === $this->listenEvent) {
            $this->behatStepEvents[] = [$event, $name];
        }
    }

    /**
     * @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 received, disable expectation */
            if ($event instanceof StepTested) {
                if (true === $this->expectStepEndEvent) {
                    $this->assertEventArgs([$event, $name], 'step', false);
                }
                $this->expectStepEndEvent = false;
            } elseif ($event instanceof BackgroundTested) {
                if (true === $this->expectBackgroundEndEvent) {
                    $this->assertEventArgs([$event, $name], 'background', false);
                }
                $this->expectBackgroundEndEvent = false;
            } else {
                if (ExampleTested::AFTER === $name) {
                    if (true === $this->expectExampleEndEvent) {
                        $this->assertEventArgs([$event, $name], 'example', false);
                    }
                    $this->expectExampleEndEvent = false;
                } else {
                    if (true === $this->expectScenarioEndEvent) {
                        $this->assertEventArgs([$event, $name], 'scenario', false);
                    }
                    $this->expectScenarioEndEvent = false;
                }
            }
        }
    }

    /**
     * @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->expectScenarioEndEvent,
                    'Scenario end event expected but not catched !'
                );
                \PHPUnit_Framework_Assert::assertFalse(
                    $this->expectExampleEndEvent,
                    'Example end event expected but not catched !'
                );
            }

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

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

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        $storeEventListener = ['storeEvent', ListenerPriority::HIGH_PRIORITY];

        $beforeStepListenerList = [
            ['setNodeContext', ListenerPriority::HIGH_PRIORITY],
            $storeEventListener,
        ];
        $beforeScenarioListenerList = array_merge(
            [ ['setUp', ListenerPriority::HIGH_PRIORITY] ],
            $beforeStepListenerList
        );
        $afterListenerList = [
            $storeEventListener,
            ['checkEndEventExpectation', ListenerPriority::HIGH_PRIORITY],
            ['tearDown', ListenerPriority::HIGH_PRIORITY],
            ['setNodeContext', ListenerPriority::LOW_PRIORITY],
        ];
        return [
            ScenarioTested::BEFORE => $beforeScenarioListenerList,
            ExampleTested::BEFORE => $beforeScenarioListenerList,

            BackgroundTested::BEFORE => $beforeStepListenerList,
            StepTested::BEFORE => $beforeStepListenerList,

            StepTested::AFTER => $afterListenerList,
            BackgroundTested::AFTER => $afterListenerList,

            ScenarioTested::AFTER => $afterListenerList,
            ExampleTested::AFTER => $afterListenerList,
        ];
    }

    /**
     * @return array|null Event as first value and event name as second value
     */
    protected function shiftEvent()
    {
        return array_shift($this->behatStepEvents);
    }

    protected function resetEventList()
    {
        $this->behatStepEvents = [];
    }

    protected function assertStartEventInstanceOf(array $eventData, $type)
    {
        switch (strtoupper($type)) {
            case BehatStepLoggerSubscriber::HEADER_NODE_BACKGROUND:
                $className = BeforeBackgroundTested::class;
                break;
            case BehatStepLoggerSubscriber::HEADER_NODE_EXAMPLE:
            case BehatStepLoggerSubscriber::HEADER_NODE_SCENARIO:
                $className = BeforeScenarioTested::class;
                break;
            case BehatStepLoggerSubscriber::HEADER_NODE_STEP:
                $className = BeforeStepTested::class;
                break;
            default:
                throw new \InvalidArgumentException(sprintf('"%s" not handled !', $type));
        }
        \PHPUnit_Framework_Assert::assertInstanceOf(
            $className,
            $eventData[0],
            sprintf('Failed asserting that start %s event has been received !', $type)
        );
    }

    protected function assertEventArgs(array $eventData, $type, $isStart)
    {
        switch (strtoupper($type)) {
            case BehatStepLoggerSubscriber::HEADER_NODE_BACKGROUND:
                $expected = $this->currentBackground->getTitle();
                $current = $eventData[0]->getNode()->getTitle();
                break;
            case BehatStepLoggerSubscriber::HEADER_NODE_SCENARIO:
                $expected = $this->currentScenario->getTitle();
                $current = $eventData[0]->getNode()->getTitle();
                break;
            case BehatStepLoggerSubscriber::HEADER_NODE_EXAMPLE:
                $expected = $this->currentScenario->getTokens();
                $current = $eventData[0]->getNode()->getTokens();
                break;
            case BehatStepLoggerSubscriber::HEADER_NODE_STEP:
                $expected = $this->currentStep->getText();
                $current = $eventData[0]->getNode()->getText();
                break;
            default:
                throw new \InvalidArgumentException(sprintf('"%s" not handled !', $type));
        }

        \PHPUnit_Framework_Assert::assertSame(
            $expected,
            $current,
            sprintf(
                'Failed asserting that %s %s event is the right one !',
                $isStart ? 'start' : 'end',
                $type
            )
        );
    }
}


<?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\Driver;

abstract class BaseDriver implements DriverInterface
{
    /**
     * Get a list of keys or dates and chooses the max date.
     *
     * @param array $params
     *
     * @return \DateTime
     */
    public function getMax(array $params)
    {
        if (empty($params)) {
            throw new \InvalidArgumentException('Unknown key list');
        }

        foreach ($params as $key => $value) {
            if (!($value instanceof \DateTime)) {
                $params[$key] = $this->get($value);
            }
        }

        return max($params);
    }
}


<?php

namespace Dhii\Data\Object;

use ArrayAccess;
use Dhii\Util\String\StringableInterface as Stringable;
use Exception as RootException;
use InvalidArgumentException;
use OutOfRangeException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use stdClass;

/**
 * Functionality for data retrieval.
 *
 * @since [*next-version*]
 */
trait UnsetDataCapableTrait
{
    /**
     * Unset data by key.
     *
     * @since [*next-version*]
     *
     * @param string|int|float|bool|Stringable $key The key of data to unset.
     *
     * @throws InvalidArgumentException    If the key is invalid.
     * @throws OutOfRangeException         If the inner store is invalid.
     * @throws NotFoundExceptionInterface  If the key is not found.
     * @throws ContainerExceptionInterface If problem accessing the container.
     */
    protected function _unsetData($key)
    {
        $store = $this->_getDataStore();

        try {
            $this->_containerUnset($store, $key);
        } catch (InvalidArgumentException $e) {
            throw $this->_createOutOfRangeException($this->__('Invalid store'),  null, $e, $store);
        } catch (OutOfRangeException $e) {
            throw $this->_createInvalidArgumentException($this->__('Invalid key'), null, $e, $key);
        }
    }

    /**
     * Retrieves a pointer to the data store.
     *
     * @since [*next-version*]
     *
     * @return array|ArrayAccess|stdClass The data store.
     */
    abstract protected function _getDataStore();

    /**
     * Unsets a value with the specified key on the given container.
     *
     * @since [*next-version*]
     *
     * @param array|ArrayAccess|stdClass       $container The writable container to unset the value on.
     * @param string|int|float|bool|Stringable $key       The key to unset the value for.
     *
     * @throws InvalidArgumentException    If the container is invalid.
     * @throws OutOfRangeException         If the key is invalid.
     * @throws NotFoundExceptionInterface  If the key is not found.
     * @throws ContainerExceptionInterface If problem accessing the container.
     */
    abstract protected function _containerUnset(&$container, $key);

    /**
     * Creates a new Out Of Range exception.
     *
     * @since [*next-version*]
     *
     * @param string|Stringable|null $message  The error message, if any.
     * @param int|null               $code     The error code, if any.
     * @param RootException|null     $previous The inner exception for chaining, if any.
     * @param mixed|null             $argument The value that is out of range, if any.
     *
     * @return OutOfRangeException The new exception.
     */
    abstract protected function _createOutOfRangeException(
        $message = null,
        $code = null,
        RootException $previous = null,
        $argument = null
    );

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

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


<?php

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

namespace jlorente\location\models;

use yii\base\Model;
use dosamigos\google\maps\services\GeocodingClient;
use yii\helpers\Json;
use jlorente\location\exceptions\GeocodingApiException;
use yii\base\InvalidConfigException,
    yii\base\InvalidParamException;

/**
 * Class Coordinates to call the geocoding google api.
 *
 * @author José Lorente <jose.lorente.martin@gmail.com>
 */
class Coordinates extends Model
{

    /**
     *
     * @var float
     */
    public $latitude;

    /**
     *
     * @var float
     */
    public $longitude;

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

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        if (empty($this->apiServerKey)) {
            throw new InvalidConfigException('A Google api server key must be provided');
        }
    }

    /**
     * Calls the api to search the coordinates for the given $address and
     * $regionCode.
     *
     * @param string $address
     * @param string $regionCode
     * @return boolean
     * @throws GeocodingApiException
     */
    public function apiCall($address, $regionCode)
    {
        $result = (new GeocodingClient())->lookup([
            'key' => $this->apiServerKey,
            'address' => $address,
            'region' => $regionCode
                ]
        );
        /*
         * https://console.developers.google.com/project/263658429534/apiui/credential
         * To work, the IP where this method it's executing must be enabled y google developers console
         */
        if ($result['status'] == "REQUEST_DENIED") {
            throw new GeocodingApiException('Configuration Error: This IP is not enabled in Google Developer Console');
        }
        if ($result['status'] !== 'OK' && $result['status'] !== 'ZERO_RESULTS') {
            throw new GeocodingApiException('Request failed');
        }
        if ($result['status'] === 'OK') {
            if (isset($result['results'][0]['geometry']['location']['lng']) === false || isset($result['results'][0]['geometry']['location']['lat']) === false) {
                throw new GeocodingApiException('Unexpected Google Api Response: ' . Json::encode($result));
            }
            $this->longitude = $result['results'][0]['geometry']['location']['lng'];
            $this->latitude = $result['results'][0]['geometry']['location']['lat'];
            return true;
        } else {
            return false;
        }
    }

    /**
     * Sets the api server key.
     *
     * @param string $key
     */
    public function setApiServerKey($key)
    {
        if (is_string($key)) {
            throw new InvalidParamException("Google api key must be a string value");
        }
        $this->apiServerKey = $key;
    }

}


<?php

namespace ByTIC\Codeception\Page\AbstractTraits;

/**
 * Class FormTrait
 * @package ByTIC\Codeception\Page\AbstractTraits
 */
trait FormTrait
{

    protected $forms = [];

    protected $formNameDefault = 'default';

    protected $formData = [];

    /**
     * @param null $name
     */
    public function checkForm($name = null)
    {
        $name = $this->initFormName($name);
        $form = $this->forms[$name];

        $this->getTester()->seeElement($form['path']);

        $fields = $form['fields'];
        foreach ($fields as $field => $params) {
            $this->getTester()->seeElement($params['path']);
        }
    }

    /**
     * @param null $name
     * @return null|string
     */
    public function initFormName($name = null)
    {
        return $name ? $name : $this->getFormNameDefault();
    }

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

    /**
     * @return \ByTIC\Common\Tests\AcceptanceTester;
     */
    abstract protected function getTester();

    /**
     * @param array $params
     * @param null $name
     */
    public function setFieldsAndsubmitForm($params = [], $name = null)
    {
        foreach ($this->formData as $field => $value) {
            $value = isset($params[$field]) ? $params[$field] : $value;
            $this->setFieldValue($field, $value);
        }
        $this->submitForm($name);
    }

    /**
     * Sets a form field value based on field type
     * @param $field
     * @param $value
     * @return mixed
     */
    public function setFieldValue($field, $value)
    {
        $type = $this->getFieldFormType($field);
        switch ($type) {
            case 'select':
                return $this->selectOptionForm($field, $value);
            case 'checkbox':
            case 'checkboxGroup':
                return $this->checkOptionForm($field);
            default:
                return $this->fillFieldForm($field, $value);
        }
    }

    /**
     * @param $field
     * @param null $form
     * @return mixed
     */
    public function getFieldFormType($field, $form = null)
    {
        return $this->getFieldFormParam($field, 'type', $form);
    }

    /**
     * @param $field
     * @param $param
     * @param null $form
     * @return mixed
     */
    public function getFieldFormParam($field, $param, $form = null)
    {
        $form = $this->initFormName($form);

        return $this->forms[$form]['fields'][$field][$param];
    }

    /**
     * @param $field
     * @param $value
     * @param null $form
     * @return mixed|null
     */
    public function selectOptionForm($field, $value, $form = null)
    {
        $form = $this->initFormName($form);
        $path = $this->getFieldFormPath($field, $form);

        return $this->getTester()->selectOption($path, $value);
    }

    /**
     * @param $field
     * @param null $form
     * @return mixed
     */
    public function getFieldFormPath($field, $form = null)
    {
        return $this->getFieldFormParam($field, 'path', $form);
    }

    /**
     * @param $field
     * @param null $form
     * @return mixed|null
     */
    public function checkOptionForm($field, $form = null)
    {
        $form = $this->initFormName($form);
        $path = $this->getFieldFormPath($field, $form);

        return $this->getTester()->checkOption($path);
    }

    /**
     * @param $field
     * @param $value
     * @param null $form
     * @return mixed|null
     */
    public function fillFieldForm($field, $value, $form = null)
    {
        $form = $this->initFormName($form);
        $path = $this->getFieldFormPath($field, $form);

        return $this->getTester()->fillField($path, $value);
    }

    /**
     * @param null $name
     * @param array $params
     */
    public function submitForm($name = null, $params = [])
    {
        $name = $this->initFormName($name);
        $form = $this->forms[$name];
        $this->getTester()->submitForm($form['path'], $params);
    }

    /**
     * @param $name
     * @param $value
     */
    public function setFieldFormData($name, $value)
    {
        $this->formData[$name] = $value;
    }

    /**
     * sets a field value from data object
     * @param $name
     * @return mixed
     */
    public function setFieldFromData($name)
    {
        $value = $this->getFieldFormData($name);
        return $this->setFieldValue($name, $value);
    }

    /**
     * @param $name
     * @return null
     */
    public function getFieldFormData($name)
    {
        return isset($this->formData[$name]) ? $this->formData[$name] : null;
    }

    /**
     * @param $field
     * @param $count
     * @param null $form
     */
    public function selectOptionCountForm($field, $count, $form = null)
    {
        $form = $this->initFormName($form);
        $path = $this->getFieldFormPath($field, $form);

        $option = $this->getTester()->grabTextFrom($path . ' option:nth-child(' . $count . ')');
        $this->selectOptionForm($field, $option);
    }

    /**
     * @param $path
     * @param null $name
     */
    protected function addForm($path, $name = null)
    {
        $name = $this->initFormName($name);
        $this->initForm($name);
        $this->forms[$name]['path'] = $path;
    }

    /**
     * @param null $name
     * @return $this
     */
    protected function initForm($name = null)
    {
        $name = $this->initFormName($name);
        if (!isset($this->forms[$name]) || !is_array($this->forms[$name])) {
            $this->forms[$name] = [
                'path' => 'form',
                'fields' => [],
                'submit' => 'button[type=submit]',
            ];
        }

        return $this;
    }

    /**
     * @param $field
     * @param $params
     * @param null $name
     * @return $this
     */
    protected function addInputForm($field, $params, $name = null)
    {
        return $this->addFieldForm($field, 'input', $params, $name);
    }

    /**
     * @param $field
     * @param $type
     * @param $params
     * @param null $name
     * @return $this
     */
    protected function addFieldForm($field, $type, $params, $name = null)
    {
        $name = $this->initFormName($name);
        $this->initForm($name);

        $params = is_string($params) ? ['path' => $params] : $params;
        $params['type'] = $type;
        $this->forms[$name]['fields'][$field] = $params;

        return $this;
    }

    /**
     * @param $field
     * @param $params
     * @param null $name
     * @return $this
     */
    protected function addSelectForm($field, $params, $name = null)
    {
        return $this->addFieldForm($field, 'select', $params, $name);
    }

    /**
     * @param $field
     * @param $params
     * @param null $name
     * @return $this
     */
    protected function addRadioForm($field, $params, $name = null)
    {
        return $this->addFieldForm($field, 'radio', $params, $name);
    }

    /**
     * @param $field
     * @param $params
     * @param null $name
     * @return $this
     */
    protected function addCheckboxForm($field, $params, $name = null)
    {
        return $this->addFieldForm($field, 'checkbox', $params, $name);
    }

    /**
     * @param $field
     * @param $params
     * @param null $name
     * @return $this
     */
    protected function addCheckboxGroupForm($field, $params, $name = null)
    {
        return $this->addFieldForm($field, 'checkboxGroup', $params, $name);
    }

    /**
     * @param $field
     * @param $params
     * @param null $name
     * @return $this
     */
    protected function addTextareaForm($field, $params, $name = null)
    {
        return $this->addFieldForm($field, 'textarea', $params, $name);
    }
}


<?php

namespace WyriHaximus\ApiClient\Tools;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

class EmptyLineAboveDocblocksFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = 2; $index < count($tokens); $index++) {
            $token = $tokens[$index];
            $previousToken = $tokens[$index - 1];
            $sndPreviousToken = $tokens[$index - 2];
            if ($sndPreviousToken->getContent() !== '{' &&
                substr($token->getContent(), 0, 3) === '/**' &&
                $previousToken->getLine() === $token->getLine() - 1
            ) {
                $previousToken->setContent(PHP_EOL . $previousToken->getContent());
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Ensure there is an empty line behind abstract or interface methods.';
    }
}


<?php

namespace Peyote;

/**
 * A class to allow table altering.
 *
 * @package    Peyote
 * @author     Dave Widmer <dave@davewidmer.net>
 */
class Alter implements Builder
{
	/**
	 * @var string
	 */
	private $table = null;

	/**
	 * @var array
	 */
	private $conditions = array();

	/**
	 * @param string $table  The table name
	 */
	public function __construct($table = null)
	{
		$this->setTable($table);
	}

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

	/**
	 * @param string $table The table name to drop.
	 * @return \Peyote\Alter
	 */
	public function setTable($table)
	{
		$this->table = $table;
		return $this;
	}

	/**
	 * @return array  A list of alter conditions
	 */
	public function getConditions()
	{
		return $this->conditions;
	}

	/**
	 * @param string|\Peyote\Column $column     The column name or Peyote column
	 * @return \Peyote\Alter                    $this
	 */
	public function addColumn($column)
	{
		if ($column instanceof \Peyote\Column)
		{
			$column = $column->compile();
		}

		$this->conditions[] = array("ADD", $column, null);
		return $this;
	}

	/**
	 * @param  string $column The columns name
	 * @return \Peyote\Alter
	 */
	public function addPrimaryKey($column)
	{
		return $this->addIndex($column, "PRIMARY KEY");
	}

	/**
	 *
	 * @param  string $column The column name to add as a key
	 * @param  string $type   The type of key to add
	 * @return \Peyote\Alter  $this
	 */
	public function addIndex($column, $type = "INDEX")
	{
		$this->conditions[] = array("ADD", $type, "({$column})");
		return $this;
	}

	/**
	 * @param  string $column The column name
	 * @return \Peyote\Alter  $this
	 */
	public function dropColumn($column)
	{
		$this->conditions[] = array("DROP", $column, "");
		return $this;
	}

	/**
	 * @return \Peyote\Alter  $this
	 */
	public function dropPrimaryKey()
	{
		$this->conditions[] = array("DROP", "PRIMARY", "KEY");
	}

	/**
	 * @param  string $index  The index
	 * @return \Peyote\Alter  $this
	 */
	public function dropIndex($index, $type = "INDEX")
	{
		$this->conditions[] = array("DROP", $type, $index);
		return $this;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @throws \Peyote\Exception
	 */
	public function compile()
	{
		$conditions = $this->getConditions();

		if (empty($conditions))
		{
			throw new \Peyote\Exception("\Peyote\Alter is an empty statement");
		}

		$query = array("ALTER", "TABLE", $this->getTable());

		foreach ($conditions as $condition)
		{
			$query[] = rtrim(join(' ', $condition));
		}

		return join(' ', $query);
	}

}


<?php

namespace Qck;

/**
 * IpAddress from https://raw.githubusercontent.com/zendframework/zend-http/master/src/PhpEnvironment/RemoteAddress.php
 *
 * @author muellerm
 */
class IpAddress implements \Qck\Interfaces\IpAddress
{

    function __construct( $FilterFlags = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE )
    {
        $this->FilterFlags = $FilterFlags;
    }

    /**
     * Changes proxy handling setting.
     *
     * This must be static method, since validators are recovered automatically
     * at session read, so this is the only way to switch setting.
     *
     * @param  bool  $useProxy Whether to check also proxied IP addresses.
     * @return RemoteAddress
     */
    public function setUseProxy( $useProxy = true )
    {
        $this->useProxy = $useProxy;
        return $this;
    }

    /**
     * Checks proxy handling setting.
     *
     * @return bool Current setting value.
     */
    public function getUseProxy()
    {
        return $this->useProxy;
    }

    /**
     * Set list of trusted proxy addresses
     *
     * @param  array $trustedProxies
     * @return RemoteAddress
     */
    public function setTrustedProxies( array $trustedProxies )
    {
        $this->trustedProxies = $trustedProxies;
        return $this;
    }

    /**
     * Set the header to introspect for proxy IPs
     *
     * @param  string $header
     * @return RemoteAddress
     */
    public function setProxyHeader( $header = 'X-Forwarded-For' )
    {
        $this->proxyHeader = $this->normalizeProxyHeader( $header );
        return $this;
    }

    /**
     * Returns client IP address.
     *
     * @return string IP address.
     */
    public function getValue()
    {
        static $ip = null;
        if ( is_null( $ip ) )
        {
            $ip = $this->getIpAddressFromProxy();

            // direct IP address
            if ( isset( $_SERVER[ 'REMOTE_ADDR' ] ) )
            {
                $ip = $_SERVER[ 'REMOTE_ADDR' ];
            }
        }

        return $ip;
    }

    /**
     * Attempt to get the IP address for a proxied client
     *
     * @see http://tools.ietf.org/html/draft-ietf-appsawg-http-forwarded-10#section-5.2
     * @return false|string
     */
    protected function getIpAddressFromProxy()
    {
        if ( !$this->useProxy || (isset( $_SERVER[ 'REMOTE_ADDR' ] ) && !in_array( $_SERVER[ 'REMOTE_ADDR' ], $this->trustedProxies ))
        )
        {
            return false;
        }

        $header = $this->proxyHeader;
        if ( !isset( $_SERVER[ $header ] ) || empty( $_SERVER[ $header ] ) )
        {
            return false;
        }

        // Extract IPs
        $ips = explode( ',', $_SERVER[ $header ] );
        // trim, so we can compare against trusted proxies properly
        $ips = array_map( 'trim', $ips );
        // remove trusted proxy IPs
        $ips = array_diff( $ips, $this->trustedProxies );

        // Any left?
        if ( empty( $ips ) )
        {
            return false;
        }

        // Since we've removed any known, trusted proxy servers, the right-most
        // address represents the first IP we do not know about -- i.e., we do
        // not know if it is a proxy server, or a client. As such, we treat it
        // as the originating IP.
        // @see http://en.wikipedia.org/wiki/X-Forwarded-For
        $ip = array_pop( $ips );
        return $ip;
    }

    /**
     * Normalize a header string
     *
     * Normalizes a header string to a format that is compatible with
     * $_SERVER
     *
     * @param  string $header
     * @return string
     */
    protected function normalizeProxyHeader( $header )
    {
        $header = strtoupper( $header );
        $header = str_replace( '-', '_', $header );
        if ( 0 !== strpos( $header, 'HTTP_' ) )
        {
            $header = 'HTTP_' . $header;
        }
        return $header;
    }

    public function isValid()
    {
        if ( filter_var( $this->getValue(), FILTER_VALIDATE_IP, $this->FilterFlags ) )
        {
            // it's valid
            return true;
        }
        else
        {
            // it's not valid
            return false;
        }
    }

    /**
     *
     * @var int
     */
    protected $FilterFlags;

    /**
     * Whether to use proxy addresses or not.
     *
     * As default this setting is disabled - IP address is mostly needed to increase
     * security. HTTP_* are not reliable since can easily be spoofed. It can be enabled
     * just for more flexibility, but if user uses proxy to connect to trusted services
     * it's his/her own risk, only reliable field for IP address is $_SERVER['REMOTE_ADDR'].
     *
     * @var bool
     */
    protected $useProxy = false;

    /**
     * List of trusted proxy IP addresses
     *
     * @var array
     */
    protected $trustedProxies = [];

    /**
     * HTTP header to introspect for proxies
     *
     * @var string
     */
    protected $proxyHeader = 'HTTP_X_FORWARDED_FOR';

}


<?php

namespace CoRex\Support;

class Collection implements \Iterator, \Countable
{
    private $items;

    /**
     * Data constructor.
     *
     * @param array $items Default null which means [].
     */
    public function __construct(array $items = null)
    {
        if ($items === null) {
            $items = [];
        }
        $this->items = $items;
    }

    /**
     * To json.
     *
     * @param boolean $prettyPrint Default false.
     * @return string
     */
    public function toJson($prettyPrint = false)
    {
        $options = 0;
        if ($prettyPrint) {
            $options += JSON_PRETTY_PRINT;
        }
        return json_encode($this->items, $options);
    }

    /**
     * Get count.
     *
     * @return integer
     */
    public function count()
    {
        if (is_array($this->items) && $this->items !== null) {
            return count($this->items);
        }
        return 0;
    }

    /**
     * Return the current item.
     *
     * @return mixed
     */
    public function current()
    {
        if ($this->items === null) {
            return null;
        }
        return current($this->items);
    }

    /**
     * Move forward to next item.
     *
     * @return $this
     */
    public function next()
    {
        if ($this->items === null) {
            return null;
        }
        next($this->items);
        return $this;
    }

    /**
     * Return the key of the current item.
     *
     * @return mixed
     */
    public function key()
    {
        if ($this->items === null) {
            return null;
        }
        return key($this->items);
    }

    /**
     * Checks if current position is valid.
     *
     * @return boolean
     */
    public function valid()
    {
        if ($this->items === null) {
            return false;
        }
        $key = key($this->items);
        return ($key !== null && $key !== false);
    }

    /**
     * Rewind the Iterator to the first item.
     *
     * @return $this
     */
    public function rewind()
    {
        if ($this->items === null) {
            return null;
        }
        reset($this->items);
        return $this;
    }

    /**
     * Get first item in collection.
     *
     * @return mixed
     */
    public function first()
    {
        $this->rewind();
        return $this->current();
    }

    /**
     * Get last element in collection.
     *
     * @return mixed|null
     */
    public function last()
    {
        if (is_array($this->items) && count($this->items) > 0) {
            return end($this->items);
        }
        return null;
    }

    /**
     * Get all items.
     *
     * @return array|mixed|null
     */
    public function all()
    {
        return $this->items;
    }

    /**
     * Run a callable/closure on each element.
     *
     * @param callable $callable Parameters: ($item, $key). Prefix $item with & to modify $item.
     * @return $this
     * @throws \Exception
     */
    public function each(callable $callable)
    {
        foreach ($this->items as $key => $item) {
            if ($callable($item, $key) === false) {
                break;
            }
            $this->items[$key] = $item;
        }
        return $this;
    }

    /**
     * Pluck.
     *
     * @param string $path
     * @param mixed $defaultValue Default null.
     * @return $this
     */
    public function pluck($path, $defaultValue = null)
    {
        $result = [];
        if ($this->items === null || (is_array($this->items) && count($this->items) == 0)) {
            return null;
        }
        foreach ($this->items as $key => $item) {
            if (is_object($item)) {
                $value = isset($item->{$path}) ? $item->{$path} : null;
            } else {
                $value = Arr::get($item, $path, $defaultValue);
            }
            $result[] = $value;
        }
        return new static($result);
    }

    /**
     * Sum.
     *
     * @param string $path
     * @param integer $defaultValue Default 0.
     * @return float|integer
     */
    public function sum($path, $defaultValue = 0)
    {
        return array_sum($this->pluck($path, $defaultValue)->all());
    }

    /**
     * Average.
     *
     * @param string $path
     * @param integer $defaultValue Default 0.
     * @return float|integer
     */
    public function average($path, $defaultValue = 0)
    {
        if ($this->items === null || (is_array($this->items) && count($this->items) == 0)) {
            return $defaultValue;
        }
        $sum = $this->sum($path, $defaultValue);
        if ($sum == 0) {
            return 0;
        }
        return $sum / count($this->items);
    }

    /**
     * Max.
     *
     * @param string $path
     * @param integer $defaultValue Default 0.
     * @return integer
     */
    public function max($path, $defaultValue = 0)
    {
        if ($this->items === null || (is_array($this->items) && count($this->items) == 0)) {
            return $defaultValue;
        }
        $items = $this->pluck($path, $defaultValue);
        $max = 0;
        foreach ($items as $item) {
            if ($item > $max) {
                $max = $item;
            }
        }
        return $max;
    }

    /**
     * Min.
     *
     * @param string $path
     * @param integer $defaultValue Default 0.
     * @return integer
     */
    public function min($path, $defaultValue = 0)
    {
        if ($this->items === null || (is_array($this->items) && count($this->items) == 0)) {
            return $defaultValue;
        }
        $items = $this->pluck($path, $defaultValue);
        $min = PHP_INT_MAX;
        foreach ($items as $item) {
            if ($item < $min) {
                $min = $item;
            }
        }
        return $min;
    }

    /**
     * Reverse.
     *
     * @return Collection
     */
    public function reverse()
    {
        return new static(array_reverse($this->items, true));
    }

    /**
     * Keys.
     *
     * @return array
     */
    public function keys()
    {
        if (is_array($this->items)) {
            return array_keys($this->items);
        }
        return [];
    }

    /**
     * Values.
     *
     * @return array
     */
    public function values()
    {
        return array_values($this->items);
    }

    /**
     * Get.
     *
     * @param string $key
     * @param mixed $defaultValue Default null.
     * @return mixed
     */
    public function get($key, $defaultValue = null)
    {
        if ($this->has($key)) {
            return $this->items[$key];
        }
        return $defaultValue;
    }

    /**
     * Has.
     *
     * @param string $key
     * @return boolean
     */
    public function has($key)
    {
        return in_array($key, $this->keys());
    }

    /**
     * Add.
     *
     * @param mixed $value
     * @return $this
     */
    public function add($value)
    {
        $this->items[] = $value;
        return $this;
    }

    /**
     * Set.
     *
     * @param string $key
     * @param mixed $value
     * @return $this
     */
    public function set($key, $value)
    {
        $this->items[$key] = $value;
        return $this;
    }

    /**
     * Delete.
     *
     * @param string $key
     * @return $this
     */
    public function delete($key)
    {
        if (isset($this->items[$key])) {
            unset($this->items[$key]);
        }
        return $this;
    }
}


<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\filters;

use yii\base\Component;
use yii\base\Action;
use yii\web\User;
use yii\web\Request;
use yii\base\Controller;

/**
 * This class represents an access rule defined by the [[AccessControl]] action filter
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AccessRule extends Component
{
    /**
     * @var boolean whether this is an 'allow' rule or 'deny' rule.
     */
    public $allow;
    /**
     * @var array list of action IDs that this rule applies to. The comparison is case-sensitive.
     * If not set or empty, it means this rule applies to all actions.
     */
    public $actions;
    /**
     * @var array list of the controller IDs that this rule applies to. Each controller ID is prefixed with the module ID (if any).
     * The comparison is case-sensitive. If not set or empty, it means this rule applies to all controllers.
     */
    public $controllers;
    /**
     * @var array list of roles that this rule applies to. Two special roles are recognized, and
     * they are checked via [[User::isGuest]]:
     *
     * - `?`: matches a guest user (not authenticated yet)
     * - `@`: matches an authenticated user
     *
     * If you are using RBAC (Role-Based Access Control), you may also specify role or permission names.
     * In this case, [[User::can()]] will be called to check access.
     *
     * If this property is not set or empty, it means this rule applies to all roles.
     */
    public $roles;
    /**
     * @var array list of user IP addresses that this rule applies to. An IP address
     * can contain the wildcard `*` at the end so that it matches IP addresses with the same prefix.
     * For example, '192.168.*' matches all IP addresses in the segment '192.168.'.
     * If not set or empty, it means this rule applies to all IP addresses.
     * @see Request::userIP
     */
    public $ips;
    /**
     * @var array list of request methods (e.g. `GET`, `POST`) that this rule applies to.
     * The request methods must be specified in uppercase.
     * If not set or empty, it means this rule applies to all request methods.
     * @see \yii\web\Request::method
     */
    public $verbs;
    /**
     * @var callable a callback that will be called to determine if the rule should be applied.
     * The signature of the callback should be as follows:
     *
     * ```php
     * function ($rule, $action)
     * ```
     *
     * where `$rule` is this rule, and `$action` is the current [[Action|action]] object.
     * The callback should return a boolean value indicating whether this rule should be applied.
     */
    public $matchCallback;
    /**
     * @var callable a callback that will be called if this rule determines the access to
     * the current action should be denied. If not set, the behavior will be determined by
     * [[AccessControl]].
     *
     * The signature of the callback should be as follows:
     *
     * ```php
     * function ($rule, $action)
     * ```
     *
     * where `$rule` is this rule, and `$action` is the current [[Action|action]] object.
     */
    public $denyCallback;

    /**
     * Checks whether the Web user is allowed to perform the specified action.
     * @param Action $action the action to be performed
     * @param User $user the user object
     * @param Request $request
     * @return boolean|null true if the user is allowed, false if the user is denied, null if the rule does not apply to the user
     */
    public function allows($action, $user, $request)
    {
        if ($this->matchAction($action)
            && $this->matchRole($user)
            && $this->matchIP($request->getUserIP())
            && $this->matchVerb($request->getMethod())
            && $this->matchController($action->controller)
            && $this->matchCustom($action)
        ) {
            return $this->allow ? true : false;
        } else {
            return null;
        }
    }

    /**
     * @param Action $action the action
     * @return boolean whether the rule applies to the action
     */
    protected function matchAction($action)
    {
        return empty($this->actions) || in_array($action->id, $this->actions, true);
    }

    /**
     * @param Controller $controller the controller
     * @return boolean whether the rule applies to the controller
     */
    protected function matchController($controller)
    {
        return empty($this->controllers) || in_array($controller->uniqueId, $this->controllers, true);
    }

    /**
     * @param User $user the user object
     * @return boolean whether the rule applies to the role
     */
    protected function matchRole($user)
    {
        if (empty($this->roles)) {
            return true;
        }
        foreach ($this->roles as $role) {
            if ($role === '?') {
                if ($user->getIsGuest()) {
                    return true;
                }
            } elseif ($role === '@') {
                if (!$user->getIsGuest()) {
                    return true;
                }
            } elseif ($user->can($role)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param string $ip the IP address
     * @return boolean whether the rule applies to the IP address
     */
    protected function matchIP($ip)
    {
        if (empty($this->ips)) {
            return true;
        }
        foreach ($this->ips as $rule) {
            if ($rule === '*' || $rule === $ip || (($pos = strpos($rule, '*')) !== false && !strncmp($ip, $rule, $pos))) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param string $verb the request method
     * @return boolean whether the rule applies to the request
     */
    protected function matchVerb($verb)
    {
        return empty($this->verbs) || in_array($verb, $this->verbs, true);
    }

    /**
     * @param Action $action the action to be performed
     * @return boolean whether the rule should be applied
     */
    protected function matchCustom($action)
    {
        return empty($this->matchCallback) || call_user_func($this->matchCallback, $this, $action);
    }
}