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

/**
 * SetTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     SetInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait SetTrait
{
    /**
     * SET column values
     *
     * @var    array
     * @access protected
     */
    protected $clause_data = [];

    /**
     * SET column name
     *
     * @var    array
     * @access protected
     */
    protected $clause_set  = [];

    /**
     * Current data row number
     *
     * @var    array
     * @access protected
     */
    protected $clause_rownum = 0;

    /**
     * Set column values
     *
     * @param  string|array $col
     * @param  mixed value scalar or Select query
     * @return self
     * @access public
     */
    public function set($col, $value = ClauseInterface::NO_VALUE)
    {
        if (is_array($col)) {
            return $this->setWithArrayData($col);
        }

        // update column name
        if (!isset($this->clause_set[$col])) {
            $this->clause_set[$col] = true;
        }

        // store data by row
        if (ClauseInterface::NO_VALUE !== $value) {
            $this->clause_data[$this->clause_rownum][$col] = $value;
        }

        return $this;
    }

    /**
     * Batch SET
     *
     * @param  array $data
     * @return self
     * @access protected
     */
    protected function setWithArrayData(array $data)
    {
        // multiple rows
        if (isset($data[0])) {
            foreach ($data as $row) {
                is_array($row) ? $this->setWithArrayData($row) :
                    $this->set($row);
            }
            return $this;

        // multiple values
        } else {
            foreach ($data as $col => $val) {
                $this->set($col, $val);
            }
        }

        // increase rownum
        $this->clause_rownum++;

        return $this;
    }

    /**
     * Build SET
     *
     * @return array
     * @access protected
     */
    protected function buildSet()/*# : array */
    {
        if ('UPDATE' === $this->getType()) {
            return $this->buildUpdateSet();
        } else {
            return $this->buildInsertSet();
        }
    }

    /**
     * Build ( ... )
     *
     * @return array
     * @access protected
     */
    protected function buildInsertSet()/*# : array */
    {
        $result = [];

        if (empty($this->clause_set)) {
            return $result;
        }

        // build cols first
        $cols = [];
        foreach (array_keys($this->clause_set) as $col) {
            $cols[] = $this->quote($col);
        }
        $result[] = '(' . join(', ', $cols) . ')';

        return $result;
    }

    /**
     * Build SET ... = ..., ... = ...
     *
     * @return array
     * @access protected
     */
    protected function buildUpdateSet()/*# : array */
    {
        $result = [];

        // build set
        $data = $this->clause_data[0];
        foreach ($data as $col => $val) {
            $result[] = $this->quote($col) . ' = ' . $this->processValue($val);
        }

        return $result;
    }

    /**
     * Build VALUES ( ... )
     *
     * @return array
     * @access protected
     */
    protected function buildValues()/*# : array */
    {
        $result = [];
        $cols = array_keys($this->clause_set);

        $maxRow = count($this->clause_data) - 1;
        foreach ($this->clause_data as $num => $row) {
            $values = [];
            foreach ($cols as $col) {
                if (isset($row[$col])) {
                    $values[] = $this->processValue($row[$col]);
                } else {
                    $values[] = $this->getSettings()['useNullAsDefault'] ?
                        'NULL' : 'DEFAULT';
                }
            }
            $result[] = '(' . join(', ', $values) . ')' . ($num !== $maxRow ?
                ',' : '');
        }

        return $result;
    }

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

    /**
     * Return the SQL statement type
     *
     * from StatementInterface
     *
     * @return string
     * @access public
     */
    abstract public function getType()/*# : string */;

    /**
     * Get current settings
     *
     * @return array
     * @access public
     */
    abstract public function getSettings()/*# : array */;
}


<?php

namespace Asoc\Dadatata\Filter;

use Asoc\Dadatata\Model\ThingInterface;

class ChainFilter implements FilterInterface
{

    /**
     * @var FilterInterface[]
     */
    private $filters;

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

    /**
     * @param ThingInterface   $thing
     * @param string           $sourcePath
     * @param OptionsInterface $options
     *
     * @return array Paths to generated files
     */
    public function process(ThingInterface $thing, $sourcePath, OptionsInterface $options = null)
    {
        $result = null;
        foreach ($this->filters as $filter) {
            if ($result === null) {
                $result = $filter->process($thing, $sourcePath, $options);
            } else {
                $tmp = [];

                foreach ($result as $path) {
                    $tmp = array_merge($tmp, $filter->process($thing, $path, $options));
                }

                $result = $tmp;
            }
        }

        return $result;
    }

    /**
     * @param ThingInterface $thing
     *
     * @return boolean
     */
    public function canHandle(ThingInterface $thing)
    {
        return $this->filters[0]->canHandle($thing);
    }

    /**
     * @param OptionsInterface $options
     */
    public function setOptions(OptionsInterface $options)
    {
        foreach ($this->filters as $filter) {
            $filter->setOptions($options);
        }
    }
}


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

use Peach\Http\SingleHeaderField;
use Peach\Http\Util;

/**
 * Accept, Accept-Language, Accept-Encoding など, quality value を値に持つヘッダーを表現するクラスです.
 */
class QualityValues implements SingleHeaderField
{
    /**
     * ヘッダー名です.
     *
     * @var string
     */
    private $name;

    /**
     * このヘッダーに含まれる quality value の一覧です.
     *
     * @var array
     */
    private $qvalueList;

    /**
     * 指定されたヘッダー名および quality value のリストを持つ QualityValues インスタンスを構築します.
     *
     * 第 2 引数には以下のようなフォーマットの配列を指定してください.
     * <code>
     * array("ja" => 1.0, "en-US" => 0.9, "en-GB" => 0.8, "en" => 0.7)
     * </code>
     *
     * @param type $name
     * @param array $qvalueList
     */
    public function __construct($name, array $qvalueList)
    {
        Util::validateHeaderName($name);
        foreach ($qvalueList as $key => $value) {
            $this->validateQvalue($key, $value);
        }
        arsort($qvalueList);
        $this->name       = $name;
        $this->qvalueList = $qvalueList;
    }

    /**
     * それぞれの qvalue の値が 0 以上 1 以下の小数となっていることを確認します.
     *
     * @param string $key
     * @param string $value
     * @throws \InvalidArgumentException
     */
    private function validateQvalue($key, $value)
    {
        if (!preg_match("/\\A[a-zA-Z0-9_\\-\\/\\+\\*]+\\z/", $key)) {
            throw new \InvalidArgumentException("Invalid qvalue name: '{$key}'");
        }
        if (!is_numeric($value)) {
            throw new \InvalidArgumentException("Each qvalue must be a real number");
        }
        if ($value < 0 || 1.0 < $value) {
            throw new \InvalidArgumentException("Each qvalue must be in the range 0 through 1");
        }
    }

    /**
     * このヘッダーに含まれる quality value の一覧を "," で連結した文字列で出力します.
     * 各 quality value について, その値が 1.0 に等しい場合はキーのみ,
     * 1.0 未満の場合は "key;q=value" 形式で書式化されます.
     *
     * @return string
     */
    public function format()
    {
        $callback = function ($key, $value) {
            return $value === 1.0 ? $key : "{$key};q={$value}";
        };
        $qvalueList = $this->qvalueList;
        return implode(",", array_map($callback, array_keys($qvalueList), array_values($qvalueList)));
    }

    /**
     * このヘッダーの名前を返します.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * このヘッダーに含まれる quality value の一覧を配列で返します.
     *
     * @return array
     */
    public function getValue()
    {
        return $this->qvalueList;
    }
}


<?php

namespace Peyote;

/**
 * The Create table class
 *
 * @package    Peyote
 * @author     Dave Widmer <dave@davewidmer.net>
 */
class Create extends Drop
{
	/**
	 * @var array
	 */
	private $columns = array();

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

	/**
	 * @var string
	 */
	private $engine = "MyISAM";

	/**
	 * @var string
	 */
	private $charset = "utf8";

	/**
	 * @return string  The column list
	 */
	public function getColumns()
	{
		return $this->columns;
	}

	/**
	 * @param array $columns   The columns to set.
	 * @return \Peyote\Create  $this
	 */
	public function setColumns(array $columns)
	{
		$this->columns = $columns;
		return $this;
	}

	/**
	 * @return array  A list of primary keys
	 */
	public function getPrimaryKey()
	{
		return $this->primary_key;
	}

	/**
	 * @param array|string     The key(s) to set
	 * @return \Peyote\Create  $this
	 */
	public function setPrimaryKey($keys)
	{
		if (\is_string($keys))
		{
			$keys = array($keys);
		}

		$this->primary_key = $keys;
		return $this;
	}

	/**
	 * @param string $key      The name of the primary key to add
	 * @return \Peyote\Create  $this
	 */
	public function addPrimaryKey($key)
	{
		if ( ! in_array($key, $this->primary_key))
		{
			$this->primary_key[] = $key;
		}

		return $this;
	}

	/**
	 * @return string  The database engine (MyISAM, InnoDB)
	 */
	public function getEngine()
	{
		return $this->engine;
	}

	/**
	 * @param  string $engine  The database engine
	 * @return \Peyote\Create  $this
	 */
	public function setEngine($engine)
	{
		$this->engine = $engine;
		return $this;
	}

	/**
	 * @return string  The character set
	 */
	public function getCharset()
	{
		return $this->charset;
	}

	/**
	 * @param  string $charset  The character set.
	 * @return \Peyote\Create   $this
	 */
	public function setCharset($charset)
	{
		$this->charset = $charset;
		return $this;
	}

