<?php

namespace Owl\Service\DB;

class Select
{
    /**
     * 数据库连接.
     *
     * @var
     */
    protected $adapter;

    /**
     * 被查询的表或关系.
     *
     * @var
     */
    protected $table;

    /**
     * 查询条件表达式.
     *
     * @var
     */
    protected $where = [];

    /**
     * 查询结果字段.
     *
     * @var array
     */
    protected $columns = [];

    /**
     * group by 语句.
     *
     * @var array
     */
    protected $group_by;

    /**
     * order by 语句.
     *
     * @var array
     */
    protected $order_by;

    /**
     * limit 语句参数.
     *
     * @var int
     */
    protected $limit = 0;

    /**
     * offset 语句参数.
     *
     * @var int
     */
    protected $offset = 0;

    /**
     * 预处理函数
     * 每条返回的结果都会被预处理函数处理一次
     *
     * @see Select::get()
     *
     * @var callable
     */
    protected $processor;

    /**
     * @param \Owl\Service\DB\Adapter $adapter
     * @param string|Expr|Select      $table
     */
    public function __construct(Adapter $adapter, $table)
    {
        $this->adapter = $adapter;
        $this->table = $table;
    }

    public function __destruct()
    {
        $this->adapter = null;
    }

    /**
     * 返回select语句.
     *
     * @return string
     */
    public function __toString()
    {
        list($sql) = $this->compile();

        return $sql;
    }

    /**
     * 获取数据库连接.
     *
     * @return \Owl\Service\DB\Adapter
     */
    public function getAdapter()
    {
        return $this->adapter;
    }

    /**
     * 设置查询的字段.
     *
     * @param string|array $columns
     *
     * @return $this
     *
     * @example
     * $select->setColumns('foo', 'bar');
     * $select->setColumns(array('foo', 'bar'));
     * $select->setColumns('foo', 'bar', new DB\Expr('foo + bar'));
     */
    public function setColumns($columns)
    {
        $this->columns = is_array($columns) ? $columns : func_get_args();

        return $this;
    }

    /**
     * 设置查询条件
     * 通过where()方法设置的多条条件之间的关系都是AND
     * OR关系必须写到同一个where条件内.
     *
     * @param string $where
     * @param mixed... [$params]
     *
     * @return $this
     *
     * @example
     * $select->where('foo = ?', 1)->where('bar = ?', 2);
     * $select->where('foo = ? or bar = ?', 1, 2);
     */
    public function where($where, $params = null)
    {
        $params = $params === null
                ? []
                : is_array($params) ? $params : array_slice(func_get_args(), 1);

        $this->where[] = [$where, $params];

        return $this;
    }

    /**
     * in 子查询.
     *
     * @param string       $column
     * @param array|Select $relation
     *
     * @return $this
     *
     * @example
     * // select * from foobar where foo in (1, 2, 3)
     * $select->whereIn('foo', array(1, 2, 3));
     *
     * // select * from foo where id in (select foo_id from bar where bar > 1)
     * $foo_select = $db->select('foo');
     * $bar_select = $db->select('bar');
     *
     * // select * from foo where id in (select id from bar)
     * $select->whereIn('id', new Expr('select id from bar'));
     *
     * $foo_select->whereIn('id', $bar_select->setcolumns('foo_id')->where('bar > 1'));
     */
    public function whereIn($column, $relation)
    {
        return $this->whereSub($column, $relation, true);
    }

    /**
     * not in 子查询.
     *
     * @param string       $column
     * @param array|Select $relation
     *
     * @return $this
     */
    public function whereNotIn($column, $relation)
    {
        return $this->whereSub($column, $relation, false);
    }

    /**
     * group by 条件.
     *
     * @param array $columns
     * @param string [$having]
     * @param mixed... [$having_params]
     *
     * @return $this
     *
     * @example
     * // select foo, count(1) from foobar group by foo having count(1) > 2
     * $select->setcolumns('foo', new Expr('count(1) as count'))->groupBy('foo', 'count(1) > ?', 2);
     */
    public function groupBy($columns, $having = null, $having_params = null)
    {
        $having_params = ($having === null || $having_params === null)
                       ? []
                       : is_array($having_params) ? $having_params : array_slice(func_get_args(), 2);

        $this->group_by = [$columns, $having, $having_params];

        return $this;
    }

    /**
     * order by 语句.
     *
     * @param string|Expr
     *
     * @return $this
     *
     * @example
     *
     * $select->orderBy('foo');
     * $select->orderBy(new Expr('foo desc'));
     * $select->orderBy(['foo' => 'desc', 'bar' => 'asc']);
     * $select->orderBy('foo', 'bar', new Expr('baz desc'));
     */
    public function orderBy($expressions)
    {
        $expressions = is_array($expressions) ? $expressions : func_get_args();

        $order_by = [];
        foreach ($expressions as $key => $expression) {
            if ($expression instanceof Expr) {
                $order_by[] = $expression;
            } else {
                if (is_numeric($key)) {
                    $column = $expression;
                    $sort = 'ASC';
                } else {
                    $column = $key;
                    $sort = $expression;
                }

                $column = $this->adapter->quoteIdentifier($column);
                $sort = (strtoupper($sort) === 'DESC') ? 'DESC' : '';

                $order_by[] = $sort ? $column . ' ' . $sort : $column;
            }
        }

        $this->order_by = $order_by;

        return $this;
    }

    /**
     * limit语句.
     *
     * @param int $count
     *
     * @return $this
     */
    public function limit($count)
    {
        $this->limit = abs((int) $count);

        return $this;
    }

    /**
     * offset语句.
     *
     * @param int $count
     * @param $this
     */
    public function offset($count)
    {
        $this->offset = abs((int) $count);

        return $this;
    }

    /**
     * 执行查询，返回查询结果句柄对象
     *
     * @return \Owl\Service\DB\Statement
     */
    public function execute()
    {
        list($sql, $params) = $this->compile();

        return $this->adapter->execute($sql, $params);
    }

    /**
     * 根据当前查询对象的各项参数，编译为具体的select语句及查询参数.
     *
     * @return
     * array(
     *     (string),    // select语句
     *     (array)      // 查询参数值
     * )
     */
    public function compile()
    {
        $adapter = $this->adapter;
        $sql = 'SELECT ';
        $params = [];

        $sql .= $this->columns
              ? implode(', ', $adapter->quoteIdentifier($this->columns))
              : '*';

        list($table, $table_params) = $this->compileFrom();
        if ($table_params) {
            $params = array_merge($params, $table_params);
        }

        $sql .= ' FROM ' . $table;

        list($where, $where_params) = $this->compileWhere();
        if ($where) {
            $sql .= ' WHERE ' . $where;
        }

        if ($where_params) {
            $params = array_merge($params, $where_params);
        }

        list($group_by, $group_params) = $this->compileGroupBy();
        if ($group_by) {
            $sql .= ' ' . $group_by;
        }

        if ($group_params) {
            $params = array_merge($params, $group_params);
        }

        if ($this->order_by) {
            $sql .= ' ORDER BY ' . implode(', ', $this->order_by);
        }

        if ($this->limit) {
            $sql .= ' LIMIT ' . $this->limit;
        }

        if ($this->offset) {
            $sql .= ' OFFSET ' . $this->offset;
        }

        return [$sql, $params];
    }

    /**
     * 查询当前查询条件在表内的行数.
     *
     * @return int
     */
    public function count()
    {
        $columns = $this->columns;
        $this->columns = [new Expr('count(1)')];

        $count = $this->execute()->getCol();

        $this->columns = $columns;

        return $count;
    }

    /**
     * 分页，把查询结果限定在指定的页.
     *
     * @param int $page
     * @param int $size
     *
     * @return $this
     *
     * @example
     * $select->setPage(2, 10)->get();
     */
    public function setPage($page, $size)
    {
        $this->limit($size)->offset(($page - 1) * $size);

        return $this;
    }