	/**
	 * {@inheritDoc}
	 */
	public function compile()
	{
		$query = array("CREATE", $this->getType());

		if ($this->getIfExists() === true)
		{
			$query[] = "IF NOT EXISTS";
		}

		$query[] = $this->getTable();
		$query[] = "(";

		$columns = array();
		foreach ($this->getColumns() as $column)
		{
			if ($column instanceof \Peyote\Column)
			{
				if ($column->isPrimaryKey())
				{
					$this->addPrimaryKey($column->getName());
				}

				$column = $column->compile();
			}

			$columns[] = $column;
		}

		if ( ! empty($this->primary_key))
		{
			$columns[] = "PRIMARY KEY (".join(', ', $this->primary_key).')';
		}

		$query[] = join(', ', $columns);
		$query[] = ")";

		$query[] = 'ENGINE='.$this->getEngine();
		$query[] = 'DEFAULT CHARSET='.$this->getCharset();

		return join(' ', $query);
	}

}


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

/**
 * UTF-8 で符号化された文字列を扱う Codec です.
 * このクラスの decode メソッドは, UTF-8 の文字列を文字単位で分解し,
 * 各文字の Unicode 符号点をあらわす整数の配列を返します.
 * encode メソッドは, 整数の配列を UTF-8 の文字列に変換します.
 *
 * UTF-8 のビットパターンは以下の通りです.
 * <pre>
 * 0xxxxxxx                                               (00-7f)
 * 110xxxxx 10xxxxxx                                      (c0-df)(80-bf)
 * 1110xxxx 10xxxxxx 10xxxxxx                             (e0-ef)(80-bf)(80-bf)
 * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx                    (f0-f7)(80-bf)(80-bf)(80-bf)
 * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx           (f8-fb)(80-bf)(80-bf)(80-bf)(80-bf)
 * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx  (fc-fd)(80-bf)(80-bf)(80-bf)(80-bf)(80-bf)
 * </pre>
 *
 * RFC 3629 では 5 バイト以上のシーケンスが無効とされましたが,
 * このクラスは RFC 2279 に基づいて 5 バイト以上のシーケンスも受理します.
 * なお, このクラスはサロゲートペアを考慮しません.
 *
 * 引用文献: {@link http://ja.wikipedia.org/wiki/UTF-8 UTF-8 - Wikipedia}
 *
 * このクラスは将来的に状態 (メンバ変数) を持つ可能性が高いので,
 * 敢えて Singleton パターンにしていません.
 */
class Utf8Codec implements Codec
{
    /**
     * 指定された UTF-8 の文字列を Unicode 符号点の配列に変換します.
     *
     * @param  string $text UTF-8 でエンコードされた文字列
     * @return array        Unicode 符号点の配列
     */
    public function decode($text)
    {
        $bom = chr(0xEF) . chr(0xBB) . chr(0xBF);
        if (Strings::startsWith($text, $bom)) {
            return $this->decode(substr($text, 3));
        }

        $context = new Utf8Context($text);
        $result  = array();
        while ($context->hasNext()) {
            $result[] = $context->next();
        }

        // 文字列の末尾に不正な文字が存在していた場合,
        // $result の最後の要素に null が代入されるので取り除く
        $count = count($result);
        if ($count && $result[$count - 1] === null) {
            array_pop($result);
        }
        return $result;
    }

    /**
     * 指定された Unicode 符号点の配列を UTF-8 文字列に変換します.
     * 引数には Unicode 符号点をあらわす正の整数の配列を指定してください.
     * 配列以外の値を指定した場合は, その引数 (整数でない場合はメソッド内で整数に変換されます)
     * を Unicode 符号点とみなし, 1 文字分の UTF-8 文字列を返します.
     *
     * @param  array|int $var Unicode 符号点の配列
     * @return string UTF-8 文字列
     */
    public function encode($var)
    {
        return is_array($var) ? array_reduce($var, array($this, "appendChar"), "") : $this->encodeUnicode($var);
    }

    /**
     * 指定された文字列の末尾に, 引数の Unicode 符号点を UTF-8 に変換したバイト列を追加します.
     *
     * @param string $result
     * @param int    $unicode
     * @ignore
     */
    public function appendChar($result, $unicode)
    {
        return $result . $this->encodeUnicode($unicode);
    }

    /**
     * 指定された Unicode 符号点を表現する 1 文字分の UTF-8 文字列を返します.
     * @param  int $unicode Unicode 符号点
     * @return string 引数の Unicode 文字を表現する UTF-8 文字列
     */
    private function encodeUnicode($unicode)
    {
        if (!is_int($unicode)) {
            return $this->encodeUnicode(intval($unicode));
        }
        if ($unicode < 0 || 0xFFFF < $unicode) {
            return $this->encodeUnicode(max(0, $unicode % 0x200000));
        }

        $count = $this->getCharCount($unicode);
        if ($count === 1) {
            return chr($unicode);
        }

        $result = array();
        for ($i = 1; $i < $count; $i++) {
            array_unshift($result, 0x80 + $unicode % 64); // Last 6 bit
            $unicode >>= 6;
        }
        array_unshift($result, $this->getFirstCharPrefix($count) + $unicode);
        return implode("", array_map("chr", $result));
    }

    /**
     * 指定された Unicode 符号点が UTF-8 において何バイトで表現されるか調べます.
     * @param  int $unicode Unicode 符号点
     * @return int バイト数
     */
    private function getCharCount($unicode)
    {
        static $borders = array(
            1 => 0x80,       //  7 bit
            2 => 0x800,      // 11 bit
            3 => 0x10000,    // 16 bit
            4 => 0x200000,   // 21 bit
        );
        foreach ($borders as $i => $border) {
            if ($unicode < $border) {
                return $i;
            }
        }
        // @codeCoverageIgnoreStart
        throw new Exception("Illegal state");
        // @codeCoverageIgnoreEnd
    }

    /**
     * 引数の値に応じて以下の値を返します. (2 進数表現)
     *
     * - 1: 00000000
     * - 2: 11000000
     * - 3: 11100000
     * - 4: 11110000
     * - 5: 11111000
     * - 6: 11111100
     *
     * @param  int $count バイト数
     * @return int 引数のバイト数に応じた値
     */
    private function getFirstCharPrefix($count)
    {
        $result = 0;
        for ($i = 0; $i < $count; $i++) {
            $result >>= 1;
            $result += 0x80;
        }
        return $result;
    }
}


<?php
/**
 * File containing FirstClass
 *
 * @package conquerorsoft/my_first_library
 * @author Christian Varela <cvarela@conquerorsoft.com>
 * @copyright (c) 2017, Conqueror Soft Inc (http://www.conquerorsoft.com)
 */

namespace conquerorsoft\my_first_library;

/**
 * This class provides functionality for encoding and decoding alphanumerical strings including spaces
 * Other characters will throw an exception
 *
 * @author Christian Varela <cvarela@conquerorsoft.com>
 */
class FirstClass
{
    /**
     * Encodes a string by a simple shift of characters
     *
     * @param string $string
     * @return string
     * @throws \Exception
     */
    public function encodeString($string)
    {
        $string=strtolower($string);
        $src="abcdefghijklmnopqrstuvwxyz0123456789 ";
        $dst="jklmnopqrstuvwxyz0123456789abcdefghi ";
        for ($i=0; $i<strlen($string); $i++) {
            $pos=strpos($src, $string[$i]);
            if ($pos===false) {
                throw new \Exception("Please provide only numbers and alphanumerical characters");
            }
            $string[$i]=$dst[$pos];
        }
        return $string;
    }

    /**
     * Decodes a string by a simple shift of characters
     *
     * @param string $string
     * @return string
     * @throws \Exception
     */
    public function decodeString($string)
    {
        $string=strtolower($string);
        $src="jklmnopqrstuvwxyz0123456789abcdefghi ";
        $dst="abcdefghijklmnopqrstuvwxyz0123456789 ";
        for ($i=0; $i<strlen($string); $i++) {
            $pos=strpos($src, $string[$i]);
            if ($pos===false) {
                throw new \Exception("Please provide only numbers and alphanumerical characters");
            }
            $string[$i]=$dst[$pos];
        }
        return $string;
    }
}


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

use Phossa\Query\Statement\ExpressionInterface;
use Phossa\Query\Dialect\Common\SelectStatementInterface;

/**
 * JoinTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     JoinInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait JoinTrait
{
    /**
     * JOINs
     *
     * @var    array
     * @access protected
     */
    protected $clause_join = [];

    /**
     * {@inheritDoc}
     */
    public function realJoin(
        /*# string */ $joinType,
        $table,
        $firstTableCol = '',
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE,
        /*# bool */ $rawMode = false
    ) {
        $join = strtoupper($joinType) . ' JOIN';

        // raw mode
        if ($rawMode || '' === $firstTableCol) {
            $rawMode = true;
            $on = null;

        // groupd on/orOn
        } elseif (is_object($firstTableCol) &&
                $firstTableCol instanceof ExpressionInterface
        ) {
            // object ExpressionInterface
            $on = $firstTableCol;

        } elseif ($this->isRaw($firstTableCol)) {
            $rawMode = true;

            // raw string
            $on = $firstTableCol;

        // col provided
        } else {
            // only ONE colName provided
            if (ClauseInterface::NO_OPERATOR === $operator) {
                $on = [$firstTableCol, '=', $firstTableCol];

            // 2 colNames provides
            } elseif (ClauseInterface::NO_VALUE === $secondTableCol) {
                $on = [$firstTableCol, '=', $operator];

            // 2 colNames and operator provided
            } else {
                $on = [$firstTableCol, $operator, $secondTableCol];
            }
        }

        // check table alias
        if (is_object($table) && $table instanceof SelectStatementInterface) {
            // subquery MUST have alias
            $alias = $table->getAlias();
        } else {
            // find alias in the $table
            $splitted = $this->splitAlias($table);
            if (!$rawMode && isset($splitted[1])) {
                $table = $splitted[0];
                $alias = $splitted[1];
            } else {
                $alias = null;
            }
        }

        $this->clause_join[] = [$rawMode, $join, $table, $on, $alias];

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function join(
        $table,
        $firstTableCol = '',
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE
    ) {
        return $this->realJoin('INNER', $table, $firstTableCol, $operator,
            $secondTableCol);
    }

    /**
     * {@inheritDoc}
     */
    public function innerJoin(
        $table,
        $firstTableCol = '',
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE
    ) {
        return $this->realJoin('INNER', $table, $firstTableCol, $operator,
            $secondTableCol);
    }

    /**
     * {@inheritDoc}
     */
    public function outerJoin(
        $table,
        $firstTableCol = '',
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE
    ) {
        return $this->realJoin(
            'OUTER', $table, $firstTableCol, $operator, $secondTableCol
        );
    }

    /**
     * {@inheritDoc}
     */
    public function leftJoin(
        $table,
        $firstTableCol = '',
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE
    ) {
        return $this->realJoin(
            'LEFT', $table, $firstTableCol, $operator, $secondTableCol
        );
    }

    /**
     * {@inheritDoc}
     */
    public function leftOuterJoin(
        $table,
        $firstTableCol = '',
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE
    ) {
        return $this->realJoin(
            'LEFT OUTER', $table, $firstTableCol, $operator, $secondTableCol
        );
    }

    /**
     * {@inheritDoc}
     */
    public function rightJoin(
        $table,
        $firstTableCol = '',
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE
    ) {
        return $this->realJoin(
            'RIGHT', $table, $firstTableCol, $operator, $secondTableCol
        );
    }

    /**
     * {@inheritDoc}
     */
    public function rightOuterJoin(
        $table,
        $firstTableCol = '',
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE
    ) {
        return $this->realJoin(
            'RIGHT OUTER', $table, $firstTableCol, $operator, $secondTableCol
        );
    }

    /**
     * {@inheritDoc}
     */
    public function fullOuterJoin(
        $table,
        $firstTableCol = '',
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE
    ) {
        return $this->realJoin(
            'FULL OUTER', $table, $firstTableCol, $operator, $secondTableCol
        );
    }

    /**
     * {@inheritDoc}
     */
    public function crossJoin(
        $table,
        $firstTableCol = '',
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE
    ) {
        return $this->realJoin(
            'CROSS', $table, $firstTableCol, $operator, $secondTableCol
        );
    }

    /**
     * Build JOIN
     *
     * @return array
     * @access protected
     */
    protected function buildJoin()/*# : array */
    {
        $result = [];
        foreach ($this->clause_join as $join) {

            // join type, INNER JOIN etc.
            $res = [$join[1]];

            // raw mode
            if ($join[0]) {
                $res[] = $join[2];

            } else {
                // join table
                $tbl = $join[2];
                if (is_object($tbl) && $tbl instanceof SelectStatementInterface) {
                    $res[] = '(' . $tbl->getStatement([], false) . ')';
                } else {
                    $res[] = $this->quote($tbl);
                }

                // table alias if any
                if ($join[4]) {
                    $tbl = $join[4];
                    $res[] = 'AS ' . $this->quote($tbl);
                }

                // on clause
                $res[] = $this->buildJoinOn($join[3], $tbl);
            }

            $result[] = join(' ', $res);
        }
        return $result;
    }

    /**
     * Build ON
     *
     * @param  string|array|object|null $input
     * @param  string $table joined table or table alias
     * @return string
     * @access protected
     */
    protected function buildJoinOn($input, $table)/*# : string */
    {
        // original table
        $tbl1 = $this->getTableName(true);

        if (is_array($input)) {
            $res = ['ON'];

            // first table
            if (false === strpos($input[0], '.')) {
                $res[] = $this->quote($tbl1 . '.' . $input[0]);
            } else {
                $res[] = $this->quote($input[0]);
            }

            // operator
            $res[] = $input[1];

            // second table
            if (false === strpos($input[2], '.')) {
                $res[] = $this->quote($table . '.' . $input[2]);
            } else {
                $res[] = $this->quote($input[2]);
            }
        } elseif (is_object($input)) {
            $res = [$input->getStatement([], false)];

        } elseif (is_string($input)) {
            $res = ['ON', $input];
        }

        return join(' ', $res);
    }

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

    /* utilities from FromTrait */
    abstract protected function getTableName($returnAlias = false)/*# : string */;
    abstract protected function splitAlias(/*# string */ $string)/*# : array */;
}


<?php

namespace MandarinMedien\MMMediaBundle\Form\Type;

use Doctrine\Common\Persistence\ObjectManager;
use MandarinMedien\MMMediaBundle\Entity\Media;
use MandarinMedien\MMMediaBundle\Form\DataTransformer\MediaToMediaSortableCollectionTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;

class UploadCollectionType extends AbstractType
{
    protected $manager;

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

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['multiple'] = $options['multiple'];
        $view->vars['allowed_filetypes'] = $options['allowed_filetypes'];
        $view->vars['value_media_json'] = $this->getJsonFormatedMedias($view->vars['value']);
        // TODO: implement MediaType Configuration
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'multiple' => true,
            'allowed_filetypes' => null,
        ));

        $resolver
            ->setAllowedTypes('multiple', 'boolean')
            ->setAllowedTypes('allowed_filetypes', array('null', 'array'));
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addModelTransformer(new MediaToMediaSortableCollectionTransformer($this->manager));
    }

    public function getParent()
    {
        return HiddenEntityCollectionType::class;
    }

    /**
     * @param Media[] $medias
     *
     * @return string
     */
    public function getJsonFormatedMedias($medias)
    {
        $array = array();

        foreach ($medias as $media) {
            $array[] = array(
                'id' => $media->getId(),
                'name' => $media->getMediaTypeReference(),
                'size' => false,
                'type' => '',
                'url' => '/media/'.$media->getMediaTypeReference(),
            );
        }

        return json_encode($array);
    }
}


<?php

namespace futuretek\shared;

use PHPQRCode\Constants;
use PHPQRCode\QRcode;
use RuntimeException;

/**
 * Class QRPayment
 *
 * This class implements Short Payments Definition version 1.0
 *
 * @package futuretek\shared
 * @author  Lukas Cerny <lukas.cerny@futuretek.cz>
 * @license Apache-2.0
 * @link    http://www.futuretek.cz
 */
class QRPayment
{
    /**
     * Peer to peer
     */
    const PAYMENT_PEER_TO_PEER = 'P2P';

    /**
     * Notify via SMS
     */
    const NOTIFY_PHONE = 'P';

    /**
     * Notify via email
     */
    const NOTIFY_EMAIL = 'E';

    /**
     * Regexp for allowed input characters
     */
    const BINARY_QR_REGEXP = '[0-9A-Z $%*+-./:]';

    /**
     * Parts delimiter
     */
    const DELIMITER = '*';

    /**
     * Key - value delimiter
     */
    const KV_DELIMITER = ':';

    /**
     * @var bool Append CRC32 checksum
     */
    public $appendCRC32 = true;

    /**
     * @var string Spayd version
     */
    protected $version = '1.0';

    /**
     * @var array Spayd content holder
     */
    private $content = [];

    /**
     * @var array Spayd parts definition
     */
    private static $keysDefinition = [
        'ACC' => '[A-Z]{2}\d{2,32}(\+[A-Z0-9]{4}[A-Z]{2}[A-Z0-9]{2,5})?',
        'ALT-ACC' => '[A-Z]{2}\d{2,32}(\+[A-Z0-9]{4}[A-Z]{2}[A-Z0-9]{2,5})?(,[A-Z]{2}\d{2,32}(\+[A-Z0-9]{4}[A-Z]{2}[A-Z0-9]{2,5})?)?',
        'AM' => '^[0-9]{0,10}(\\.[0-9]{0,2})?$',
        'CC' => '[A-Z]{3}',
        'RF' => '\d{1,16}',
        'RN' => '[0-9A-Z $%+-./:]{1,35}',
        'DT' => '[12]\d{3}[01]\d[0-3]\d',
        'PT' => '[0-9A-Z $%+-./:]{1,3}',
        'MSG' => '[0-9A-Z $%+-./:]{1,60}',
        'CRC32' => '[A-F0-9]{8}',
        'NT' => '[PE]',
        'NTA' => '((\+|00)\'{12}|.+@.+\..+)',
        'X-PER' => '\d{1,2}',
        'X-VS' => '\d{1,10}',
        'X-SS' => '\d{1,10}',
        'X-KS' => '\d{1,10}',
        'X-ID' => '[0-9A-Z $%+-./:]{1,20}',
        'X-URL' => '[0-9A-Z $%+-./:]{1,140}',
    ];