    /**
     * 分页，直接返回指定页的结果.
     *
     * @param int $page
     * @param int $size
     *
     * @return array
     *
     * @example
     * $select->getPage(2, 10);
     */
    public function getPage($page, $size)
    {
        return $this->setPage($page, $size)->get();
    }

    /**
     * 查询数据库数量，计算分页信息.
     *
     * @param int $current 当前页
     * @param int $size    每页多少条
     * @param int [$total]  一共有多少条，不指定就到数据库内查询
     *
     * @return
     * array(
     *  'total' => (integer),       // 一共有多少条数据
     *  'size' => (integer),        // 每页多少条
     *  'from' => (integer),        // 本页开始的序号
     *  'to' => (integer),          // 本页结束的序号
     *  'first' => 1,               // 第一页
     *  'prev' => (integer|null),   // 上一页，null说明没有上一页
     *  'current' => (integer),     // 本页页码
     *  'next' => (integer|null),   // 下一页，null说明没有下一页
     *  'last' => (integer),        // 最后一页
     * )
     */
    public function getPageInfo($current, $size, $total = null)
    {
        if ($total === null) {
            $limit = $this->limit;
            $offset = $this->offset;
            $order_by = $this->order_by;

            $this->order_by = [];
            $this->limit = 0;
            $this->offset = 0;

            $total = $this->count();

            $this->order_by = $order_by;
            $this->limit = $limit;
            $this->offset = $offset;
        }

        return self::buildPageInfo($total, $size, $current);
    }

    /**
     * 设置预处理函数.
     *
     * @param callable $processor
     *
     * @return $this
     */
    public function setProcessor($processor)
    {
        if ($processor && !is_callable($processor)) {
            throw new \UnexpectedValueException('Select processor is not callable');
        }

        $this->processor = $processor;

        return $this;
    }

    /**
     * 用预处理函数处理查询到的行.
     *
     * @param array $row
     *
     * @return mixed
     */
    public function process(array $row)
    {
        return $this->processor
             ? call_user_func($this->processor, $row)
             : $row;
    }

    /**
     * 获得所有的查询结果.
     *
     * @param int [$limit]
     *
     * @return array
     */
    public function get($limit = null)
    {
        if ($limit !== null) {
            $this->limit($limit);
        }

        $sth = $this->execute();
        $processor = $this->processor;

        $records = [];
        while ($record = $sth->getRow()) {
            $records[] = $processor
                       ? call_user_func($processor, $record)
                       : $record;
        }

        return $records;
    }

    /**
     * 只查询返回第一行数据.
     *
     * @return mixed
     */
    public function getOne()
    {
        $records = $this->get(1);

        return array_shift($records);
    }

    /**
     * 根据当前的条件，删除相应的数据.
     *
     * 注意：直接利用select删除数据可能不是你想要的结果
     * <code>
     * // 找出符合条件的前5条
     * // select * from "users" where id > 100 order by create_time desc limit 5
     * $select = $adapter->select('users')->where('id > ?', 100)->orderBy('create_time desc')->limit(5);
     *
     * // 因为DELETE语句不支持order by / limit / offset
     * // 删除符合条件的，不仅仅是前5条
     * // delete from "users" where id > 100
     * $select->delete()
     *
     * // 如果要删除符合条件的前5条
     * // delete from "users" where id in (select id from "users" where id > 100 order by create_time desc limit 5)
     * $adapter->select('users')->whereIn('id', $select->setcolumns('id'))->delete();
     * </code>
     * 这里很容易犯错，考虑是否不提供delete()和update()方法
     * 或者发现定义了limit / offset就抛出异常中止
     *
     * @return int affected row count
     */
    public function delete()
    {
        list($where, $params) = $this->compileWhere();

        // 不允许没有任何条件的delete
        if (!$where) {
            throw new \LogicException('MUST specify WHERE condition before delete');
        }

        // 见方法注释
        if ($this->limit or $this->offset or $this->group_by) {
            throw new \LogicException('CAN NOT DELETE while specify LIMIT or OFFSET or GROUP BY');
        }

        return $this->adapter->delete($this->table, $where, $params);
    }

    /**
     * 根据当前查询语句的条件参数更新数据.
     *
     * @param array $row
     *
     * @return int affected row count
     */
    public function update(array $row)
    {
        list($where, $params) = $this->compileWhere();

        // 不允许没有任何条件的update
        if (!$where) {
            throw new \LogicException('MUST specify WHERE condition before update');
        }

        // 见delete()方法注释
        if ($this->limit or $this->offset or $this->group_by) {
            throw new \LogicException('CAN NOT UPDATE while specify LIMIT or OFFSET or GROUP BY');
        }

        return $this->adapter->update($this->table, $row, $where, $params);
    }

    /**
     * 以iterator的形式返回查询结果
     * 通过遍历iterator的方式处理查询结果，避免过大的内存占用.
     */
    public function iterator()
    {
        $res = $this->execute();

        while ($row = $res->fetch()) {
            yield $this->process($row);
        }
    }

    /**
     * 分批遍历查询结果
     * 每批次获取一定数量，遍历完一批再继续下一批.
     *
     * 避免mysql buffered query遍历巨大的查询结果导致的内存溢出问题
     *
     * @param int $size
     */
    public function batchIterator($size = 1000)
    {
        $limit_copy = $this->limit;
        $offset_copy = $this->offset;

        $limit = $limit_copy ?: -1;
        $offset = $offset_copy;

        if (0 < $limit && $limit < $size) {
            $size = $limit;
        }

        try {
            do {
                $res = $this->limit($size)->offset($offset)->execute();

                $found = false;
                while ($row = $res->fetch()) {
                    if ($limit-- === 0) {
                        break;
                    }

                    $found = true;

                    yield $this->process($row);
                }

                $offset += $size;
            } while ($found);
        } finally {
            // retrieve limit & offset
            $this->limit($limit_copy)->offset($offset_copy);
        }
    }

    //////////////////// protected method ////////////////////

    /**
     * where in 子查询语句.
     *
     * @param string       $column
     * @param array|Select $relation
     * @param bool         $in
     *
     * @return $this
     */
    protected function whereSub($column, $relation, $in)
    {
        $column = $this->adapter->quoteIdentifier($column);
        $params = [];

        if ($relation instanceof self) {
            list($sql, $params) = $relation->compile();
            $sub = $sql;
        } elseif ($relation instanceof Expr) {
            $sub = (string) $relation;
        } else {
            $sub = implode(',', $this->adapter->quote($relation));
        }

        $where = $in
               ? sprintf('%s IN (%s)', $column, $sub)
               : sprintf('%s NOT IN (%s)', $column, $sub);

        $this->where[] = [$where, $params];

        return $this;
    }

    /**
     * 把from参数编译为select 子句.
     *
     * @return
     * array(
     *     (string),    // from 子句
     *     (array),     // 查询参数
     * )
     */
    protected function compileFrom()
    {
        $params = [];

        if ($this->table instanceof self) {
            list($sql, $params) = $this->table->compile();
            $table = sprintf('(%s) AS %s', $sql, $this->adapter->quoteIdentifier(uniqid()));
        } elseif ($this->table instanceof Expr) {
            $table = (string) $this->table;
        } else {
            $table = $this->adapter->quoteIdentifier($this->table);
        }

        return [$table, $params];
    }

    /**
     * 把查询条件参数编译为where子句.
     *
     * @return
     * array(
     *     (string),    // where 子句
     *     (array),     // 查询参数
     * )
     */
    protected function compileWhere()
    {
        if (!$this->where) {
            return ['', []];
        }

        $where = $params = [];

        foreach ($this->where as $w) {
            list($where_sql, $where_params) = $w;

            $where[] = $where_sql;
            if ($where_params) {
                $params = array_merge($params, $where_params);
            }
        }
        $where = '(' . implode(') AND (', $where) . ')';

        return [$where, $params];
    }

    /**
     * 编译group by 子句.
     *
     * @return
     * array(
     *     (string),    // group by 子句
     *     (array),     // 查询参数
     * )
     */
    protected function compileGroupBy()
    {
        if (!$this->group_by) {
            return ['', []];
        }

        list($group_columns, $having, $having_params) = $this->group_by;

        $group_columns = $this->adapter->quoteIdentifier($group_columns);
        if (is_array($group_columns)) {
            $group_columns = implode(',', $group_columns);
        }

        $sql = 'GROUP BY ' . $group_columns;
        if ($having) {
            $sql .= ' HAVING ' . $having;
        }

        return [$sql, $having_params];
    }

    public static function buildPageInfo($total, $page_size, $current_page = 1)
    {
        $total = (int) $total;
        $page_size = (int) $page_size;
        $current_page = (int) $current_page;

        $page_count = ceil($total / $page_size) ?: 1;

        if ($current_page > $page_count) {
            $current_page = $page_count;
        } elseif ($current_page < 1) {
            $current_page = 1;
        }

        $page = [
            'total' => $total,
            'size' => $page_size,
            'from' => 0,
            'to' => 0,
            'first' => 1,
            'prev' => null,
            'current' => $current_page,
            'next' => null,
            'last' => $page_count,
        ];

        if ($current_page > $page['first']) {
            $page['prev'] = $current_page - 1;
        }

        if ($current_page < $page['last']) {
            $page['next'] = $current_page + 1;
        }

        if ($total) {
            $page['from'] = ($current_page - 1) * $page_size + 1;
            $page['to'] = $current_page == $page['last']
                        ? $total
                        : $current_page * $page_size;
        }

        return $page;
    }
}


<?php declare(strict_types=1);
namespace Imatic\Bundle\ViewBundle\Templating\Utils;

class StringUtil
{
    /**
     * Escape a string for use in HTML 5 code.
     *
     * @param string $string
     *
     * @return string
     */
    public static function escape($string)
    {
        return \htmlspecialchars((string) $string, ENT_HTML5 | ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }

    /**
     * Unescape a HTML 5 encoded string.
     *
     * @param string $html
     *
     * @return string
     */
    public static function unescape($html)
    {
        return \htmlspecialchars_decode($html, ENT_HTML5 | ENT_QUOTES);
    }

    /**
     * @param string $string
     *
     * @return string
     */
    public static function slugify($string)
    {
        $slug = \preg_replace('~[^\\pL0-9_]+~u', '-', \trim($string, '-'));
        $slug = \iconv('utf-8', 'us-ascii//TRANSLIT', $slug);
        $slug = \preg_replace('~[^-a-z0-9_]+~', '', \strtolower($slug));

        return $slug;
    }

    /**
     * @param string $string
     *
     * @return string
     */
    public static function humanize($string)
    {
        return \ucfirst(\trim(\strtolower(\preg_replace(['/([A-Z])/', '/[_\s]+/'], ['_$1', ' '], $string))));
    }
}


<?php

/*
 * This file is part of the FSi Component package.
 *
 * (c) Lukasz Cybula <lukasz@fsi.pl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FSi\Component\Reflection;

class ReflectionFunction extends \ReflectionFunction
{
    protected static $functions = array();

    /**
     * Constructs a new ReflectionFunction object.
     *
     * @param string $function
     * @throws ReflectionException
     * @return ReflectionFunction
     */
    final public function __construct($function)
    {
        $bt = debug_backtrace();
        if (!isset($bt[1]['class']) || ($bt[1]['class'] !== __CLASS__))
            throw new ReflectionException('ReflectionClass\' constructor cannot be called from outside the class');
        parent::__construct($function);
    }

    /**
     * Constructs a new ReflectionFunction object from function name and store it in cache.
     * If object already exists in cache it will taken from there instead of creating
     * new object
     *
     * @param string $class
     * @return ReflectionFunction
     */
    public static function factory($function)
    {
        $function = (string)$function;
        if (!isset(self::$functions[$function]))
            self::$functions[$function] = new self($function);
        return self::$functions[$function];
    }

}


<?php

namespace Addons\Core\Models;

use DB;

trait TreeTrait{

	public function hasChildren()
	{
		return $this->children()->count() > 0;
	}

	/**
	 * 将二维dataset数组生成tree，必须是ID为KEY的二维数组
	 *
	 * @param mixed $items ID为KEY的二维数组
	 * @param bool 返回的children中，是否以ID为Key
	 */
	public static function datasetToTree(array $items, bool $idAsKey = true)
	{
		$node = new static;
		$ids = [];

		if ($idAsKey)
		{
			foreach ($items as $item)
			{
				if ($item[$node->getKeyName()] == $item[$node->parentKey]) continue; //如果父ID等于自己，避免死循环，跳过

				$ids[] = $item[$node->getKeyName()];
				$items[ ($item[$node->parentKey]) ][ 'children' ][ ($item[$node->getKeyName()]) ] = &$items[ ($item[$node->getKeyName()]) ];
			}
		}
		else
		{
			foreach ($items as $item)
			{
				if ($item[$node->getKeyName()] == $item[$node->parentKey]) continue; //如果父ID等于自己，避免死循环，跳过

				$ids[] = $item[$node->getKeyName()];
				$items[ ($item[$node->parentKey]) ][ 'children' ][] = &$items[ ($item[$node->getKeyName()]) ];
			}
		}

		$result = array_except($items, $ids);
		return count($result) === 1 ? array_get(array_pop($result), 'children', []) : $result;
	}

	/**
	 * 改变父级，本函数不可再任何情况下调用
	 * $tree->update(['pid' => 'xxx']) 会自动调用本函数
	 *
	 * @return [type]          [description]
	 */
	protected function changeParent()
	{
		$newParent = $this->getNode($this->getParentKey());
		if(empty($newParent) || $this->getParentKey() == $this->getOriginal($this->parentKey)) return NULL;

		if (!empty($this->pathKey))
		{
			$newPath = $newParent->getPathKey() . $this->getKey() . '/';
			static::where($this->pathKey, 'LIKE', '%'.$this->getPathKey().'%')->update([$this->pathKey => DB::raw('REPLACE(`'.$this->pathKey.'`, \''.$this->getPathKey().'\', \''.$newPath.'\')')]);
		}

		if (!empty($this->levelKey))
		{
			$deltaLevel = intval($this->getLevelKey()) - intval($newParent->getLevelKey()) - 1;
			$ids = $this->getLeaves([])->add($this)->modelKeys(); //get id pid
			static::whereIn($this->getKeyName(), $ids)->decrement($this->levelKey, $deltaLevel);
		}

		return $this;
	}

	public static function bootTreeTrait()
	{
		//更新order/level
		static::creating(function($node){
			!empty($node->getOrderKeyName()) && $node[$node->getOrderKeyName()] = $node->newOrder();
			!empty($node->getLevelKeyName()) && $node[$node->getLevelKeyName()] = $node->getParent()->getLevelKey() + 1;
		});
		//更新path
		static::created(function($node){
			if (!empty($node->pathKey))
			{
				$node[$node->getPathKeyName()] = $node->getParent()->getPathKey() . $node->getKey().'/';
				$node->save();
			}
		});

		//切换父级
		static::updated(function($node) {
			if ($node->isDirty($node->getParentKeyName()))
			{
				$node->changeParent();
				//放到新Parent的结尾
				$node->moveToLast();
			}
		});
		//删除子集，会自动递归删除后代
		static::deleted(function($node){
			foreach($node->getChildren() as $v)
				$v->delete();
		});
	}
}


<?php
/**
 * Plugin Name: Bedrock Autoloader
 * Plugin URI: https://github.com/autobahn-cloud/bedrock-autoloader
 * Description: An autoloader that enables standard plugins to be required just like must-use plugins. The autoloaded plugins are included during mu-plugin loading.
 * Version: 1.0.0
 * Author: Autobahn
 * Author URI: https://github.com/mrgrain/autobahn
 * License: MIT License
 */

namespace Roots\Bedrock;

if (!is_blog_installed()) {
    return;
}

/**
 * Class Autoloader
 * @package Roots\Bedrock
 * @author Roots
 * @link https://roots.io/
 */