    /**
     * Set account
     *
     * @param string $iban IBAN
     * @param string|null $swift SWIFT
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setAccount($iban, $swift = null)
    {
        if ($swift !== null) {
            $iban .= '+' . $swift;
        }

        return $this->add('ACC', $iban);
    }

    /**
     * Set alternative accounts
     *
     * @param string $iban1 Account 1 - IBAN
     * @param string|null $swift1 Account 1 - SWIFT
     * @param string|null $iban2 Account 2 - IBAN
     * @param string|null $swift2 Account 2 - SWIFT
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setAlternativeAccount($iban1, $swift1 = null, $iban2 = null, $swift2 = null)
    {
        if ($swift1 !== null) {
            $iban1 .= '+' . $swift1;
        }
        if ($iban2 !== null) {
            if ($swift2 !== null) {
                $iban2 .= '+' . $swift2;
            }
            $iban1 .= ',' . $iban2;
        }

        return $this->add('ALT-ACC', $iban1);
    }

    /**
     * Set payment amount
     *
     * @param float $amount Amount
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setAmount($amount)
    {
        return $this->add('AM', $amount);
    }

    /**
     * Set currency
     *
     * @param float $code Currency code (USD, EUR, CZK)
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setCurrency($code)
    {
        return $this->add('CC', $code);
    }

    /**
     * Set recipient identificator
     *
     * @param string $id Recipient identificator (number, max 16 digits)
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setRecipientId($id)
    {
        return $this->add('RF', $id);
    }

    /**
     * Set recipient name
     *
     * @param string $name Recipient name (max 16 characters)
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setRecipientName($name)
    {
        return $this->add('RN', $name);
    }

    /**
     * Set due date
     *
     * @param \DateTime $dueDate Due date
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setDueDate(\DateTime $dueDate)
    {
        return $this->add('DT', $dueDate->format('Ymd'));
    }

    /**
     * Set payment type
     *
     * @param string $paymentType Payment type - see constants PAYMENT_*
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setPaymentType($paymentType)
    {
        if (self::PAYMENT_PEER_TO_PEER !== $paymentType) {
            throw new RuntimeException(Tools::poorManTranslate('fts-shared', 'Invalid payment type.'));
        }

        return $this->add('PT', $paymentType);
    }

    /**
     * Set message
     *
     * @param string $message Message (max. 60 characters)
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setMessage($message)
    {
        return $this->add('MSG', $message);
    }

    /**
     * Set notify type (bank-specific)
     *
     * @param string $notifyType Notify type - see constants NOTIFY_*
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setNotifyType($notifyType)
    {
        if (!\in_array($notifyType, [self::NOTIFY_EMAIL, self::NOTIFY_PHONE], true)) {
            throw new RuntimeException(Tools::poorManTranslate('fts-shared', 'Invalid notify type.'));
        }

        return $this->add('NT', $notifyType);
    }

    /**
     * Set notify target (phone number or email address)
     *
     * @param string $address Notify address
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setNotifyAddress($address)
    {
        return $this->add('NTA', $address);
    }

    /**
     * Set payment execution retry (in case there is not enough funds on senders account)
     *
     * @param string $days Number of days
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setPaymentExecutionRetry($days)
    {
        return $this->add('X-PER', (int)$days);
    }

    /**
     * Set variable symbol
     *
     * @param string $vs Variable symbol
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setVS($vs)
    {
        return $this->add('X-VS', (int)$vs);
    }

    /**
     * Set specific symbol
     *
     * @param string $ss Specific symbol
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setSS($ss)
    {
        return $this->add('X-SS', (int)$ss);
    }

    /**
     * Set constant symbol
     *
     * @param string $ks Constant symbol
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setKS($ks)
    {
        return $this->add('X-KS', (int)$ks);
    }

    /**
     * Set sender identificator
     *
     * @param string $id Sender identificator (max 20 characters)
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setSenderId($id)
    {
        return $this->add('X-ID', $id);
    }

    /**
     * Set URL
     *
     * @param string $url URL address (max. 140 characters)
     * @return QRPayment
     * @throws RuntimeException
     */
    public function setUrl($url)
    {
        return $this->add('X-URL', $url);
    }

    /**
     * @param string $key
     * @param string $value
     * @return QRPayment
     * @throws RuntimeException
     */
    protected function add($key, $value)
    {
        $key = $this->normalizeKey($key);
        if (!array_key_exists($key, self::$keysDefinition) && strpos($key, 'X-') !== 0) {
            throw new RuntimeException(Tools::poorManTranslate('fts-shared', 'Key {key} is not defined in specification.', ['key' => $key]));
        }

        if (array_key_exists($key, self::$keysDefinition) && !preg_match('~^' . self::$keysDefinition[$key] . '$~', $value)) {
            throw new RuntimeException(Tools::poorManTranslate('fts-shared', 'Key {key} with value {value} does not match defined format.', ['key' => $key, 'value' => $value]));
        }

        $this->content[$key] = $value;

        return $this;
    }

    /**
     * @param string $key
     * @return QRPayment
     */
    protected function delete($key)
    {
        unset($this->content[$this->normalizeKey($key)]);

        return $this;
    }

    /**
     * Normalize key
     *
     * @param string $key
     * @return string
     */
    private function normalizeKey($key)
    {
        return strtoupper($key);
    }

    /**
     * Generate SPD as text
     *
     * @return string
     */
    public function generateText()
    {
        $result = 'SPD' . self::DELIMITER . $this->version . self::DELIMITER . $this->implodeContent();

        if ($this->appendCRC32) {
            $result .= self::DELIMITER . 'CRC32:' . sprintf('%x', crc32($result));
        }

        return $result;
    }

    /**
     * Generate SPD as PNG image and output it
     *
     * @param string|bool $filename Image filename
     * @param int $level QR code error correction level - please see Constants::QR_ECLEVEL_*
     * @param int $size QR code size (1 - 1024)
     * @param int $margin QR code margin
     */
    public function generateImage($filename = false, $level = Constants::QR_ECLEVEL_L, $size = 3, $margin = 4)
    {
        $result = 'SPD' . self::DELIMITER . $this->version . self::DELIMITER . $this->implodeContent();

        if ($this->appendCRC32) {
            $result .= self::DELIMITER . 'CRC32:' . sprintf('%x', crc32($result));
        }

        QRcode::png($result, $filename, $level, $size, $margin);
        die();
    }

    /**
     * Generate SPD
     *
     * @return string
     *
     * @deprecated  Please use QRPayment::generateText() instead
     */
    public function generate()
    {
        return $this->generateText();
    }

    /**
     * Build Spayd content from parts
     *
     * @return string
     */
    private function implodeContent()
    {
        ksort($this->content);
        $output = '';
        foreach ($this->content as $key => $value) {
            $output .= $key . self::KV_DELIMITER . $value . self::DELIMITER;
        }

        return rtrim($output, self::DELIMITER);
    }

    /**
     * Normalize account number
     *
     * @param string $account Account number
     * @return string
     */
    public static function normalizeAccountNumber($account)
    {
        $account = str_replace(' ', '', $account);
        if (false === strpos($account, '-')) {
            $account = '000000-' . $account;
        }
        $parts = explode('-', $account);
        $parts[0] = str_pad($parts[0], 6, '0', STR_PAD_LEFT);
        $parts2 = explode('/', $parts[1]);
        $parts2[0] = str_pad($parts2[0], 10, '0', STR_PAD_LEFT);
        $parts2[1] = str_pad($parts2[1], 4, '0', STR_PAD_LEFT);
        $parts[1] = implode('/', $parts2);

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

    /**
     * Convert bank account number to IBAN
     *
     * @param string $account Normal account number in format: prefix-account/bank
     * @param string $country ISO standard country code
     * @return string IBAN
     * @throws RuntimeException
     */
    public static function accountToIBAN($account, $country = 'CZ')
    {
        $allowedCountries = ['AT', 'BE', 'BG', 'CZ', 'CY', 'DK', 'EE', 'FI', 'FR', 'DE', 'GI', 'GR', 'HU', 'IE', 'IS', 'IT', 'LI', 'LT', 'LU', 'LV', 'MC', 'MT', 'NL', 'NO', 'PL', 'PT', 'RO', 'SE', 'CH', 'SI', 'SK', 'ES', 'GB'];

        $account = self::normalizeAccountNumber($account);

        $accountArray = explode('/', str_replace('-', '', $account));
        if (2 !== \count($accountArray)) {
            throw new RuntimeException(Tools::poorManTranslate('fts-shared', 'Wrong bank account (some part missing).'));
        }

        $country = strtoupper($country);
        if (!\in_array($country, $allowedCountries, true)) {
            throw new RuntimeException(Tools::poorManTranslate('fts-shared', 'Invalid country code.'));
        }

        $accountStr = str_pad($accountArray[1], 4, '0', STR_PAD_LEFT) . str_pad($accountArray[0], 16, '0', STR_PAD_LEFT) . (\ord($country[0]) - 55) . (\ord($country[1]) - 55) . '00';
        $crc = '';
        $pos = 0;

        while (\strlen($accountStr) > 0) {
            $len = 9 - \strlen($crc);
            $crc = (int)($crc . substr($accountStr, $pos, $len)) % 97;
            $accountStr = substr($accountStr, $len);
        }

        return ($country . str_pad(98 - $crc, 2, '0', STR_PAD_LEFT) . $accountArray[1] . $accountArray[0]);
    }
}


<?php

namespace Peyote;

/**
 * An abstract starting class for the ORDER BY and GROUP BY classes.
 *
 * @package    Peyote
 * @author     Dave Widmer <dave@davewidmer.net>
 */
abstract class Sort implements \Peyote\Builder
{
	/**
	 * @var array  The order clauses.
	 */
	protected $clauses = array();

	/**
	 * Gets the type of sorting query we are running.
	 *
	 * @return string
	 */
	abstract public function getType();

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

		$sql = array();
		foreach ($this->clauses as $clause)
		{
			list($column, $direction) = $clause;

			if ($direction === null)
			{
				$sql[] = $column;
			}
			else
			{
				$sql[] = "{$column} {$direction}";
			}
		}

		return $this->getType()." ".join(", ", $sql);
	}

}


<?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\Action;
use yii\base\InvalidParamException;