class Autoloader
{
    /** @var array Store Autoloader cache and site option */
    private static $cache;

    /** @var array Autoloaded plugins */
    private static $auto_plugins;

    /** @var array Autoloaded mu-plugins */
    private static $mu_plugins;

    /** @var int Number of plugins */
    private static $count;

    /** @var array Newly activated plugins */
    private static $activated;

    /** @var string Relative path to the mu-plugins dir */
    private static $relative_path;

    /** @var static Singleton instance */
    private static $_single;

    /**
     * Create singleton, populate vars, and set WordPress hooks
     */
    public function __construct()
    {
        if (isset(self::$_single)) {
            return;
        }

        self::$_single = $this;
        self::$relative_path = '/../' . basename(dirname(__DIR__));

        if (is_admin()) {
            add_filter('show_advanced_plugins', [$this, 'showInAdmin'], 0, 2);
        }

        $this->loadPlugins();
    }

    /**
     * Run some checks then autoload our plugins.
     */
    public function loadPlugins()
    {
        $this->checkCache();
        $this->validatePlugins();
        $this->countPlugins();

        foreach (self::$cache['plugins'] as $plugin_file => $plugin_info) {
            include_once(WPMU_PLUGIN_DIR . '/' . $plugin_file);
        }

        $this->pluginHooks();
    }

    /**
     * Filter show_advanced_plugins to display the autoloaded plugins.
     * @param $bool bool Whether to show the advanced plugins for the specified plugin type.
     * @param $type string The plugin type, i.e., `mustuse` or `dropins`
     * @return bool We return `false` to prevent WordPress from overriding our work
     * {@internal We add the plugin details ourselves, so we return false to disable the filter.}
     */
    public function showInAdmin($show, $type)
    {
        $screen = get_current_screen();
        $current = is_multisite() ? 'plugins-network' : 'plugins';

        if ($screen->{'base'} != $current || $type != 'mustuse' || !current_user_can('activate_plugins')) {
            return $show;
        }

        $this->updateCache();

        self::$auto_plugins = array_map(function ($auto_plugin) {
            return $auto_plugin;
        }, self::$auto_plugins);

        $GLOBALS['plugins']['mustuse'] = array_unique(array_merge(self::$auto_plugins, self::$mu_plugins), SORT_REGULAR);

        return false;
    }

    /**
     * This sets the cache or calls for an update
     */
    private function checkCache()
    {
        $cache = get_site_option('bedrock_autoloader');

        if ($cache === false) {
            $this->updateCache();
            return;
        }

        self::$cache = $cache;
    }

    /**
     * Get the plugins and mu-plugins from the mu-plugin path and remove duplicates.
     * Check cache against current plugins for newly activated plugins.
     * After that, we can update the cache.
     */
    private function updateCache()
    {
        require_once(ABSPATH . 'wp-admin/includes/plugin.php');

        self::$auto_plugins = get_plugins(self::$relative_path);
        self::$mu_plugins = get_mu_plugins();
        $plugins = array_diff_key(self::$auto_plugins, self::$mu_plugins);
        $rebuild = !is_array(self::$cache['plugins']);
        self::$activated = ($rebuild) ? $plugins : array_diff_key($plugins, self::$cache['plugins']);
        self::$cache = array('plugins' => $plugins, 'count' => $this->countPlugins());

        update_site_option('bedrock_autoloader', self::$cache);
    }

    /**
     * This accounts for the plugin hooks that would run if the plugins were
     * loaded as usual. Plugins are removed by deletion, so there's no way
     * to deactivate or uninstall.
     */
    private function pluginHooks()
    {
        if (!is_array(self::$activated)) {
            return;
        }

        foreach (self::$activated as $plugin_file => $plugin_info) {
            add_action('wp_loaded', function () use ($plugin_file) {
                do_action('activate_' . $plugin_file);
            });
        }
    }

    /**
     * Check that the plugin file exists, if it doesn't update the cache.
     */
    private function validatePlugins()
    {
        foreach (self::$cache['plugins'] as $plugin_file => $plugin_info) {
            if (!file_exists(WPMU_PLUGIN_DIR . '/' . $plugin_file)) {
                $this->updateCache();
                break;
            }
        }
    }

    /**
     * Count the number of autoloaded plugins.
     *
     * Count our plugins (but only once) by counting the top level folders in the
     * mu-plugins dir. If it's more or less than last time, update the cache.
     *
     * @return int Number of autoloaded plugins.
     */
    private function countPlugins()
    {
        if (isset(self::$count)) {
            return self::$count;
        }

        $count = count(glob(WPMU_PLUGIN_DIR . '/*/', GLOB_ONLYDIR | GLOB_NOSORT));

        if (!isset(self::$cache['count']) || $count != self::$cache['count']) {
            self::$count = $count;
            $this->updateCache();
        }

        return self::$count;
    }
}

new Autoloader();


<?php
namespace Karlomikus\Multilog;

use Illuminate\Contracts\Config\Repository as Config;
use Illuminate\Contracts\Container\Container as App;
use Karlomikus\Multilog\Contracts\MultilogInterface;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

/**
 * Multilog
 *
 * @author Karlo Mikus <contact@karlomikus.com>
 * @version 1.0.0
 */
class Multilog implements MultilogInterface
{
    private $channels = [];

    private $app;

    /**
     * @param Config $config
     * @param App $app
     */
    public function __construct(Config $config, App $app)
    {
        $this->app = $app;
        $loggers = $config->get('multilog');
        $this->initLoggers($loggers);
    }

    /**
     * Get monolog instance for a specific channel
     *
     * @param  string $name Channel name
     * @return \Monolog\Logger|null
     */
    public function channel($name)
    {
        if (array_key_exists($name, $this->channels)) {
            return $this->channels[$name];
        }

        return null;
    }

    /**
     * Alias for channel
     *
     * @param  string $name
     * @return \Monolog\Logger
     */
    public function c($name)
    {
        return $this->channel($name);
    }

    /**
     * Read config array and initialize
     * all loggers
     *
     * @param  array  $loggers
     * @return void
     */
    private function initLoggers(array $loggers)
    {
        foreach ($loggers as $channel => $config) {
            $this->createLogger($channel, $config);
        }
    }

    /**
     * Create new logger instance with given
     * configuration and store it in array
     * with channel name
     *
     * @param  string $channel Channel name
     * @param  array $config  Channel configuration
     * @return void
     */
    private function createLogger($channel, array $config)
    {
        // Setup configuration
        // Use default laravel logs path
        $storagePath = $this->app->make('path.storage');
        $filepath = $storagePath . '/logs/' . $config['stream'];

        $logger = new Logger($channel);
        $handler = new StreamHandler($filepath);

        // Daily rotation
        if ($config['daily']) {
            $handler = new RotatingFileHandler($filepath, 1);
        }

        // Format line
        if (isset($config['format'])) {
            $format = $config['format'];
            $handler->setFormatter(new LineFormatter($format['output'], $format['date']));
        }

        $logger->pushHandler($handler);

        $this->channels[$channel] = $logger;
    }
}


<?php
/**
 * processor "*.md"
 */
namespace picklesFramework2\processors\md;

/**
 * processor "*.md" class
 */
class ext{

	/**
	 * 変換処理の実行
	 * @param object $px Picklesオブジェクト
	 */
	public static function exec( $px ){

		foreach( $px->bowl()->get_keys() as $key ){
			$src = $px->bowl()->pull( $key );

			if($key != 'head' && $key != 'foot'){
				$src = \Michelf\MarkdownExtra::defaultTransform($src);
			}

			$px->bowl()->replace( $src, $key );
		}

		return true;
	}
}


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

namespace CampaignChain\Location\EZPlatformBundle\Controller\REST;

use CampaignChain\CoreBundle\Controller\REST\BaseModuleController;
use CampaignChain\CoreBundle\Entity\Location;
use FOS\RestBundle\Controller\Annotations as REST;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use FOS\RestBundle\Request\ParamFetcher;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

/**
 * @REST\NamePrefix("campaignchain_location_ezplatform_rest_")
 *
 * Class LocationController
 * @package CampaignChain\Location\EZPlatformBundle\Controller\REST
 */
class LocationController extends BaseModuleController
{
    const MODULE_URI = 'campaignchain/location-ezplatform/campaignchain-ezplatform-object';

    /**
     * Get a list of eZ Platform content object Locations.
     *
     * Example Request
     * ===============
     *
     *      GET /api/{version}/p/campaignchain/location-ezplatform/objects
     *
     * Example Response
     * ================
    {
        "response": [
            {
                "id": 108,
                "identifier": "62",
                "name": "eZ Publish Tutorials",
                "status": "unpublished",
                "createdDate": "2015-12-01T09:37:39+0000",
                "operationId": "92",
                "channelId": "8"
            }
        ]
    }
     *
     * @ApiDoc(
     *  section="Packages: eZ Platform"
     * )
     */
    public function getObjectsAction()
    {
        $qb = $this->getQueryBuilder();
        $qb->select(\CampaignChain\CoreBundle\Controller\REST\LocationController::SELECT_STATEMENT);
        $qb->from('CampaignChain\CoreBundle\Entity\Location', 'l');
        $qb->where('l.channel IS NULL');
        $qb->orderBy('l.name');
        $qb = $this->getModuleRelation($qb, 'l.locationModule', self::MODULE_URI);
        $qb = $this->getLocationChannelId($qb);
        $query = $qb->getQuery();

        return $this->response(
            $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY)
        );
    }
}


<?php

namespace Addons\Core\Models;

use Cache;
use Illuminate\Support\Arr;

trait CacheTrait {

	/*
	 * forget these keys when fire
	 *
	 * @var array
	 */
	//protected $fire_caches = [];

	protected static function bootCacheTrait()
	{
		static::deleted(function($model) {
			$model->deleteFireCache();
		});
		static::saved(function($model) {
			$model->deleteFireCache();
		});
		if (method_exists(static::class, 'restored'))
			static::restored(function($model){
				$model->deleteFireCache();
		});
	}

	private static function getCacheIndex($id)
	{
		return floor($id / 100);
	}

	private static function getRangeCache($index)
	{
		$model = new static();
		$keyName = $model->getKeyName();
		$min = $index;
		$max = $min + 1;
		$key = $model->getTable().','.$min.'-'.$max;
		return Cache::remember($key, config('cache.ttl'), function() use($min, $max, $keyName){ // 7 days
			$models = static::where($keyName, '>=', $min * 100)->where($keyName, '<', $max * 100)->get();
			return $models->mapWithKeys(function($model, $key){
				return [$model->getKey() => $model->getAttributes()];
			});
		});
	}

	public function deleteFireCache()
	{
		if (isset($this->fire_caches))
			foreach($this->fire_caches as $key)
				Cache::forget($key);

		$min = static::getCacheIndex($this->getKey());
		$max = $min + 1;
		$key = $this->getTable().','.$min.'-'.$max;
		Cache::forget($key);
	}

	public static function findByCache($id)
	{
		if (!is_numeric($id)) return static::find($id);

		$index = static::getCacheIndex($id);
		$data = static:: getRangeCache($index);

		return $data->has($id) ? (new static)->setRawAttributes($data->get($id)) : false;
	}

	public static function findManyByCache(...$ids)
	{
		$ids = Arr::flatten($ids);
		$indices = array_unique(array_map(function($id) {
			return static::getCacheIndex($id);
		}, $ids));

		$data = [];
		foreach($indices as $index)
			$data = array_merge($data, static:: getRangeCache($index));

		$result = collect([]);
		foreach ($ids as $id) {
			if (!$data->has($id))
				continue;
			$result[] = (new static)->setRawAttributes($data->get($id));
		}

		return $result;
	}

}


<?php

/*
 * This file is part of the FSi Component package.
 *
 * (c) Lukasz Cybula <lukasz@fsi.pl>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FSi\Component\Reflection;

class ReflectionClass extends \ReflectionClass
{
    protected static $classes = array();

    /**
     * Constructs a new ReflectionClass object.
     *
     * @param string|object $class
     * @throws ReflectionException
     * @return ReflectionClass
     */
    final public function __construct($class)
    {
        $bt = debug_backtrace();
        if (!isset($bt[1]['class']) || ($bt[1]['class'] !== __CLASS__))
            throw new ReflectionException('ReflectionClass\' constructor cannot be called from outside the class');
        parent::__construct($class);
    }

    /**
     * Constructs a new ReflectionClass object from class name and store it in cache.
     * If object already exists in cache it will taken from there instead of creating
     * new object
     *
     * @param string|object $class
     * @return ReflectionClass
     */
    public static function factory($class)
    {
        if (is_object($class))
            $class = get_class($class);
        $class = (string)$class;
        if (!isset(self::$classes[$class]))
            self::$classes[$class] = new self($class);
        return self::$classes[$class];
    }

    /**
     * Get interfaces ReflectionObjects implemented by class
     *
     * @return array
     */
    public function getInterfaces()
    {
        $interfaceNames = $this->getInterfaceNames();
        $interfaces = array();
        foreach ($interfaceNames as $interface)
            $interfaces[$interface] = ReflectionClass::factory($interface);
        return $interfaces;
    }

    /**
     * Get parent ReflectionClass object
     *
     * @return ReflectionClass|false
     */
    public function getParentClass()
    {
        $parentClass = parent::getParentClass();
        if ($parentClass) {
            return ReflectionClass::factory($parentClass->getName());
        }
        return false;
    }

    /**
     * Get class ReflectionMethod object by method name if exists.
     *
     * @throws ReflectionException
     * @return ReflectionMethod
     */
    public function getMethod($method)
    {
        return ReflectionMethod::factory($this->name, $method);
    }

    protected function filter($items, $filter)
    {
        $filtered = array();
        foreach ($items as $item)
            if ($item->getModifiers() & $filter)
                $filtered[] = $item;
        return $filtered;
    }

    /**
     * Get class ReflectionMethods objects array list.
     *
     * @return array
     */
    public function getMethods($filter = null)
    {
        $args = func_get_args();
        $methods = ReflectionMethod::factory($this->name);

        if (count($args)) {
            return $this->filter($methods, current($args));
        }

        return $methods;
    }

    /**
     * Get class ReflectionProperty object by property name if exists. .
     *
     * @throws ReflectionException
     * @return ReflectionProperty
     */
    public function getProperty($property)
    {
        return ReflectionProperty::factory($this->name, $property);
    }

    /**
     * Get class ReflectionProperty objects array list.
     *
     * @return array
     */
    public function getProperties($filter = null)
    {
        $args = func_get_args();
        $properties = ReflectionProperty::factory($this->name);

        if (count($args)) {
            return $this->filter($properties, current($args));
        }

        return $properties;
    }

}


<?php declare(strict_types=1);
namespace Imatic\Bundle\ViewBundle\Menu;

class DemoMenuBuilder
{
    /**
     * @param Factory $factory
     * @param Helper  $helper
     *
     * @return \Knp\Menu\ItemInterface
     */
    public function getMenu(Factory $factory, Helper $helper)
    {
        // Create root item
        $menu = $factory->createItem('root');

        // Add menu items
        $menu->addChild('Home', ['route' => 'imatic_view_demo_demo_index']);
        $componentIndex = $menu->addChild('Components', ['uri' => '#']);
        $helper->setDropdown($componentIndex);
        $componentIndex->addChild($factory->createItem('Basic', ['route' => 'imatic_view_demo_component_index']));
        $componentIndex->addChild($factory->createItem('Layout', ['route' => 'imatic_view_demo_component_layout']));
        $componentIndex->addChild($factory->createItem('Panel', ['route' => 'imatic_view_demo_component_panel']));
        $componentIndex->addChild($factory->createItem('Grid', ['route' => 'imatic_view_demo_component_grid']));
        $componentIndex->addChild($factory->createItem('Form', ['route' => 'imatic_view_demo_component_form']));
        $componentIndex->addChild($factory->createItem('Show', ['route' => 'imatic_view_demo_component_show']));
        $componentIndex->addChild($factory->createItem('Tabs', ['route' => 'imatic_view_demo_component_tabs']));
        $componentIndex->addChild($factory->createItem('Menu', ['route' => 'imatic_view_demo_component_menu']));
        $componentIndex->addChild($factory->createItem('Formatter', ['route' => 'imatic_view_demo_component_formatter']));

        $javaScriptIndex = $menu->addChild('JavaScript', ['uri' => '#']);
        $helper->setDropdown($javaScriptIndex);
        $javaScriptIndex->addChild('Ajaxify', ['route' => 'imatic_view_demo_ajaxify_index']);
        $javaScriptIndex->addChild('Toggle', ['route' => 'imatic_view_demo_toggle_index']);

        return $menu;
    }