/**
 * ViewAction represents an action that displays a view according to a user-specified parameter.
 *
 * By default, the view being displayed is specified via the `view` GET parameter.
 * The name of the GET parameter can be customized via [[viewParam]].
 *
 * Users specify a view in the format of `path/to/view`, which translates to the view name
 * `ViewPrefix/path/to/view` where `ViewPrefix` is given by [[viewPrefix]]. The view will then
 * be rendered by the [[\yii\base\Controller::render()|render()]] method of the currently active controller.
 *
 * Note that the user-specified view name must start with a word character and can only contain
 * word characters, forward slashes, dots and dashes.
 *
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class ViewAction extends Action
{
    /**
     * @var string the name of the GET parameter that contains the requested view name.
     */
    public $viewParam = 'view';
    /**
     * @var string the name of the default view when [[\yii\web\ViewAction::$viewParam]] GET parameter is not provided
     * by user. Defaults to 'index'. This should be in the format of 'path/to/view', similar to that given in the
     * GET parameter.
     * @see \yii\web\ViewAction::$viewPrefix
     */
    public $defaultView = 'index';
    /**
     * @var string a string to be prefixed to the user-specified view name to form a complete view name.
     * For example, if a user requests for `tutorial/chap1`, the corresponding view name will
     * be `pages/tutorial/chap1`, assuming the prefix is `pages`.
     * The actual view file is determined by [[\yii\base\View::findViewFile()]].
     * @see \yii\base\View::findViewFile()
     */
    public $viewPrefix = 'pages';
    /**
     * @var mixed the name of the layout to be applied to the requested view.
     * This will be assigned to [[\yii\base\Controller::$layout]] before the view is rendered.
     * Defaults to null, meaning the controller's layout will be used.
     * If false, no layout will be applied.
     */
    public $layout;

    /**
     * Runs the action.
     * This method displays the view requested by the user.
     * @throws NotFoundHttpException if the view file cannot be found
     */
    public function run()
    {
        $viewName = $this->resolveViewName();
        $this->controller->actionParams[$this->viewParam] = Yii::$app->request->get($this->viewParam);

        $controllerLayout = null;
        if ($this->layout !== null) {
            $controllerLayout = $this->controller->layout;
            $this->controller->layout = $this->layout;
        }

        try {
            $output = $this->render($viewName);

            if ($controllerLayout) {
                $this->controller->layout = $controllerLayout;
            }

        } catch (InvalidParamException $e) {

            if ($controllerLayout) {
                $this->controller->layout = $controllerLayout;
            }

            if (YII_DEBUG) {
                throw new NotFoundHttpException($e->getMessage());
            } else {
                throw new NotFoundHttpException(
                    Yii::t('yii', 'The requested view "{name}" was not found.', ['name' => $viewName])
                );
            }
        }

        return $output;
    }

    /**
     * Renders a view
     *
     * @param string $viewName view name
     * @return string result of the rendering
     */
    protected function render($viewName)
    {
        return $this->controller->render($viewName);
    }

    /**
     * Resolves the view name currently being requested.
     *
     * @return string the resolved view name
     * @throws NotFoundHttpException if the specified view name is invalid
     */
    protected function resolveViewName()
    {
        $viewName = Yii::$app->request->get($this->viewParam, $this->defaultView);

        if (!is_string($viewName) || !preg_match('~^\w(?:(?!\/\.{0,2}\/)[\w\/\-\.])*$~', $viewName)) {
            if (YII_DEBUG) {
                throw new NotFoundHttpException("The requested view \"$viewName\" must start with a word character, must not contain /../ or /./, can contain only word characters, forward slashes, dots and dashes.");
            } else {
                throw new NotFoundHttpException(Yii::t('yii', 'The requested view "{name}" was not found.', ['name' => $viewName]));
            }
        }

        return empty($this->viewPrefix) ? $viewName : $this->viewPrefix . '/' . $viewName;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: christof
 * Date: 11.11.15
 * Time: 18:04.
 */
namespace MandarinMedien\MMMediaBundle\MediaType;

use MandarinMedien\MMMediaBundle\Model\MediaTypeInterface;

class MediaTypeManager
{
    /**
     * @var MediaTypeInterface[]
     */
    protected $mediaTypes;

    public function __construct(array $mediaTypes)
    {
        foreach ($mediaTypes as $mediaType) {
            $this->registerMediaType($mediaType);
        }
    }

    /**
     * register new mediaType.
     *
     * @param string $mediaType class name of mediatype
     *
     * @return $this
     *
     * @throws \Exception
     */
    public function registerMediaType($mediaType)
    {
        if ($this->check($mediaType)) {
            $this->mediaTypes[(new \ReflectionClass($mediaType))->getConstant('NAME')] = $mediaType;

            return $this;
        } else {
            throw new \Exception('registered MediaType must implement \MandarinMedien\MMMediaBundle\Model\MediaTypeInterface');
        }
    }

    /**
     * get registered MediaTypes.
     *
     * @return \MandarinMedien\MMMediaBundle\Model\MediaTypeInterface[]
     */
    public function getMediaTypes()
    {
        return $this->mediaTypes;
    }

    /**
     * return a new instance of best-matching MediaType.
     *
     * @param string|array $data raw media data
     *
     * @return MediaTypeInterface|null
     */
    public function getMediaTypeMatch($data)
    {
        foreach ($this->getMediaTypes() as $mediaTypeClass) {
            $instance = forward_static_call(array($mediaTypeClass, 'check'), $data);

            if ($instance) {
                return $instance;
            }
        }
    }

    /**
     * check if given class implements MediaTypeInterface.
     *
     * @param $mediaType
     *
     * @return bool
     */
    protected function check($mediaType)
    {
        return (new \ReflectionClass($mediaType))
            ->implementsInterface('\MandarinMedien\MMMediaBundle\Model\MediaTypeInterface');
    }

    /**
     * @param $name
     *
     * @return MediaTypeInterface|null
     */
    public function getInstanceByName($name)
    {
        $mts = $this->getMediaTypes();

        if (isset($mts[$name])) {
            return new $mts[$name]();
        }

        return;
    }
}


<?php

namespace MandarinMedien\MMMediaBundle\DependencyInjection;

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

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

        $this->addMediaTypesSection($rootNode);
        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }

    private function addMediaTypesSection(ArrayNodeDefinition $node)
    {
        $node
            ->children()
                ->arrayNode('media_types')
                    ->children()
                        ->arrayNode('types')
                        ->prototype('scalar')->end()
                        ->defaultValue(array(
                            'MandarinMedien\\MMMediaBundle\\MediaType\\ImageMediaType',
                            'MandarinMedien\\MMMediaBundle\\MediaType\\FileMediaType',
                            'MandarinMedien\\MMMediaBundle\\MediaType\\VideoMediaType',
                            'MandarinMedien\\MMMediaBundle\\MediaType\\YoutubeMediaType',
                            'MandarinMedien\\MMMediaBundle\\MediaType\\VimeoMediaType',
                        ))
                        ->end()
//                      ->arrayNode('allowed')
//                          ->prototype('array')
//                              ->defaultValue(array())
//                          ->end()
//                      ->end()
                    ->end()
                ->end()
            ->end();
    }
}


<?php
declare(strict_types=1);

namespace Stratadox\IdentityMap;

use function array_keys;
use function array_merge as these;
use function array_values as allThese;
use function assert as makeSureThat;
use function get_class as theClassOfThe;
use function is_null as weDidNotYetList;
use function is_object as itIsAn;
use function spl_object_id as theInstanceIdOf;

/**
 * Contains objects by class and id.
 *
 * @author Stratadox
 */
final class IdentityMap implements MapsObjectsByIdentity
{
    private $objectWith;
    private $entityIdFor;
    private $objects;

    private function __construct(array $objectsByClassAndId, array $idsByObject)
    {
        $this->objectWith = $objectsByClassAndId;
        $this->entityIdFor = $idsByObject;
    }

    /**
     * Produces a new identity map that contains the objects.
     *
     * @param object[] $theseObjects The objects to add, as [id => object]
     * @return MapsObjectsByIdentity The map of objects.
     */
    public static function with(array $theseObjects): MapsObjectsByIdentity
    {
        $objects = [];
        $entityIds = [];
        foreach ($theseObjects as $id => $object) {
            $objects = IdentityMap::addTo($objects, (string) $id, $object);
            $entityIds[theInstanceIdOf($object)] = (string) $id;
        }
        return new self($objects, $entityIds);
    }

    /**
     * Produces an empty identity map.
     *
     * @return MapsObjectsByIdentity The empty map of objects.
     */
    public static function startEmpty(): MapsObjectsByIdentity
    {
        return new self([], []);
    }

    /** @inheritdoc */
    public function has(string $class, string $id): bool
    {
        return isset($this->objectWith[$class][$id]);
    }

    /** @inheritdoc */
    public function hasThe(object $object): bool
    {
        return isset($this->entityIdFor[theInstanceIdOf($object)]);
    }

    /** @inheritdoc */
    public function get(string $class, string $id): object
    {
        $this->mustHave($class, $id);
        return $this->objectWith[$class][$id];
    }

    /** @inheritdoc */
    public function add(string $id, object $object): MapsObjectsByIdentity
    {
        $class = theClassOfThe($object);
        $this->mayNotAlreadyHave($class, $id);

        $new = clone $this;
        $new->objectWith[$class][$id] = $object;
        $new->entityIdFor[theInstanceIdOf($object)] = $id;
        return $new;
    }

    /** @inheritdoc */
    public function remove(string $class, string $id): MapsObjectsByIdentity
    {
        $this->mustHave($class, $id);
        $entityIdFor = $this->entityIdFor;
        $objectWith = $this->objectWith;
        unset(
            $entityIdFor[theInstanceIdOf($objectWith[$class][$id])],
            $objectWith[$class][$id]
        );
        return new IdentityMap($objectWith, $entityIdFor);
    }

    /** @inheritdoc */
    public function removeThe(object $object): MapsObjectsByIdentity
    {
        return $this->remove(theClassOfThe($object), $this->idOf($object));
    }

    /** @inheritdoc */
    public function idOf(object $object): string
    {
        if (!isset($this->entityIdFor[theInstanceIdOf($object)])) {
            throw IdentityNotFound::forThe($object);
        }
        return $this->entityIdFor[theInstanceIdOf($object)];
    }