    /**
     * @param Factory $factory
     * @param Helper  $helper
     *
     * @return \Knp\Menu\ItemInterface
     */
    public function getSubMenu(Factory $factory, Helper $helper)
    {
        $menu = $this->getNormalMenu($factory, $helper);
        $products = $menu->getChild('Products');

        // Add header
        $helper->addHeader($products, 'Products A');
        // Set submenu for products
        $helper->setSubmenu($products);
        $products->addChild('Product 1', ['route' => 'homepage']);
        $products->addChild('Product 2', ['route' => 'homepage']);
        $products->addChild('Product 3', ['route' => 'homepage']);
        // Add header
        $helper->addHeader($products, 'Products B');
        $products->addChild('Product 4', ['route' => 'homepage']);
        $products->addChild('Product 5', ['route' => 'homepage']);
        $products->addChild('Product 6', ['route' => 'homepage']);

        return $menu;
    }

    /**
     * @param Factory $factory
     * @param Helper  $helper
     *
     * @return \Knp\Menu\ItemInterface
     */
    public function getNormalMenu(Factory $factory, Helper $helper)
    {
        // Create root item
        $menu = $factory->createItem('root');

        // Add menu items
        $menu->addChild('Home', ['route' => 'homepage']);
        $menu->addChild('About', ['route' => 'homepage'])->setCurrent(true);
        $products = $menu->addChild('Products', ['route' => 'homepage']);
        $menu->addChild('Reference', ['route' => 'homepage'])->setAttribute('class', 'disabled');
        // Add vertical divider
        $helper->addDivider($menu, true);
        $contact = $menu->addChild('Contact', ['route' => 'homepage']);

        // Set badge for products
        $helper->setBadge($products, 2, 'important', true);

        // Set dropdown menu for contact
        $helper->setDropdown($contact);
        $contact->addChild('Test 1', ['route' => 'homepage']);
        $contact->addChild('Test')->setAttribute('class', 'nav-header');
        $contact->addChild('Test 2', ['route' => 'homepage']);
        // Add horizontal divider
        $helper->addDivider($contact);
        $contact->addChild('Test 3', ['uri' => 'http://www.imatic.cz']);

        return $menu;
    }
}


<?php

namespace WPLibs\Http;

use Closure;
use ArrayAccess;
use RuntimeException;
use WPLibs\Session\Store as Session;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\Support\Arrayable;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request as Symfony_Request;

/**
 * The following methods are derived from code of the Laravel Framework
 * copyright (c) Taylor Otwell under MIT license.
 *
 * @see https://github.com/illuminate/http/blob/5.5/Request.php
 *
 * @license https://github.com/laravel/framework/blob/5.5/LICENSE.md
 */
class Request extends Symfony_Request implements Arrayable, ArrayAccess {
	use Traits\Request_With_Input,
		Traits\Request_With_Flash_Data,
		Traits\Request_With_Content_Types,
		Macroable;

	/**
	 * The decoded JSON content for the request.
	 *
	 * @var ParameterBag
	 */
	protected $json;

	/**
	 * The route resolver callback.
	 *
	 * @var \Closure
	 */
	protected $route_resolver;

	/**
	 * Create a new HTTP request from server variables.
	 *
	 * @return static
	 */
	public static function capture() {
		static::enableHttpMethodParameterOverride();

		return static::create_from_base( Symfony_Request::createFromGlobals() );
	}

	/**
	 * Return the Request instance.
	 *
	 * @return $this
	 */
	public function instance() {
		return $this;
	}

	/**
	 * Get the request method.
	 *
	 * @return string
	 */
	public function method() {
		return $this->getMethod();
	}

	/**
	 * Get the root URL for the application.
	 *
	 * @return string
	 */
	public function root() {
		return rtrim( $this->getSchemeAndHttpHost() . $this->getBaseUrl(), '/' );
	}

	/**
	 * Get the URL (no query string) for the request.
	 *
	 * @return string
	 */
	public function url() {
		return rtrim( preg_replace( '/\?.*/', '', $this->getUri() ), '/' );
	}

	/**
	 * Get the full URL for the request.
	 *
	 * @return string
	 */
	public function full_url() {
		$query = $this->getQueryString();

		$question = ( $this->getBaseUrl() . $this->getPathInfo() ) === '/' ? '/?' : '?';

		return $query ? ( $this->url() . $question . $query ) : $this->url();
	}

	/**
	 * Determine if the request is the result of an AJAX call.
	 *
	 * @return bool
	 */
	public function ajax() {
		return $this->isXmlHttpRequest();
	}

	/**
	 * Determine if the request is the result of an PJAX call.
	 *
	 * @return bool
	 */
	public function pjax() {
		return (bool) $this->headers->get( 'X-PJAX' ) === true;
	}

	/**
	 * Determine if the request is over HTTPS.
	 *
	 * @return bool
	 */
	public function secure() {
		return $this->isSecure();
	}

	/**
	 * What type of request is this?
	 *
	 * @param  string $type admin, ajax, cron or frontend.
	 * @return bool
	 */
	public function is( $type ) {
		switch ( $type ) {
			case 'admin':
				return is_admin();
			case 'ajax':
				return defined( 'DOING_AJAX' );
			case 'cron':
				return defined( 'DOING_CRON' );
			case 'frontend':
				return ( ! is_admin() || defined( 'DOING_AJAX' ) ) && ! defined( 'DOING_CRON' ) && ! defined( 'REST_REQUEST' );
		}
	}

	/**
	 * Get the client IP address.
	 *
	 * @return string
	 */
	public function ip() {
		return $this->getClientIp();
	}

	/**
	 * Get the client IP addresses.
	 *
	 * @return array
	 */
	public function ips() {
		return $this->getClientIps();
	}

	/**
	 * Get the client user agent.
	 *
	 * @return string
	 */
	public function get_user_agent() {
		return $this->headers->get( 'User-Agent' );
	}

	/**
	 * Merge new input into the current request's input array.
	 *
	 * @param  array $input Added input parameters.
	 * @return void
	 */
	public function merge( array $input ) {
		$this->get_input_source()->add( $input );
	}

	/**
	 * Replace the input for the current request.
	 *
	 * @param  array $input Replace input parameters.
	 * @return void
	 */
	public function replace( array $input ) {
		$this->get_input_source()->replace( $input );
	}

	/**
	 * Get the JSON payload for the request.
	 *
	 * @param  string $key     Optional, special input key. If null ParameterBag will be return.
	 * @param  mixed  $default Default will be return if $key present and not found.
	 * @return ParameterBag|mixed
	 */
	public function json( $key = null, $default = null ) {
		if ( null === $this->json ) {
			$this->json = new ParameterBag( (array) json_decode( $this->getContent(), true ) );
		}

		if ( is_null( $key ) ) {
			return $this->json;
		}

		return data_get( $this->json->all(), $key, $default );
	}

	/**
	 * Get the session associated with the request.
	 *
	 * @return \WPLibs\Session\Store
	 */
	public function session() {
		if ( ! $this->hasSession() ) {
			throw new RuntimeException( 'Session store not set on request.' );
		}

		/* @noinspection PhpIncompatibleReturnTypeInspection */
		return $this->session;
	}

	/**
	 * Get the route handling the request.
	 *
	 * @param  string|null $param Optional, get the special route parameter.
	 * @return array|string|null
	 */
	public function route( $param = null ) {
		$route = call_user_func( $this->get_route_resolver() );

		if ( is_null( $route ) || is_null( $param ) ) {
			return $route;
		}

		return array_key_exists( $param, $route[2] ) ? $route[2][ $param ] : null;
	}

	/**
	 * Get the current route pathinfo (e.g: /example).
	 *
	 * @return string
	 */
	public function route_path() {
		$current_route = $this->route();

		return isset( $current_route[3] ) ? $current_route[3] : null;
	}

	/**
	 * Get the route resolver callback.
	 *
	 * @return \Closure
	 */
	public function get_route_resolver() {
		return $this->route_resolver ?: function () {};
	}

	/**
	 * Set the route resolver callback.
	 *
	 * @param  \Closure $callback The callback.
	 * @return $this
	 */
	public function set_route_resolver( Closure $callback ) {
		$this->route_resolver = $callback;

		return $this;
	}

	/**
	 * Set the session instance on the request.
	 *
	 * @param  \WPLibs\Session\Store $session The session store implementation.
	 * @return void
	 */
	public function set_session( Session $session ) {
		$this->session = $session;
	}

	/**
	 * Alias of set_session method.
	 *
	 * @param \WPLibs\Session\Store $session The session store implementation.
	 */
	public function set_wp_session( Session $session ) {
		$this->session = $session;
	}

	/**
	 * {@inheritdoc}
	 */
	public function hasPreviousSession() {
		return $this->hasSession() && $this->cookies->has( $this->session()->get_name() );
	}

	/**
	 * {@inheritdoc}
	 */
	public function duplicate( array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null ) {
		return parent::duplicate( $query, $request, $attributes, $cookies, $this->filter_files( $files ), $server );
	}

	/**
	 * Create an Request from a Symfony instance.
	 *
	 * @param  Symfony_Request $request The base request.
	 * @return Request
	 */
	public static function create_from_base( Symfony_Request $request ) {
		if ( $request instanceof static ) {
			return $request;
		}

		// Cache the base content, apply to clone later.
		$content = $request->content;

		$request = ( new static )->duplicate(
			$request->query->all(),
			$request->request->all(),
			$request->attributes->all(),
			$request->cookies->all(),
			$request->files->all(),
			$request->server->all()
		);

		$request->content = $content;
		$request->request = $request->get_input_source();

		return $request;
	}

	/**
	 * Filter the given array of files, removing any empty values.
	 *
	 * @param  mixed $files The input files.
	 * @return mixed
	 */
	protected function filter_files( $files ) {
		if ( ! $files ) {
			return null;
		}

		foreach ( $files as $key => $file ) {
			if ( is_array( $file ) ) {
				$files[ $key ] = $this->filter_files( $files[ $key ] );
			}

			if ( empty( $files[ $key ] ) ) {
				unset( $files[ $key ] );
			}
		}

		return $files;
	}

	/**
	 * Get the input source for the request, just like $_REQUEST.
	 *
	 * @return \Symfony\Component\HttpFoundation\ParameterBag
	 */
	protected function get_input_source() {
		if ( $this->is_json() ) {
			return $this->json();
		}

		return 'GET' === $this->getRealMethod() ? $this->query : $this->request;
	}

	/**
	 * Alias of toArray() method.
	 *
	 * @return array
	 */
	public function to_array() {
		return $this->toArray();
	}

	/**
	 * Get all of the input and files for the request.
	 *
	 * @return array
	 */
	public function toArray() {
		return $this->all();
	}

	/**
	 * Determine if the given offset exists.
	 *
	 * @param  string $offset The offset to check.
	 * @return bool
	 */
	public function offsetExists( $offset ) {
		$route_parameters = isset( $this->route()[2] ) ? $this->route()[2] : [];

		return array_key_exists( $offset, $this->all() + $route_parameters );
	}

	/**
	 * Get the value at the given offset.
	 *
	 * @param  string $offset The offset get.
	 * @return mixed
	 */
	public function offsetGet( $offset ) {
		return $this->__get( $offset );
	}

	/**
	 * Set the value at the given offset.
	 *
	 * @param  string $offset The setter offset.
	 * @param  mixed  $value  The setter value.
	 * @return void
	 */
	public function offsetSet( $offset, $value ) {
		$this->get_input_source()->set( $offset, $value );
	}

	/**
	 * Remove the value at the given offset.
	 *
	 * @param  string $offset The offset to unset.
	 * @return void
	 */
	public function offsetUnset( $offset ) {
		$this->get_input_source()->remove( $offset );
	}

	/**
	 * Check if an input element is set on the request.
	 *
	 * @param  string $key Isset key.
	 * @return bool
	 */
	public function __isset( $key ) {
		return ! is_null( $this->__get( $key ) );
	}

	/**
	 * Get an input element from the request.
	 *
	 * @param  string $key Getter key.
	 * @return mixed
	 */
	public function __get( $key ) {
		if ( array_key_exists( $key, $this->all() ) ) {
			return data_get( $this->all(), $key );
		}

		return $this->route( $key );
	}
}


<?php
/**
 * This file is part of the Hephaistos project management API.
 *
 * As each files provides by the CSCFA, this file is licensed
 * under the MIT license.
 *
 * PHP version 5.6
 *
 * @category Trait
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
namespace CSDT\CollectionsBundle\TraitCollection;

/**
 * Value collection trait
 *
 * This trait define the base logic
 * of the value collection.
 *
 * @category Trait
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
trait ValueCollectionTrait
{
    /**
     * Add
     *
     * This method is used to add a new
     * element to the collection.
     *
     * @param mixed $value The value to add
     *
     * @return ValueCollectionInterface
     */
    public function add($value)
    {
        $this->content[] = $value;
        return $this;
    }

    /**
     * Remove
     *
     * This method is used to remove an
     * element from the collection. It
     * return the removed element or null
     * if no one is removed.
     *
     * @param mixed $value The value to remove
     *
     * @return mixed|null
     */
    public function remove($value)
    {
        if ($this->contain($value)) {
            unset($this->content[array_search($value, $this->content)]);
            return $value;
        }

        return null;
    }

    /**
     * Add all
     *
     * This method is used to add a list
     * of new element to the collection.
     *
     * @param array $values The value list to add
     *
     * @return ValueCollectionInterface
     */
    public function addAll(array $values)
    {
        foreach ($values as $value) {
            $this->add($value);
        }
        return $this;
    }

    /**
     * Remove all
     *
     * This method is used to remove a list
     * of element from the collection. It
     * return a list of removed elements.
     *
     * @param array $values The list of value to remove
     *
     * @return array
     */
    public function removeAll(array $values)
    {
        $removedValues = array();
        foreach ($values as $value) {
            if ($this->remove($value) !== null) {
                $removedValues[] = $value;
            }
        }
        return $removedValues;
    }
}


<?php

namespace Orbt\StyleMirror\Css;
use Orbt\ResourceMirror\Resource\MaterializedResource;

/**
 * Aggregate style sheet collection.
 */
class StyleAggregate
{
    protected $styles;

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

    /**
     * Adds a style sheet.
     */
    public function addStyle(MaterializedResource $resource, $mediaType = 'all')
    {
        $this->styles[$resource->getPath()] = array(
            'resource' => $resource,
            'content' => $resource->getContent(),
            'media' => $mediaType,
        );
    }

    /**
     * Gets an aggregated style sheet.
     */
    public function getAggregateStyle()
    {
        $styles = $this->rewritePaths($this->styles);
        $styles = $this->wrapMediaRules($styles);
        $content = $this->concatenateStyles($styles);
        $content = $this->moveImportsToStart($content);
        return $content;
    }