    public function objects(): array
    {
        if (weDidNotYetList($this->objects)) {
            $objects = [];
            foreach ($this->objectWith as $class => $objectsById) {
                $objects[] = allThese($objectsById);
            }
            $this->objects = these(...$objects);
        }
        return $this->objects;
    }

    /** @throws NoSuchObject */
    private function mustHave(string $class, string $id): void
    {
        if ($this->has($class, $id)) {
            return;
        }
        throw IdentityNotFound::requesting($class, $id);
    }

    /** @throws AlreadyThere */
    private function mayNotAlreadyHave(string $class, string $id): void
    {
        if ($this->has($class, $id)) {
            throw DuplicationDetected::in($class, $id);
        }
    }

    private static function addTo(
        array $objectsBy,
        string $withId,
        object $object
    ): array {
        $objectsBy[theClassOfThe($object)][$withId] = $object;
        return $objectsBy;
    }
}


<?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.0.1
 */
namespace Peach\DT\SimpleFormat;

use Peach\Util\ArrayMap;

/**
 * 連続した数字文字列にマッチする Pattern です.
 *
 * @ignore
 */
class Numbers implements Pattern
{
    /**
     * 適用先のフィールド名です.
     * @var string
     */
    private $fieldName;

    /**
     * マッチするパターン文字列です.
     * @var string
     */
    private $patternString;

    /**
     * フィールド名とパターン文字列を指定して, 新しい Numbers オブジェクトを生成します.
     *
     * @param string $fieldName     適用対象のフィールド
     * @param string $patternString 正規表現
     * @codeCoverageIgnore
     */
    public function __construct($fieldName, $patternString)
    {
        $this->fieldName     = $fieldName;
        $this->patternString = $patternString;
    }

    /**
     * マッチした文字列を整数に変換した値を適用します.
     *
     * @param ArrayMap $fields  適用先のフィールド
     * @param string   $matched マッチした文字列
     */
    public function apply(ArrayMap $fields, $matched)
    {
        $fields->put($this->fieldName, intval($matched));
    }

    /**
     * 文字列の先頭が, このオブジェクトにセットされている正規表現に合致しているかどうか調べます.
     * マッチした文字列を返します.
     *
     * @param  string $input 検査対象の文字列
     * @return string        マッチした結果
     */
    public function match($input)
    {
        $matched = array();
        $test    = preg_match("/^{$this->patternString}/", $input, $matched);
        return $test ? $matched[0] : null;
    }
}


<?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\base\InvalidValueException;

/**
 * User is the class for the "user" application component that manages the user authentication status.
 *
 * You may use [[isGuest]] to determine whether the current user is a guest or not.
 * If the user is a guest, the [[identity]] property would return null. Otherwise, it would
 * be an instance of [[IdentityInterface]].
 *
 * You may call various methods to change the user authentication status:
 *
 * - [[login()]]: sets the specified identity and remembers the authentication status in session and cookie.
 * - [[logout()]]: marks the user as a guest and clears the relevant information from session and cookie.
 * - [[setIdentity()]]: changes the user identity without touching session or cookie.
 *   This is best used in stateless RESTful API implementation.
 *
 * Note that User only maintains the user authentication status. It does NOT handle how to authenticate
 * a user. The logic of how to authenticate a user should be done in the class implementing [[IdentityInterface]].
 * You are also required to set [[identityClass]] with the name of this class.
 *
 * User is configured as an application component in [[\yii\web\Application]] by default.
 * You can access that instance via `Yii::$app->user`.
 *
 * You can modify its configuration by adding an array to your application config under `components`
 * as it is shown in the following example:
 *
 * ```php
 * 'user' => [
 *     'identityClass' => 'app\models\User', // User must implement the IdentityInterface
 *     'enableAutoLogin' => true,
 *     // 'loginUrl' => ['user/login'],
 *     // ...
 * ]
 * ```
 *
 * @property string|integer $id The unique identifier for the user. If null, it means the user is a guest.
 * This property is read-only.
 * @property IdentityInterface|null $identity The identity object associated with the currently logged-in
 * user. `null` is returned if the user is not logged in (not authenticated).
 * @property boolean $isGuest Whether the current user is a guest. This property is read-only.
 * @property string $returnUrl The URL that the user should be redirected to after login. Note that the type
 * of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class User extends Component
{
    const EVENT_BEFORE_LOGIN = 'beforeLogin';
    const EVENT_AFTER_LOGIN = 'afterLogin';
    const EVENT_BEFORE_LOGOUT = 'beforeLogout';
    const EVENT_AFTER_LOGOUT = 'afterLogout';

    /**
     * @var string the class name of the [[identity]] object.
     */
    public $identityClass;
    /**
     * @var boolean whether to enable cookie-based login. Defaults to false.
     * Note that this property will be ignored if [[enableSession]] is false.
     */
    public $enableAutoLogin = false;
    /**
     * @var boolean whether to use session to persist authentication status across multiple requests.
     * You set this property to be false if your application is stateless, which is often the case
     * for RESTful APIs.
     */
    public $enableSession = true;
    /**
     * @var string|array the URL for login when [[loginRequired()]] is called.
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
     * The first element of the array should be the route to the login action, and the rest of
     * the name-value pairs are GET parameters used to construct the login URL. For example,
     *
     * ```php
     * ['site/login', 'ref' => 1]
     * ```
     *
     * If this property is null, a 403 HTTP exception will be raised when [[loginRequired()]] is called.
     */
    public $loginUrl = ['site/login'];
    /**
     * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true.
     * @see Cookie
     */
    public $identityCookie = ['name' => '_identity', 'httpOnly' => true];
    /**
     * @var integer the number of seconds in which the user will be logged out automatically if he
     * remains inactive. If this property is not set, the user will be logged out after
     * the current session expires (c.f. [[Session::timeout]]).
     * Note that this will not work if [[enableAutoLogin]] is true.
     */
    public $authTimeout;
    /**
     * @var integer the number of seconds in which the user will be logged out automatically
     * regardless of activity.
     * Note that this will not work if [[enableAutoLogin]] is true.
     */
    public $absoluteAuthTimeout;
    /**
     * @var boolean whether to automatically renew the identity cookie each time a page is requested.
     * This property is effective only when [[enableAutoLogin]] is true.
     * When this is false, the identity cookie will expire after the specified duration since the user
     * is initially logged in. When this is true, the identity cookie will expire after the specified duration
     * since the user visits the site the last time.
     * @see enableAutoLogin
     */
    public $autoRenewCookie = true;
    /**
     * @var string the session variable name used to store the value of [[id]].
     */
    public $idParam = '__id';
    /**
     * @var string the session variable name used to store the value of expiration timestamp of the authenticated state.
     * This is used when [[authTimeout]] is set.
     */
    public $authTimeoutParam = '__expire';
    /**
     * @var string the session variable name used to store the value of absolute expiration timestamp of the authenticated state.
     * This is used when [[absoluteAuthTimeout]] is set.
     */
    public $absoluteAuthTimeoutParam = '__absoluteExpire';
    /**
     * @var string the session variable name used to store the value of [[returnUrl]].
     */
    public $returnUrlParam = '__returnUrl';

    private $_access = [];

    /**
     * Initializes the application component.
     */
    public function init()
    {
        parent::init();

        if ($this->identityClass === null) {
            throw new InvalidConfigException('User::identityClass must be set.');
        }
        if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) {
            throw new InvalidConfigException('User::identityCookie must contain the "name" element.');
        }
    }

    private $_identity = false;

    /**
     * Returns the identity object associated with the currently logged-in user.
     * When [[enableSession]] is true, this method may attempt to read the user's authentication data
     * stored in session and reconstruct the corresponding identity object, if it has not done so before.
     * @param boolean $autoRenew whether to automatically renew authentication status if it has not been done so before.
     * This is only useful when [[enableSession]] is true.
     * @return IdentityInterface|null the identity object associated with the currently logged-in user.
     * `null` is returned if the user is not logged in (not authenticated).
     * @see login()
     * @see logout()
     */
    public function getIdentity($autoRenew = true)
    {
        if ($this->_identity === false) {
            if ($this->enableSession && $autoRenew) {
                $this->_identity = null;
                $this->renewAuthStatus();
            } else {
                return null;
            }
        }

        return $this->_identity;
    }

    /**
     * Sets the user identity object.
     *
     * Note that this method does not deal with session or cookie. You should usually use [[switchIdentity()]]
     * to change the identity of the current user.
     *
     * @param IdentityInterface|null $identity the identity object associated with the currently logged user.
     * If null, it means the current user will be a guest without any associated identity.
     * @throws InvalidValueException if `$identity` object does not implement [[IdentityInterface]].
     */
    public function setIdentity($identity)
    {
        if ($identity instanceof IdentityInterface) {
            $this->_identity = $identity;
            $this->_access = [];
        } elseif ($identity === null) {
            $this->_identity = null;
        } else {
            throw new InvalidValueException('The identity object must implement IdentityInterface.');
        }
    }

    /**
     * Logs in a user.
     *
     * After logging in a user, you may obtain the user's identity information from the [[identity]] property.
     * If [[enableSession]] is true, you may even get the identity information in the next requests without
     * calling this method again.
     *
     * The login status is maintained according to the `$duration` parameter:
     *
     * - `$duration == 0`: the identity information will be stored in session and will be available
     *   via [[identity]] as long as the session remains active.
     * - `$duration > 0`: the identity information will be stored in session. If [[enableAutoLogin]] is true,
     *   it will also be stored in a cookie which will expire in `$duration` seconds. As long as
     *   the cookie remains valid or the session is active, you may obtain the user identity information
     *   via [[identity]].
     *
     * Note that if [[enableSession]] is false, the `$duration` parameter will be ignored as it is meaningless
     * in this case.
     *
     * @param IdentityInterface $identity the user identity (which should already be authenticated)
     * @param integer $duration number of seconds that the user can remain in logged-in status.
     * Defaults to 0, meaning login till the user closes the browser or the session is manually destroyed.
     * If greater than 0 and [[enableAutoLogin]] is true, cookie-based login will be supported.
     * Note that if [[enableSession]] is false, this parameter will be ignored.
     * @return boolean whether the user is logged in
     */
    public function login(IdentityInterface $identity, $duration = 0)
    {
        if ($this->beforeLogin($identity, false, $duration)) {
            $this->switchIdentity($identity, $duration);
            $id = $identity->getId();
            $ip = Yii::$app->getRequest()->getUserIP();
            if ($this->enableSession) {
                $log = "User '$id' logged in from $ip with duration $duration.";
            } else {
                $log = "User '$id' logged in from $ip. Session not enabled.";
            }
            Yii::info($log, __METHOD__);
            $this->afterLogin($identity, false, $duration);
        }

        return !$this->getIsGuest();
    }

    /**
     * Logs in a user by the given access token.
     * This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
     * with the provided access token. If successful, it will call [[login()]] to log in the authenticated user.
     * If authentication fails or [[login()]] is unsuccessful, it will return null.
     * @param string $token the access token
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return IdentityInterface|null the identity associated with the given access token. Null is returned if
     * the access token is invalid or [[login()]] is unsuccessful.
     */
    public function loginByAccessToken($token, $type = null)
    {
        /* @var $class IdentityInterface */
        $class = $this->identityClass;
        $identity = $class::findIdentityByAccessToken($token, $type);
        if ($identity && $this->login($identity)) {
            return $identity;
        } else {
            return null;
        }
    }

    /**
     * Logs in a user by cookie.
     *
     * This method attempts to log in a user using the ID and authKey information
     * provided by the [[identityCookie|identity cookie]].
     */
    protected function loginByCookie()
    {
        $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
        if ($value === null) {
            return;
        }

        $data = json_decode($value, true);
        if (count($data) !== 3 || !isset($data[0], $data[1], $data[2])) {
            return;
        }

        list ($id, $authKey, $duration) = $data;
        /* @var $class IdentityInterface */
        $class = $this->identityClass;
        $identity = $class::findIdentity($id);
        if ($identity === null) {
            return;
        } elseif (!$identity instanceof IdentityInterface) {
            throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
        }

        if ($identity->validateAuthKey($authKey)) {
            if ($this->beforeLogin($identity, true, $duration)) {
                $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
                $ip = Yii::$app->getRequest()->getUserIP();
                Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
                $this->afterLogin($identity, true, $duration);
            }
        } else {
            Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
        }
    }

    /**
     * Logs out the current user.
     * This will remove authentication-related session data.
     * If `$destroySession` is true, all session data will be removed.
     * @param boolean $destroySession whether to destroy the whole session. Defaults to true.
     * This parameter is ignored if [[enableSession]] is false.
     * @return boolean whether the user is logged out
     */
    public function logout($destroySession = true)
    {
        $identity = $this->getIdentity();
        if ($identity !== null && $this->beforeLogout($identity)) {
            $this->switchIdentity(null);
            $id = $identity->getId();
            $ip = Yii::$app->getRequest()->getUserIP();
            Yii::info("User '$id' logged out from $ip.", __METHOD__);
            if ($destroySession && $this->enableSession) {
                Yii::$app->getSession()->destroy();
            }
            $this->afterLogout($identity);
        }

        return $this->getIsGuest();
    }

    /**
     * Returns a value indicating whether the user is a guest (not authenticated).
     * @return boolean whether the current user is a guest.
     * @see getIdentity()
     */
    public function getIsGuest()
    {
        return $this->getIdentity() === null;
    }

    /**
     * Returns a value that uniquely represents the user.
     * @return string|integer the unique identifier for the user. If null, it means the user is a guest.
     * @see getIdentity()
     */
    public function getId()
    {
        $identity = $this->getIdentity();

        return $identity !== null ? $identity->getId() : null;
    }

    /**
     * Returns the URL that the browser should be redirected to after successful login.
     *
     * This method reads the return URL from the session. It is usually used by the login action which
     * may call this method to redirect the browser to where it goes after successful authentication.
     *
     * @param string|array $defaultUrl the default return URL in case it was not set previously.
     * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
     * Please refer to [[setReturnUrl()]] on accepted format of the URL.
     * @return string the URL that the user should be redirected to after login.
     * @see loginRequired()
     */
    public function getReturnUrl($defaultUrl = null)
    {
        $url = Yii::$app->getSession()->get($this->returnUrlParam, $defaultUrl);
        if (is_array($url)) {
            if (isset($url[0])) {
                return Yii::$app->getUrlManager()->createUrl($url);
            } else {
                $url = null;
            }
        }

        return $url === null ? Yii::$app->getHomeUrl() : $url;
    }

    /**
     * Remembers the URL in the session so that it can be retrieved back later by [[getReturnUrl()]].
     * @param string|array $url the URL that the user should be redirected to after login.
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
     * The first element of the array should be the route, and the rest of
     * the name-value pairs are GET parameters used to construct the URL. For example,
     *
     * ```php
     * ['admin/index', 'ref' => 1]
     * ```
     */
    public function setReturnUrl($url)
    {
        Yii::$app->getSession()->set($this->returnUrlParam, $url);
    }

    /**
     * Redirects the user browser to the login page.
     *
     * Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[returnUrl]] so that
     * the user browser may be redirected back to the current page after successful login.
     *
     * Make sure you set [[loginUrl]] so that the user browser can be redirected to the specified login URL after
     * calling this method.
     *
     * Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
     *
     * @param boolean $checkAjax whether to check if the request is an AJAX request. When this is true and the request
     * is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.
     * @return Response the redirection response if [[loginUrl]] is set
     * @throws ForbiddenHttpException the "Access Denied" HTTP exception if [[loginUrl]] is not set
     */
    public function loginRequired($checkAjax = true)
    {
        $request = Yii::$app->getRequest();
        if ($this->enableSession && (!$checkAjax || !$request->getIsAjax())) {
            $this->setReturnUrl($request->getUrl());
        }
        if ($this->loginUrl !== null) {
            $loginUrl = (array) $this->loginUrl;
            if ($loginUrl[0] !== Yii::$app->requestedRoute) {
                return Yii::$app->getResponse()->redirect($this->loginUrl);
            }
        }
        throw new ForbiddenHttpException(Yii::t('yii', 'Login Required'));
    }

    /**
     * This method is called before logging in a user.
     * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
     * @param IdentityInterface $identity the user identity information
     * @param boolean $cookieBased whether the login is cookie-based
     * @param integer $duration number of seconds that the user can remain in logged-in status.
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
     * @return boolean whether the user should continue to be logged in
     */
    protected function beforeLogin($identity, $cookieBased, $duration)
    {
        $event = new UserEvent([
            'identity' => $identity,
            'cookieBased' => $cookieBased,
            'duration' => $duration,
        ]);
        $this->trigger(self::EVENT_BEFORE_LOGIN, $event);

        return $event->isValid;
    }

    /**
     * This method is called after the user is successfully logged in.
     * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
     * @param IdentityInterface $identity the user identity information
     * @param boolean $cookieBased whether the login is cookie-based
     * @param integer $duration number of seconds that the user can remain in logged-in status.
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
     */
    protected function afterLogin($identity, $cookieBased, $duration)
    {
        $this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent([
            'identity' => $identity,
            'cookieBased' => $cookieBased,
            'duration' => $duration,
        ]));
    }

    /**
     * This method is invoked when calling [[logout()]] to log out a user.
     * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
     * @param IdentityInterface $identity the user identity information
     * @return boolean whether the user should continue to be logged out
     */
    protected function beforeLogout($identity)
    {
        $event = new UserEvent([
            'identity' => $identity,
        ]);
        $this->trigger(self::EVENT_BEFORE_LOGOUT, $event);

        return $event->isValid;
    }

    /**
     * This method is invoked right after a user is logged out via [[logout()]].
     * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
     * @param IdentityInterface $identity the user identity information
     */
    protected function afterLogout($identity)
    {
        $this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent([
            'identity' => $identity,
        ]));
    }

    /**
     * Renews the identity cookie.
     * This method will set the expiration time of the identity cookie to be the current time
     * plus the originally specified cookie duration.
     */
    protected function renewIdentityCookie()
    {
        $name = $this->identityCookie['name'];
        $value = Yii::$app->getRequest()->getCookies()->getValue($name);
        if ($value !== null) {
            $data = json_decode($value, true);
            if (is_array($data) && isset($data[2])) {
                $cookie = new Cookie($this->identityCookie);
                $cookie->value = $value;
                $cookie->expire = time() + (int) $data[2];
                Yii::$app->getResponse()->getCookies()->add($cookie);
            }
        }
    }

    /**
     * Sends an identity cookie.
     * This method is used when [[enableAutoLogin]] is true.
     * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
     * information in the cookie.
     * @param IdentityInterface $identity
     * @param integer $duration number of seconds that the user can remain in logged-in status.
     * @see loginByCookie()
     */
    protected function sendIdentityCookie($identity, $duration)
    {
        $cookie = new Cookie($this->identityCookie);
        $cookie->value = json_encode([
            $identity->getId(),
            $identity->getAuthKey(),
            $duration,
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $cookie->expire = time() + $duration;
        Yii::$app->getResponse()->getCookies()->add($cookie);
    }

    /**
     * Switches to a new identity for the current user.
     *
     * When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
     * according to the value of `$duration`. Please refer to [[login()]] for more details.
     *
     * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
     * when the current user needs to be associated with the corresponding identity information.
     *
     * @param IdentityInterface|null $identity the identity information to be associated with the current user.
     * If null, it means switching the current user to be a guest.
     * @param integer $duration number of seconds that the user can remain in logged-in status.
     * This parameter is used only when `$identity` is not null.
     */
    public function switchIdentity($identity, $duration = 0)
    {
        $this->setIdentity($identity);

        if (!$this->enableSession) {
            return;
        }

        $session = Yii::$app->getSession();
        if (!YII_ENV_TEST) {
            $session->regenerateID(true);
        }
        $session->remove($this->idParam);
        $session->remove($this->authTimeoutParam);

        if ($identity) {
            $session->set($this->idParam, $identity->getId());
            if ($this->authTimeout !== null) {
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
            }
            if ($this->absoluteAuthTimeout !== null) {
                $session->set($this->absoluteAuthTimeoutParam, time() + $this->absoluteAuthTimeout);
            }
            if ($duration > 0 && $this->enableAutoLogin) {
                $this->sendIdentityCookie($identity, $duration);
            }
        } elseif ($this->enableAutoLogin) {
            Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));
        }
    }

    /**
     * Updates the authentication status using the information from session and cookie.
     *
     * This method will try to determine the user identity using the [[idParam]] session variable.
     *
     * If [[authTimeout]] is set, this method will refresh the timer.
     *
     * If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
     * if [[enableAutoLogin]] is true.
     */
    protected function renewAuthStatus()
    {
        $session = Yii::$app->getSession();
        $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;

        if ($id === null) {
            $identity = null;
        } else {
            /* @var $class IdentityInterface */
            $class = $this->identityClass;
            $identity = $class::findIdentity($id);
        }

        $this->setIdentity($identity);

        if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
            $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;
            $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;
            if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {
                $this->logout(false);
            } elseif ($this->authTimeout !== null) {
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
            }
        }

        if ($this->enableAutoLogin) {
            if ($this->getIsGuest()) {
                $this->loginByCookie();
            } elseif ($this->autoRenewCookie) {
                $this->renewIdentityCookie();
            }
        }
    }

    /**
     * Checks if the user can perform the operation as specified by the given permission.
     *
     * Note that you must configure "authManager" application component in order to use this method.
     * Otherwise it will always return false.
     *
     * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
     * @param array $params name-value pairs that would be passed to the rules associated
     * with the roles and permissions assigned to the user.
     * @param boolean $allowCaching whether to allow caching the result of access check.
     * When this parameter is true (default), if the access check of an operation was performed
     * before, its result will be directly returned when calling this method to check the same
     * operation. If this parameter is false, this method will always call
     * [[\yii\rbac\ManagerInterface::checkAccess()]] to obtain the up-to-date access result. Note that this
     * caching is effective only within the same request and only works when `$params = []`.
     * @return boolean whether the user can perform the operation as specified by the given permission.
     */
    public function can($permissionName, $params = [], $allowCaching = true)
    {
        if ($allowCaching && empty($params) && isset($this->_access[$permissionName])) {
            return $this->_access[$permissionName];
        }
        if (($manager = $this->getAuthManager()) === null) {
            return false;
        }
        $access = $manager->checkAccess($this->getId(), $permissionName, $params);
        if ($allowCaching && empty($params)) {
            $this->_access[$permissionName] = $access;
        }

        return $access;
    }

    /**
     * Returns auth manager associated with the user component.
     *
     * By default this is the `authManager` application component.
     * You may override this method to return a different auth manager instance if needed.
     * @return \yii\rbac\ManagerInterface
     * @since 2.0.6
     */
    protected function getAuthManager()
    {
        return Yii::$app->getAuthManager();
    }
}