    /**
     * Rewrites the paths of referenced resources.
     */
    protected function rewritePaths(array $styles)
    {
        foreach ($styles as &$style) {
            /** @var $resource MaterializedResource */
            $resource = $style['resource'];
            $replaceCallback = function ($match) use ($resource) {
                return "url('".$resource->resolvePath($match[1])."')";
            };
            $style['content'] = preg_replace_callback(ResourceScanner::PATH_PATTERN, $replaceCallback, $style['content']);
        }
        return $styles;
    }

    /**
     * Wraps resource content in media rules where appropriate.
     */
    protected function wrapMediaRules(array $styles)
    {
        foreach ($styles as &$style) {
            // Wrap in media rule if a media rule does not already exist in a non-all media style.
            if ($style['media'] != 'all' && strpos($style['content'], '@media') === false) {
                $style['content'] = '@media '.$style['media'].' {'.$style['content'].'}';
            }
        }
        return $styles;
    }

    /**
     * Concatenates style resources into one.
     */
    protected function concatenateStyles(array $styles)
    {
        $content = '';
        foreach ($styles as $style) {
            $content .= $style['content'];
        }
        return $content;
    }

    /**
     * Moves import rules to the start of the style sheet.
     */
    protected function moveImportsToStart($content)
    {
        $imports = '';
        $replaceCallback = function ($match) use (&$imports) {
            $imports .= $match[0];
            return '';
        };
        $content = preg_replace_callback('/@import[^;]+;/i', $replaceCallback, $content);
        $content = $imports.$content;
        return $content;
    }
}


<?php

namespace Reaction\Web\Sessions;

use React\Filesystem\Node\File;
use React\Filesystem\Node\FileInterface;
use React\Stream\WritableStreamInterface;
use Reaction\Exceptions\SessionException;
use Reaction\Helpers\FileHelperAsc;
use Reaction\Helpers\Json;
use Reaction\Promise\ExtendedPromiseInterface;
use function Reaction\Promise\reject;
use function Reaction\Promise\resolve;

/**
 * Class SessionArchiveInFiles
 * @package Reaction\Web\Sessions
 */
class SessionArchiveInFiles extends SessionArchiveAbstract
{
    /**
     * @var string Session archive path
     */
    public $archivePath = '@runtime/session_archive';
    /**
     * @var string|null Archive path processed
     */
    protected $_archivePath;

    /**
     * Get data from archive
     * @param string $id Session id
     * @param bool   $remove Flag to remove data
     * @return ExtendedPromiseInterface with data array
     */
    public function get($id, $remove = false)
    {
        $self = $this;
        /** @var File $file */
        $file = null;
        $getPromise = $this->getArchiveFilePath($id, true)->then(
            function($filePath) use (&$file) {
                $file = \Reaction::$app->fs->file($filePath);
                return $file->exists()->then(
                    function() use (&$file) {
                        return $file->open('r');
                    }
                );
            }
        )->then(
            function($stream = null) use (&$file) {
                return $file->getContents();
            }
        )->then(
            function($dataStr) use ($self, &$file, $remove) {
                try {
                    $data = $self->getHandler()->unserializeData($dataStr);
                } catch (\InvalidArgumentException $exception) {
                    $data = null;
                }
                $data = is_array($data) ? $data : null;
                if ($remove) {
                    $callback = function() use ($data) { return $data; };
                    return $file->remove()->then($callback, $callback);
                }
                return $data;
            },
            function() use ($id) {
                $message = sprintf('Failed to restore session "%s"', $id);
                throw new SessionException($message);
            }
        );
        return resolve($getPromise);
    }

    /**
     * Save data to archive
     * @param string $id
     * @param array  $data
     * @return ExtendedPromiseInterface which resolved after save complete
     */
    public function set($id, $data)
    {
        $dataSr = $this->getHandler()->serializeData($data);
        /** @var File $file */
        $file = null;
        $createMode = FileHelperAsc::permissionsAsString(0777);
        $writePromise = $this->getArchiveFilePath($id)->then(
            function($filePath) use (&$file) {
                $file = \Reaction::$app->fs->file($filePath);
                return \Reaction::$app->fs->file($filePath)->exists();
            }
        )->then(null,
            function() use (&$file, $createMode) { return $file->create($createMode); }
        )->then(
            function() use (&$file) { return $file->open('w'); }
        )->then(
            function(WritableStreamInterface $stream) use (&$file, $dataSr) {
                $stream->write($dataSr);
                return $file->close();
            }
        )->then(null, function($error = null) {
            $message = $error instanceof \Throwable
                ? $error->getMessage() . "\n" . $error->getFile() . ' #' . $error->getLine() : $error;
            \Reaction::error($message);
            return false;
        });
        return resolve($writePromise);
    }

    /**
     * Check that session exists in archive
     * @param string $id Session id
     * @return ExtendedPromiseInterface
     */
    public function exists($id)
    {
        return $this->getArchiveFilePath($id, true)->then(
            function() { return true; }
        );
    }

    /**
     * Remove from archive
     * @param string $id Session id
     * @return ExtendedPromiseInterface which resolved when process complete
     */
    public function remove($id)
    {
        return $this->getArchiveFilePath($id, true)->then(
            function($filePath) {
                $file = \Reaction::$app->fs->file($filePath);
                return $file->remove();
            }
        );
    }

    /**
     * Garbage collector callback
     * @param int $lifeTime Session life time in archive
     * @return ExtendedPromiseInterface which resolved after process complete
     */
    public function gc($lifeTime = 3600)
    {
        return $this->getArchivePath()->then(
            function($pathArchive) {
                $path = \Reaction::$app->fs->dir($pathArchive);
                return $path->ls();
            }
        )->then(
            function($list) use ($lifeTime) {
                $promises = [];
                $expiredTime = time() - $lifeTime;
                foreach ($list as $node) {
                    /** @var FileInterface $node */
                    if (!($node instanceof FileInterface)) {
                        continue;
                    }
                    $promises[] = $node->time()->then(
                        function($data) use ($expiredTime, $node) {
                            /** @var \DateTime $date */
                            $date = $data['mtime'];
                            if ($date->getTimestamp() < $expiredTime) {
                                return $node->remove()->then(null, function() {
                                    return true;
                                });
                            }
                            return true;
                        },
                        function() { return false; }
                    );
                }
                return !empty($promises) ? \Reaction\Promise\all($promises) : \Reaction\Promise\resolve(true);
            }
        )->then(null, function() {
            return \Reaction\Promise\resolve(false);
        });
    }

    /**
     * Get archive path
     * @return ExtendedPromiseInterface with string
     */
    protected function getArchivePath() {
        if (!isset($this->_archivePath)) {
            $this->_archivePath = \Reaction::$app->getAlias($this->archivePath);
            $path = \Reaction::$app->getAlias($this->archivePath);
            $self = $this;
            $fs = \Reaction::$app->fs;
            $dirAsFile = $fs->file($path);
            $pathPromise = $dirAsFile->exists()->then(
                null,
                function() use ($path) {
                    return FileHelperAsc::createDir($path, 0777, true);
                }
            )->then(
                function() use (&$self, $path) {
                    $self->_archivePath = $path;
                    return $path;
                },
                function() {
                    throw new SessionException("Failed to get session archive path");
                }
            );
            return resolve($pathPromise);
        }
        return resolve($this->_archivePath);
    }

    /**
     * Get session archive file path
     * @param string $id Session id
     * @param bool   $existCheck
     * @return ExtendedPromiseInterface
     */
    protected function getArchiveFilePath($id, $existCheck = false)
    {
        $fileName = $id . '.json';
        return $this->getArchivePath()->then(
            function($dirPath) use ($fileName) {
                return rtrim($dirPath) . DIRECTORY_SEPARATOR . $fileName;
            }
        )->then(
            function($filePath) use ($existCheck) {
                if ($existCheck) {
                    return \Reaction::$app->fs->file($filePath)->exists()->then(
                        function() use ($filePath) {
                            return $filePath;
                        }
                    );
                }
                return resolve($filePath);
            }
        );
    }
}