<?php

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

namespace Kaloa\Util\Tree;

use Exception;
use Kaloa\Util\Tree\Node;

/**
 *
 */
final class Factory
{
    /**
     * Creates a tree structure from an array and returns the root element
     *
     * $a has to be a list of (key, parent_key, value) triplets. Keys will not
     * be preserved, they are only used to define the initial tree hierarchy.
     * The value part may be any kind of object, array or scalar value.
     *
     * @param  array $array
     * @return Node Root element
     */
    public function fromArray(array $array)
    {
        $root   = new Node(null);
        $map    = array();
        $map[0] = $root;

        // Create an entry in $map for every item in $a
        foreach ($array as $element) {
            if (3 !== count($element)) {
                throw new Exception('Each array must have 3 elements.');
            }

            $map[$element[0]] = new Node($element[2]);
        }

        //
        foreach ($array as $element) {
            if (empty($element[1])) {
                $element[1] = 0;
            }

            $found = false;
            $i     = 0;
            $keys  = array_keys($map);
            $cnt   = count($keys);
            while (!$found && $i < $cnt) {
                if ($keys[$i] === $element[1]) {
                    $map[$keys[$i]]->addChild($map[$element[0]]);
                    $found = true;
                } else {
                    $i++;
                }
            }
            if (!$found) {
                // Error
                throw new Exception('Data structure does not seem to be consistent. '
                        . 'Key "' . $element[1] . '" could not be found.');
            }
        }

        return $root;
    }
}


<?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\Markup;
use Peach\Util\Values;

/**
 * HTML や XML などを出力する際に使う, デフォルトの Builder です.
 * このクラスは, 以下の条件をカスタマイズすることが出来ます.
 *
 * - インデントの文字列 (半角スペース, タブ文字)
 * - 改行コードの種類 (LF, CRLF, CR)
 * - 空要素タグや boolean 属性の出力方法 (SGML, XML)
 */
class DefaultBuilder extends Builder
{
    /**
     * DefaultContext のコンストラクタに渡される Indent オブジェクトです.
     * @var Indent
     */
    private $indent;

    /**
     * DefaultContext のコンストラクタに渡される Renderer オブジェクトです.
     * @var Renderer
     */
    private $renderer;

    /**
     * DefaultContext のコンストラクタに渡される BreakControl オブジェクトです.
     * @var BreakControl
     */
    private $breakControl;

    /**
     * デフォルトの設定を持つ DefaultBuilder インスタンスを生成します.
     */
    public function __construct()
    {
        $this->indent       = null;
        $this->renderer     = null;
        $this->breakControl = null;
    }

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

    /**
     * この Builder に指定された Indent オブジェクトをセットします.
     * null を指定した場合は設定を解除します.
     *
     * @param  Indent $indent セットする Indent オブジェクト
     */
    public function setIndent(Indent $indent = null)
    {
        $this->indent = $indent;
    }

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

    /**
     * この Builder に指定された Renderer オブジェクトをセットします.
     * 引数によって以下のように動作します.
     *
     * - Renderer オブジェクトを指定した場合: そのオブジェクトをセットします
     * - 文字列 "xml" または "xhtml" を指定した場合 (大小問わず) : {@link XmlRenderer} オブジェクトをセットします
     * - 文字列 "sgml" または "html" を指定した場合 (大小問わず) : {@link SgmlRenderer} オブジェクトをセットします
     * - null を指定した場合 : 現在セットされている Renderer を解除します
     * - それ以外: InvalidArgumentException をスローします
     *
     * @param  Renderer|string $renderer セットする Renderer または対応する文字列
     * @throws \InvalidArgumentException 不正な引数をセットした場合
     */
    public function setRenderer($renderer = null)
    {
        $this->renderer = $this->initRenderer($renderer);
    }

    /**
     * 指定された引数で Renderer オブジェクトを初期化します.
     *
     * @see    Renderer::setRenderer()
     * @param  Renderer|string $var
     * @return Renderer
     * @throws \InvalidArgumentException
     */
    private function initRenderer($var)
    {
        if ($var instanceof Renderer) {
            return $var;
        }
        if ($var === null) {
            return null;
        }

        $type     = strtolower(Values::stringValue($var));
        $xmlList  = array("xml", "xhtml");
        if (in_array($type, $xmlList)) {
            return XmlRenderer::getInstance();
        }
        $sgmlList = array("sgml", "html");
        if (in_array($type, $sgmlList)) {
            return SgmlRenderer::getInstance();
        }

        throw new \InvalidArgumentException("Invalid type name: {$type}.");
    }

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

    /**
     * この Builder に指定された BreakControl をセットします.
     * null を指定した場合は設定を解除します.
     *
     * @param  BreakControl $breakControl セットする BreakControl
     */
    public function setBreakControl(BreakControl $breakControl = null)
    {
        $this->breakControl = $breakControl;
    }

    /**
     * この Builder にセットされている Indent, Renderer, BreakControl
     * を使って新しい DefaultContext を生成します.
     *
     * @return DefaultContext 新しい DefaultContext
     */
    protected function createContext()
    {
        $indent        = isset($this->indent)        ? clone($this->indent) : new Indent();
        $renderer      = isset($this->renderer)      ? $this->renderer      : XmlRenderer::getInstance();
        $breakControl  = isset($this->breakControl)  ? $this->breakControl  : DefaultBreakControl::getInstance();
        return new DefaultContext($renderer, $indent, $breakControl);
    }
}


<?php

namespace Orchid\Log;

use Illuminate\Support\ServiceProvider;
use Orchid\Log\Providers\UtilitiesServiceProvider;

class LogServiceProvider extends ServiceProvider
{
    /**
     * Get the base path.
     *
     * @return string
     */
    public function getBasePath()
    {
        return dirname(__DIR__);
    }

    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->app->singleton(Contracts\Log::class, Log::class);
        $this->app->singleton('arcanedev.log-viewer', Contracts\Log::class);
        $this->app->alias('arcanedev.log-viewer', Facades\Log::class);
    }

    /**
     * Boot the service provider.
     */
    public function boot()
    {
        $this->app->register(UtilitiesServiceProvider::class);
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [
            Contracts\Log::class,
        ];
    }
}