<?php

namespace amilna\blog\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use amilna\blog\models\Category;

/**
 * CategorySearch represents the model behind the search form about `amilna\blog\models\Category`.
 */
class CategorySearch extends Category
{

	/*public $blogcatposId;*/
	/*public $categoriesId;*/

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'parent_id', 'isdel'], 'integer'],
            [['title', 'description', 'image'/*, blogcatposId, parentId, categoriesId*/], 'safe'],
            [['status'], 'boolean'],
        ];
    }

	public static function find()
	{
		return parent::find()->where([Category::tableName().'.isdel' => 0]);
	}

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

	private function queryString($fields)
	{
		$params = [];
		foreach ($fields as $afield)
		{
			$field = $afield[0];
			$tab = isset($afield[1])?$afield[1]:false;
			if (!empty($this->$field))
			{
				if (substr($this->$field,0,2) == "< " || substr($this->$field,0,2) == "> " || substr($this->$field,0,2) == "<=" || substr($this->$field,0,2) == ">=" || substr($this->$field,0,2) == "<>")
				{
					array_push($params,[str_replace(" ","",substr($this->$field,0,2)), "lower(".($tab?$tab.".":"").$field.")", strtolower(trim(substr($this->$field,2)))]);
				}
				else
				{
					array_push($params,["like", "lower(".($tab?$tab.".":"").$field.")", strtolower($this->$field)]);
				}
			}
		}
		return $params;
	}

	private function queryNumber($fields)
	{
		$params = [];
		foreach ($fields as $afield)
		{
			$field = $afield[0];
			$tab = isset($afield[1])?$afield[1]:false;
			if (!empty($this->$field))
			{
				$number = explode(" ",trim($this->$field));
				if (count($number) == 2)
				{
					if (in_array($number[0],['>','>=','<','<=','<>']) && is_numeric($number[1]))
					{
						array_push($params,[$number[0], ($tab?$tab.".":"").$field, $number[1]]);
					}
				}
				elseif (count($number) == 3)
				{
					if (is_numeric($number[0]) && is_numeric($number[2]))
					{
						array_push($params,['>=', ($tab?$tab.".":"").$field, $number[0]]);
						array_push($params,['<=', ($tab?$tab.".":"").$field, $number[2]]);
					}
				}
				elseif (count($number) == 1)
				{
					if (is_numeric($number[0]))
					{
						array_push($params,['=', ($tab?$tab.".":"").$field, str_replace(["<",">","="],"",$number[0])]);
					}
				}
			}
		}
		return $params;
	}

	private function queryTime($fields)
	{
		$params = [];
		foreach ($fields as $afield)
		{
			$field = $afield[0];
			$tab = isset($afield[1])?$afield[1]:false;
			if (!empty($this->$field))
			{
				$time = explode(" - ",$this->$field);
				if (count($time) > 1)
				{
					array_push($params,[">=", "concat('',".($tab?$tab.".":"").$field.")", $time[0]]);
					array_push($params,["<=", "concat('',".($tab?$tab.".":"").$field.")", $time[1]." 24:00:00"]);
				}
				else
				{
					if (substr($time[0],0,2) == "< " || substr($time[0],0,2) == "> " || substr($time[0],0,2) == "<=" || substr($time[0],0,2) == ">=" || substr($time[0],0,2) == "<>")
					{
						array_push($params,[str_replace(" ","",substr($time[0],0,2)), "concat('',".($tab?$tab.".":"").$field.")", trim(substr($time[0],2))]);
					}
					else
					{
						array_push($params,["like", "concat('',".($tab?$tab.".":"").$field.")", $time[0]]);
					}
				}
			}
		}
		return $params;
	}

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = $this->find();

        $query->joinWith([/*,blogcatpos,categories*/]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        /* uncomment to sort by relations table on respective column
		$dataProvider->sort->attributes['blogcatposId'] = [
			'asc' => ['{{%blogcatpos}}.id' => SORT_ASC],
			'desc' => ['{{%blogcatpos}}.id' => SORT_DESC],
		];
		$dataProvider->sort->attributes['categoriesId'] = [
			'asc' => ['{{%categories}}.id' => SORT_ASC],
			'desc' => ['{{%categories}}.id' => SORT_DESC],
		];*/

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $params = self::queryNumber([['id',$this->tableName()],['parent_id'],['status'],['isdel']/*['id','{{%blogcatpos}}'],['id','{{%parent}}'],['id','{{%categories}}']*/]);
		foreach ($params as $p)
		{
			$query->andFilterWhere($p);
		}
        $params = self::queryString([['title'],['description'],['image']/*['id','{{%blogcatpos}}'],['id','{{%parent}}'],['id','{{%categories}}']*/]);
		foreach ($params as $p)
		{
			$query->andFilterWhere($p);
		}
        return $dataProvider;
    }
}


<?php

namespace amilna\blog\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use amilna\blog\models\File;

/**
 * FileSearch represents the model behind the search form about `amilna\blog\models\File`.
 */
class FileSearch extends File
{

	public $term;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'isdel'], 'integer'],
            [['title', 'term', 'description', 'file', 'tags', 'time'], 'safe'],
            [['status'], 'boolean'],
        ];
    }

	/* uncomment to undisplay deleted records (assumed the table has column isdel) */
	public static function find()
	{
		return parent::find()->where([File::tableName().'.isdel' => 0]);
	}

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

	private function queryString($fields)
	{
		$params = [];
		foreach ($fields as $afield)
		{
			$field = $afield[0];
			$tab = isset($afield[1])?$afield[1]:false;
			if (!empty($this->$field))
			{
				if (substr($this->$field,0,2) == "< " || substr($this->$field,0,2) == "> " || substr($this->$field,0,2) == "<=" || substr($this->$field,0,2) == ">=" || substr($this->$field,0,2) == "<>")
				{
					array_push($params,[str_replace(" ","",substr($this->$field,0,2)), "lower(".($tab?$tab.".":"").$field.")", strtolower(trim(substr($this->$field,2)))]);
				}
				else
				{
					array_push($params,["like", "lower(".($tab?$tab.".":"").$field.")", strtolower($this->$field)]);
				}
			}
		}
		return $params;
	}

	private function queryNumber($fields)
	{
		$params = [];
		foreach ($fields as $afield)
		{
			$field = $afield[0];
			$tab = isset($afield[1])?$afield[1]:false;
			if (!empty($this->$field))
			{
				$number = explode(" ",trim($this->$field));
				if (count($number) == 2)
				{
					if (in_array($number[0],['>','>=','<','<=','<>']) && is_numeric($number[1]))
					{
						array_push($params,[$number[0], ($tab?$tab.".":"").$field, $number[1]]);
					}
				}
				elseif (count($number) == 3)
				{
					if (is_numeric($number[0]) && is_numeric($number[2]))
					{
						array_push($params,['>=', ($tab?$tab.".":"").$field, $number[0]]);
						array_push($params,['<=', ($tab?$tab.".":"").$field, $number[2]]);
					}
				}
				elseif (count($number) == 1)
				{
					if (is_numeric($number[0]))
					{
						array_push($params,['=', ($tab?$tab.".":"").$field, str_replace(["<",">","="],"",$number[0])]);
					}
				}
			}
		}
		return $params;
	}

	private function queryTime($fields)
	{
		$params = [];
		foreach ($fields as $afield)
		{
			$field = $afield[0];
			$tab = isset($afield[1])?$afield[1]:false;
			if (!empty($this->$field))
			{
				$time = explode(" - ",$this->$field);
				if (count($time) > 1)
				{
					array_push($params,[">=", "concat('',".($tab?$tab.".":"").$field.")", $time[0]]);
					array_push($params,["<=", "concat('',".($tab?$tab.".":"").$field.")", $time[1]." 24:00:00"]);
				}
				else
				{
					if (substr($time[0],0,2) == "< " || substr($time[0],0,2) == "> " || substr($time[0],0,2) == "<=" || substr($time[0],0,2) == ">=" || substr($time[0],0,2) == "<>")
					{
						array_push($params,[str_replace(" ","",substr($time[0],0,2)), "concat('',".($tab?$tab.".":"").$field.")", trim(substr($time[0],2))]);
					}
					else
					{
						array_push($params,["like", "concat('',".($tab?$tab.".":"").$field.")", $time[0]]);
					}
				}
			}
		}
		return $params;
	}

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = $this->find();

        $query->joinWith([/**/]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        /* uncomment to sort by relations table on respective column*/

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'status' => $this->status,
            /**/
        ]);

        $params = self::queryNumber([['id',$this->tableName()],['isdel']]);
		foreach ($params as $p)
		{
			$query->andFilterWhere($p);
		}
        $params = self::queryString([['title'],['description'],['file'],['tags']]);
		foreach ($params as $p)
		{
			$query->andFilterWhere($p);
		}
        $params = self::queryTime([['time']]);
		foreach ($params as $p)
		{
			$query->andFilterWhere($p);
		}

		/* example to use search all in field1,field2,field3 or field4
		if ($this->term)
		{
			$query->andFilterWhere(["OR","lower(field1) like '%".strtolower($this->term)."%'",
				["OR","lower(field2) like '%".strtolower($this->term)."%'",
					["OR","lower(field3) like '%".strtolower($this->term)."%'",
						"lower(field4) like '%".strtolower($this->term)."%'"
					]
				]
			]);
		}
		*/

		$query->andFilterWhere(["like","lower(concat(title,description,file))",strtolower($this->term)]);

        return $dataProvider;
    }
}


<?php

namespace Mouf\Database\SchemaAnalyzer;

use Fhaculty\Graph\Edge;
use Fhaculty\Graph\Exception\UnexpectedValueException;
use Fhaculty\Graph\Vertex;
use SplPriorityQueue;

/**
 * Dijkstra's shortest path algorithm modified to measure all possible shortest paths.
 */
class MultiDijkstra
{
    /**
     * Get all edges on shortest path for this vertex.
     *
     * @throws UnexpectedValueException     when encountering an Edge with negative weight
     * @throws MultiDijkstraNoPathException
     *
     * @return array<string, Vertex[]> where key is the destination vertex name and value is an array of possible origin vertex
     */
    public static function findShortestPaths(Vertex $startVertex, Vertex $endVertex)
    {
        $totalCostOfCheapestPathTo = [];
        // start node distance
        $totalCostOfCheapestPathTo[$startVertex->getId()] = 0;

        $endVertexId = $endVertex->getId();

        // just to get the cheapest vertex in the correct order
        $cheapestVertex = new SplPriorityQueue();
        $cheapestVertex->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
        $cheapestVertex->insert($startVertex, 0);

        // predecessors
        $predecesEdgeOfCheapestPathTo = [];

        // mark vertices when their cheapest path has been found
        $usedVertices = [$startVertex->getId() => true];

        $isFirst = true;

        // Repeat until all vertices have been marked
        $totalCountOfVertices = count($startVertex->getGraph()->getVertices());
        for ($i = 0; $i < $totalCountOfVertices; ++$i) {
            $currentVertex = null;
            $currentVertexId = null;
            $isEmpty = false;
            if ($isFirst) {
                $currentVertex = $startVertex;
                $currentCost = 0;
                $currentVertexId = $currentVertex->getId();
            } else {
                do {
                    // if the priority queue is empty there are isolated vertices, but the algorithm visited all other vertices
                    if ($cheapestVertex->isEmpty()) {
                        $isEmpty = true;
                        break;
                    }
                    // Get cheapest unmarked vertex
                    $cheapestResult = $cheapestVertex->extract();
                    $currentVertex = $cheapestResult['data'];
                    $currentCost = $cheapestResult['priority'];
                    $currentVertexId = $currentVertex->getId();
                // Vertices can be in the priority queue multiple times, with different path costs (if vertex is already marked, this is an old unvalid entry)
                } while (isset($usedVertices[$currentVertexId]));
            }

            // Check premature end condition
            // If the end vertex is marked as done and the next lowest possible weight is bigger than end vertix,
            // we are done processing.

            // catch "algorithm ends" condition
            if ($isEmpty) {
                break;
            }

            if ($isFirst) {
                $isFirst = false;
            }

            // mark this vertex
            $usedVertices[$currentVertexId] = true;

            if (isset($usedVertices[$endVertexId]) && $totalCostOfCheapestPathTo[$endVertexId] < -$currentCost) {
                break;
            }

            // check for all edges of current vertex if there is a cheaper path (or IN OTHER WORDS: Add reachable nodes from currently added node and refresh the current possible distances)
            foreach ($currentVertex->getEdgesOut() as $edge) {
                $weight = $edge->getWeight();
                if ($weight < 0) {
                    throw new UnexpectedValueException('Dijkstra not supported for negative weights - Consider using MooreBellmanFord');
                }

                $targetVertex = $edge->getVertexToFrom($currentVertex);
                $targetVertexId = $targetVertex->getId();

                // if the targetVertex is marked, the cheapest path for this vertex has already been found (no negative edges) {
                if (!isset($usedVertices[$targetVertexId])) {
                    // calculate new cost to vertex
                    $newCostsToTargetVertex = $totalCostOfCheapestPathTo[$currentVertexId] + $weight;

                    if ((!isset($predecesEdgeOfCheapestPathTo[$targetVertexId]))
                           // is the new path cheaper?
                           || $totalCostOfCheapestPathTo[$targetVertexId] > $newCostsToTargetVertex) {

                        // Not an update, just a new insert with lower cost
                        $cheapestVertex->insert($targetVertex, -$newCostsToTargetVertex);
                        // so the lowest cost will be extracted first
                        // and higher cost will be skipped during extraction

                        // update/set costs found with the new connection
                        $totalCostOfCheapestPathTo[$targetVertexId] = $newCostsToTargetVertex;
                        // update/set predecessor vertex from the new connection
                        $predecesEdgeOfCheapestPathTo[$targetVertexId] = [$edge];
                    } elseif ($totalCostOfCheapestPathTo[$targetVertexId] == $newCostsToTargetVertex) {
                        // Same length paths. We need to add the predecessor to the list of possible predecessors.
                        $predecesEdgeOfCheapestPathTo[$targetVertexId][] = $edge;
                    }
                }
            }
        }

        if (!isset($totalCostOfCheapestPathTo[$endVertexId])) {
            throw new MultiDijkstraNoPathException("No path found between vertex '".$startVertex->getId()."' and vertex '".$endVertex->getId()."'");
        }

        // algorithm is done, return resulting edges
        return $predecesEdgeOfCheapestPathTo;
    }

    /**
     * @param array<string, Vertex[]> $predecesEdgesArray key is the destination vertex name and value is an array of possible origin vertex
     *
     * @return Edge\Base[]
     */
    public static function getCheapestPathFromPredecesArray(Vertex $startVertex, Vertex $endVertex, array $predecesEdgesArray)
    {
        $edges = [];
        $currentVertex = $endVertex;
        while ($currentVertex !== $startVertex) {
            $predecessorEdges = $predecesEdgesArray[$currentVertex->getId()];
            if (count($predecessorEdges) > 1) {
                throw new MultiDijkstraAmbiguityException("There are many possible shortest paths to link vertex '".$startVertex->getId()."' to '".$endVertex->getId()."'");
            }
            /* @var $edge \Fhaculty\Graph\Edge\Base */
            $edge = $predecessorEdges[0];
            $edges[] = $edge;
            if ($currentVertex === $edge->getVerticesStart()->getVertexFirst()) {
                $currentVertex = $edge->getVerticesTarget()->getVertexFirst();
            } else {
                $currentVertex = $edge->getVerticesStart()->getVertexFirst();
            }
        }

        return array_reverse($edges);
    }

    /**
     * @param Vertex $startVertex
     * @param Vertex $endVertex
     * @param array  $predecesEdgesArray
     *
     * @return Edge\Base[][]
     */
    public static function getAllPossiblePathsFromPredecesArray(Vertex $startVertex, Vertex $endVertex, array $predecesEdgesArray)
    {
        $edgesPaths = [];

        if ($startVertex === $endVertex) {
            return [];
        }

        $predecessorEdges = $predecesEdgesArray[$endVertex->getId()];

        foreach ($predecessorEdges as $edge) {
            if ($endVertex === $edge->getVerticesStart()->getVertexFirst()) {
                $nextVertex = $edge->getVerticesTarget()->getVertexFirst();
            } else {
                $nextVertex = $edge->getVerticesStart()->getVertexFirst();
            }

            $edgesPaths2 = self::getAllPossiblePathsFromPredecesArray($startVertex, $nextVertex, $predecesEdgesArray);
            if ($edgesPaths2) {
                foreach ($edgesPaths2 as &$edges2) {
                    $edges2[] = $edge;
                }
            } else {
                $edgesPaths2 = [[$edge]];
            }

            $edgesPaths = array_merge($edgesPaths, $edgesPaths2);
        }

        return $edgesPaths;
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Router\UrlGenerator;

use Nice\Router\RouteCollectorInterface;

/**
 * URL data generator for FastRoute's GroupCountBased route data generator
 */
class GroupCountBasedDataGenerator implements DataGeneratorInterface
{
    /**
     * @var \Nice\Router\RouteCollectorInterface
     */
    private $routeCollector;

    /**
     * Constructor
     *
     * @param RouteCollectorInterface $routeCollector
     */
    public function __construct(RouteCollectorInterface $routeCollector)
    {
        $this->routeCollector = $routeCollector;
    }

    /**
     * Get formatted route data for use by a URL generator
     *
     * @return array
     */
    public function getData()
    {
        $routes = $this->routeCollector->getData();
        $data = array();
        foreach ($routes[0] as $method => $paths) {
            foreach ($paths as $path => $handler) {
                if (is_array($handler) && isset($handler['name'])) {
                    $data[$handler['name']] = $path;
                }
            }
        }

        foreach ($routes[1] as $method) {
            foreach ($method as $group) {
                $data = array_merge($data, $this->parseDynamicGroup($group));
            }
        }

        return $data;
    }

    /**
     * Parse a group of dynamic routes
     *
     * @param $group
     * @return array
     */
    private function parseDynamicGroup($group)
    {
        $regex = $group['regex'];
        $parts = explode('|', $regex);
        $data = array();
        foreach ($group['routeMap'] as $matchIndex => $routeData) {
            if (!is_array($routeData[0]) || !isset($routeData[0]['name']) || !isset($parts[$matchIndex - 1])) {
                continue;
            }

            $parameters = $routeData[1];
            $path = $parts[$matchIndex - 1];

            foreach ($parameters as $parameter) {
                $path = $this->replaceOnce('([^/]+)', '{'.$parameter.'}', $path);
            }

            $path = rtrim($path, '()$~');

            $data[$routeData[0]['name']] = array(
                'path' => $path,
                'params' => $parameters,
            );
        }

        return $data;
    }

    /**
     * Replace the first occurrence of a string
     *
     * @param  string $search
     * @param  string $replace
     * @param  string $subject
     * @return mixed
     */
    private function replaceOnce($search, $replace, $subject)
    {
        $pos = strpos($subject, $search);
        if ($pos !== false) {
            $subject = substr_replace($subject, $replace, $pos, strlen($search));
        }

        return $subject;
    }
}


<?php

namespace SSD\StringConverter\Types;

use SSD\StringConverter\{
    RegEx, Converter
};

class ClassName extends Converter implements Contract
{
    /**
     * Convert to class name.
     *
     * @param  \SSD\StringConverter\Types\Contract $contract
     * @param  string $string
     * @param  callable|null $callback
     * @return string
     */
    public function from(Contract $contract, string $string, callable $callback = null): string
    {
        $string = ucwords(
            $contract->recipe(
                $string,
                'upperCaseFirst',
                function ($string) use ($contract) {

                    if ($contract instanceof Camel) {
                        return $string;
                    }

                    return strtolower($string);
                }
            )
        );

        return $this->callback($string, $callback);
    }

    /**
     * Conversion recipe.
     *
     * @param  string $string
     * @param  string $method
     * @param  callable|null $callback
     * @return mixed
     */
    public function recipe(string $string, string $method, callable $callback = null): string
    {
        return preg_replace_callback(
            RegEx::REGEX_CAPITAL_LETTERS,
            [$this, $method],
            $this->callback($string, $callback)
        );
    }
}


<?php

namespace SSD\StringConverter\Types;

use SSD\StringConverter\{
    RegEx, Converter
};

class Camel extends Converter implements Contract
{
    /**
     * Convert to camel case.
     *
     * @param  \SSD\StringConverter\Types\Contract $contract
     * @param  string $string
     * @param  callable|null $callback
     * @return string
     */
    public function from(Contract $contract, string $string, callable $callback = null): string
    {
        return $this->callback(
            $contract->recipe(
                $string,
                'upperCaseFirst',
                function ($string) use ($contract) {

                    if ($contract instanceof ClassName) {
                        return lcfirst($string);
                    }

                    return strtolower($string);
                }
            ),
            $callback
        );
    }

    /**
     * Conversion recipe.
     *
     * @param  string $string
     * @param  string $method
     * @param  callable|null $callback
     * @return mixed
     */
    public function recipe(string $string, string $method, callable $callback = null): string
    {
        return preg_replace_callback(
            RegEx::REGEX_CAPITAL_LETTERS,
            [$this, $method],
            $this->callback($string, $callback)
        );
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Router;

use FastRoute\Dispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Handles resolving a controller for the incoming Request
 */
class RouterSubscriber implements EventSubscriberInterface
{
    /**
     * @var \FastRoute\Dispatcher
     */
    private $dispatcher;

    /**
     * Constructor
     *
     * @param Dispatcher $dispatcher
     */
    public function __construct(Dispatcher $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * @param GetResponseEvent $event
     *
     * @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if ($request->get('_controller')) {
            return;
        }

        $routeInfo = $this->dispatcher->dispatch($request->getMethod(), $request->getPathInfo());
        switch ($routeInfo[0]) {
            case Dispatcher::NOT_FOUND:
                $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo());

                throw new NotFoundHttpException($message);

            case Dispatcher::METHOD_NOT_ALLOWED:
                $allowedMethods = $routeInfo[1];
                $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getPathInfo(), implode(', ', $allowedMethods));

                throw new MethodNotAllowedHttpException($allowedMethods, $message);

            case Dispatcher::FOUND:
                $handler = $routeInfo[1];
                $vars = $routeInfo[2];

                $request->attributes->add($vars);
                $request->attributes->set('_controller', $handler);

                break;
        }
    }

    /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST => array('onKernelRequest', 0),
        );
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Router\UrlGenerator;

use Nice\Router\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * A simple URL generator implementation
 */
class SimpleUrlGenerator implements UrlGeneratorInterface
{
    /**
     * @var DataGeneratorInterface
     */
    private $dataGenerator;

    private $initialized = false;

    private $routes = array();

    /**
     * @var Request
     */
    private $request;

    /**
     * Constructor
     *
     * @param DataGeneratorInterface $dataGenerator
     */
    public function __construct(DataGeneratorInterface $dataGenerator)
    {
        $this->dataGenerator = $dataGenerator;
    }

    /**
     * Generate a URL for the given route
     *
     * @param string $name       The name of the route to generate a url for
     * @param array  $parameters Parameters to pass to the route
     * @param bool   $absolute   If true, the generated route should be absolute
     *
     * @return string
     */
    public function generate($name, array $parameters = array(), $absolute = false)
    {
        if (!$this->initialized) {
            $this->initialize();
        }

        $path = $this->routes[$name];
        if (is_array($path)) {
            $params = $path['params'];
            $path = $path['path'];

            foreach ($params as $param) {
                if (!isset($parameters[$param])) {
                    throw new \RuntimeException('Missing required parameter "'.$param.'". Optional parameters not currently supported');
                }

                $path = str_replace('{'.$param.'}', $parameters[$param], $path);
            }
        }

        if ($this->request) {
            $path = $this->request->getBaseUrl().$path;

            if ($absolute) {
                $path = $this->request->getSchemeAndHttpHost().$path;
            }
        }

        return $path;
    }

    /**
     * @param \Symfony\Component\HttpFoundation\Request $request
     */
    public function setRequest(Request $request = null)
    {
        $this->request = $request;
    }

    /**
     * Initialize the generator
     */
    private function initialize()
    {
        $this->routes = $this->dataGenerator->getData();
        $this->initialized = true;
    }
}


<?php

namespace SSD\StringConverter;

abstract class Converter
{
    /**
     * Convert first letter to upper case.
     *
     * @param  array $params
     * @return string
     */
    final protected function upperCaseFirst(array $params): string
    {
        return ucfirst($params[1]);
    }

    /**
     * Prepend hyphen.
     *
     * @param  array $params
     * @return string
     */
    final protected function hyphen(array $params): string
    {
        return "-".$params[1];
    }

    /**
     * Prepend underscore.
     *
     * @param  array $params
     * @return string
     */
    final public function underscore(array $params): string
    {
        return "_".$params[1];
    }

    /**
     * Prepend space.
     *
     * @param  array $params
     * @return string
     */
    final protected function space(array $params): string
    {
        return " ".$params[1];
    }

    /**
     * Callback.
     *
     * @param  string $string
     * @param  callable|null $callback
     * @return string
     */
    final protected function callback(string $string, callable $callback = null): string
    {
        if (!is_callable($callback)) {
            return $string;
        }

        return call_user_func($callback, $string);
    }
}


<?php

namespace StuYam\KickboxValidator;

use Illuminate\Support\ServiceProvider;
use \Kickbox\Client as Kickbox;
// use \Validator as Validator;

class KickboxValidatorServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // allow publishing off the config
        $this->publishes([
            __DIR__.'/config/kickbox.php' => config_path('kickbox.php'),
        ], 'kickbox');

        // load translation files
        $this->loadTranslationsFrom(__DIR__ . '/lang', 'kickbox');

        $this->app->booted(function($app) {
            // get validator and translator
            $validator = $app['validator'];
            $translator = $app['translator'];

            // setup custom kickbox validator
            $validator->extend('kickbox', function($attribute, $value, $parameters, $validator){

                // fetch the api key from the config - which allows the config to be cached
                $kickboxApiKey = config('kickbox.api_key');

                // throw exception if the kickbox credentials are missing from the env
                if( $kickboxApiKey == null ) {
                    // throw the custom exception defined below
                    throw new KickboxCredentialsNotFoundException('Please provide a KICKBOX_API_KEY in your .env file.');
                }

                // get kickbox key from users env file
                $client = new Kickbox($kickboxApiKey);
                return $client->kickbox()->verify($value)->body['result'] !== 'undeliverable';
            }, $translator->get('kickbox::validation.kickbox'));

        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__ . '/config/kickbox.php', 'kickbox'
        );
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Extension;

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

class LogConfiguration implements ConfigurationInterface
{
    /**
     * Generates the configuration tree builder.
     *
     * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('logging');

        $rootNode
            ->children()
                ->arrayNode('channels')
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->addDefaultsIfNotSet()
                        ->children()
                            ->scalarNode('handler')
                                ->isRequired()
                                ->validate()
                                    ->ifNotInArray(array('stream', 'error_log'))
                                    ->thenInvalid('Invalid logging handler %s')
                                ->end()
                            ->end()
                            ->scalarNode('level')->defaultValue(200)->end()
                            ->arrayNode('options')->defaultValue(array())
                                ->prototype('scalar')
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice;

use Nice\DependencyInjection\CacheRoutingDataPass;
use Nice\DependencyInjection\ConfigurationProvider\NullConfigurationProvider;
use Nice\DependencyInjection\ConfigurationProviderInterface;
use Nice\DependencyInjection\ContainerInitializer\CachedInitializer;
use Nice\DependencyInjection\ContainerInitializer\DefaultInitializer;
use Nice\DependencyInjection\ContainerInitializerInterface;
use Nice\DependencyInjection\ExtendableInterface;
use Nice\Extension\RouterExtension;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\DependencyInjection\Scope;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;

/**
 * A Nice Application
 */
class Application implements HttpKernelInterface, ExtendableInterface
{
    /**
     * @var bool
     */
    protected $cache;

    /**
     * @var bool
     */
    protected $debug;

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

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

    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var ConfigurationProviderInterface
     */
    protected $configProvider;

    /**
     * @var array|Extension[]
     */
    private $extensions = array();

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

    /**
     * @var HttpKernelInterface
     */
    private $kernel;

    /**
     * @var bool
     */
    private $booted = false;

    /**
     * Constructor.
     *
     * @param string $environment
     * @param bool   $debug
     * @param bool   $cache
     */
    public function __construct($environment = 'dev', $debug = false, $cache = true)
    {
        $this->environment = (string) $environment;
        $this->debug       = (bool) $debug;
        $this->cache       = (bool) $cache;
    }

    /**
     * Boots the Application.
     */
    public function boot()
    {
        if ($this->booted) {
            return;
        }

        $this->container = $this->initializeContainer();
        $this->kernel    = $this->container->get('http_kernel');

        $this->booted = true;
    }

    /**
     * Prepends an extension.
     *
     * @param ExtensionInterface $extension
     */
    public function prependExtension(ExtensionInterface $extension)
    {
        array_unshift($this->extensions, $extension);
    }

    /**
     * Appends an extension.
     *
     * @param ExtensionInterface $extension
     */
    public function appendExtension(ExtensionInterface $extension)
    {
        array_push($this->extensions, $extension);
    }

    /**
     * Gets an ordered list of extensions.
     *
     * @return array|ExtensionInterface[]
     */
    public function getExtensions()
    {
        return $this->extensions;
    }

    /**
     * Adds a compiler pass.
     *
     * @param CompilerPassInterface $pass A compiler pass
     * @param string                $type The type of compiler pass
     */
    public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION)
    {
        $this->compilerPasses[] = array($pass, $type);
    }

    /**
     * Registers default extensions.
     *
     * This method allows a subclass to customize default extensions
     */
    protected function registerDefaultExtensions()
    {
        $this->appendExtension(new RouterExtension());

        if ($this->isCacheEnabled()) {
            $this->addCompilerPass(new CacheRoutingDataPass());
        }
    }

    /**
     * Initializes a new container.
     *
     * @return ContainerInterface
     */
    protected function initializeContainer()
    {
        $this->registerDefaultExtensions();
        $initializer = $this->getContainerInitializer();
        $this->container = $initializer->initializeContainer($this, $this->extensions, $this->compilerPasses);
        $this->container->set('app', $this);

        return $this->container;
    }

    /**
     * Returns a ContainerInitializer.
     *
     * A ContainerInitializer creates fully-built, ready-to-use containers.
     *
     * @return ContainerInitializerInterface
     */
    protected function getContainerInitializer()
    {
        $initializer = new DefaultInitializer($this->getConfigurationProvider());
        if ($this->cache) {
            $initializer = new CachedInitializer($initializer, $this->getCacheDir());
        }

        return $initializer;
    }

    /**
     * Sets the ConfigurationProvider.
     *
     * @param ConfigurationProviderInterface $configProvider
     */
    public function setConfigurationProvider(ConfigurationProviderInterface $configProvider)
    {
        $this->configProvider = $configProvider;
    }

    /**
     * Returns a ConfigurationProvider.
     *
     * A ConfigurationProvider can load configuration files and configure ContainerBuilders.
     *
     * @return ConfigurationProviderInterface
     */
    public function getConfigurationProvider()
    {
        return $this->configProvider ?: new NullConfigurationProvider();
    }

    /**
     * Helper method to get things going.
     *
     * Inspired by Silex.
     *
     * @param Request $request
     */
    public function run(Request $request = null)
    {
        $request = $request ?: Request::createFromGlobals();
        $response = $this->handle($request);
        $response->send();

        if ($this->kernel instanceof TerminableInterface) {
            $this->kernel->terminate($request, $response);
        }
    }

    /**
     * Handles a Request to convert it to a Response.
     *
     * @param Request $request A Request instance
     * @param int     $type    The type of the request
     *                         (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
     * @param bool    $catch   Whether to catch exceptions or not
     *
     * @return Response A Response instance
     */
    public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
    {
        if (!$this->booted) {
            $this->boot();
        }

        $request->attributes->set('app', $this);

        return $this->kernel->handle($request, $type, $catch);
    }

    /**
     * Gets the root directory.
     *
     * @return string
     */
    public function getRootDir()
    {
        if (!$this->rootDir) {
            $refl = new \ReflectionObject($this);
            $filename = $refl->getFileName();
            if (false !== ($pos = strrpos($filename, '/vendor/'))) {
                $filename = substr($filename, 0, $pos);
            } else {
                $filename = dirname($filename).'/..';
            }

            $this->rootDir = str_replace('\\', '/', $filename);
        }

        return $this->rootDir;
    }

    /**
     * Gets the cache directory.
     *
     * @return string|null Null if Caching should be disabled
     */
    public function getCacheDir()
    {
        return $this->cache
            ? $this->getRootDir().'/cache/'.$this->environment
            : null;
    }

    /**
     * Gets the log directory.
     *
     * @return string
     */
    public function getLogDir()
    {
        return $this->getRootDir().'/logs';
    }

    /**
     * Gets the environment.
     *
     * @return string
     */
    public function getEnvironment()
    {
        return $this->environment;
    }

    /**
     * Gets the charset.
     *
     * @return string
     */
    public function getCharset()
    {
        return 'UTF-8';
    }

    /**
     * Returns true if debug is enabled.
     *
     * @return boolean
     */
    public function isDebug()
    {
        return $this->debug;
    }

    /**
     * Returns true if caching is enabled.
     *
     * @return boolean
     */
    public function isCacheEnabled()
    {
        return $this->cache;
    }

    /**
     * Gets the service container.
     *
     * @return ContainerInterface
     */
    public function getContainer()
    {
        return $this->container;
    }

    /**
     * Sets a service within the service container.
     *
     * @param string          $id      The service identifier
     * @param object|callable $service The service instance
     * @param string          $scope   The scope of the service
     */
    public function set($id, $service, $scope = ContainerInterface::SCOPE_CONTAINER)
    {
        if (!$this->booted) {
            $this->boot();
        }

        $this->container->set($id, $service, $scope);
    }

    /**
     * Gets a service from the service container.
     *
     * @param string $id              The service identifier
     * @param int    $invalidBehavior The behavior when the service does not exist
     *
     * @return object The associated service
     */
    public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE)
    {
        if (!$this->booted) {
            $this->boot();
        }

        return $this->container->get($id, $invalidBehavior);
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\DependencyInjection\ContainerInitializer;

use Nice\Application;
use Nice\DependencyInjection\ContainerInitializerInterface;
use Symfony\Component\Config\ConfigCache;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;

/**
 * Wraps a ContainerInitializer, providing a file-based cache for the built container
 */
class CachedInitializer implements ContainerInitializerInterface
{
    /**
     * @var string
     */
    private $cacheDir;

    /**
     * @var \Nice\DependencyInjection\ContainerInitializerInterface
     */
    private $wrappedInitializer;

    /**
     * Constructor
     *
     * @param ContainerInitializerInterface $wrappedInitializer
     * @param string                        $cacheDir
     */
    public function __construct(ContainerInitializerInterface $wrappedInitializer, $cacheDir)
    {
        if (!is_dir($cacheDir)) {
            if (false === @mkdir($cacheDir, 0777, true)) {
                throw new \RuntimeException(sprintf("Unable to create the cache directory (%s)", $cacheDir));
            }
        } elseif (!is_writable($cacheDir)) {
            throw new \RuntimeException(sprintf("Unable to write in the cache directory (%s)", $cacheDir));
        }

        $this->cacheDir = $cacheDir;
        $this->wrappedInitializer = $wrappedInitializer;
    }

    /**
     * Returns a fully built, ready to use Container
     *
     * @param Application                   $application
     * @param array|ExtensionInterface[]    $extensions
     * @param array|CompilerPassInterface[] $compilerPasses
     *
     * @return ContainerInterface
     */
    public function initializeContainer(Application $application, array $extensions = array(), array $compilerPasses = array())
    {
        $class = $this->getContainerClass($application);
        $cache = new ConfigCache($this->cacheDir.'/'.$class.'.php', $application->isDebug());
        if (!$cache->isFresh()) {
            $container = $this->wrappedInitializer->initializeContainer($application, $extensions, $compilerPasses);

            $this->dumpContainer($cache, $container, $class, 'Container');
        }

        require_once $cache;

        return new $class();
    }

    /**
     * Gets the container class.
     *
     * @return string The container class
     */
    protected function getContainerClass(Application $application)
    {
        return ucfirst($application->getEnvironment()).($application->isDebug() ? 'Debug' : '').'ProjectContainer';
    }

    /**
     * Dumps the service container to PHP code in the cache.
     *
     * @param ConfigCache      $cache     The config cache
     * @param ContainerBuilder $container The service container
     * @param string           $class     The name of the class to generate
     * @param string           $baseClass The name of the container's base class
     */
    protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
    {
        $dumper  = new PhpDumper($container);
        $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass));

        $cache->write($content, $container->getResources());
    }
}


<?php
/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Enrise B.V.
 *
 * 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.
 *
 * @author Richard Tuin <richard@enrise.com>
 */

namespace Enrise\ZfModule\ElasticSearch;

use Elasticsearch\Client as ElasticsearchClient;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ClientFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $configService = $serviceLocator->get('Config');
        $params = [];
        if (isset($configService['elasticsearch'])) {
            $params = $configService['elasticsearch'];
        }

        return new ElasticsearchClient($params);
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Router\UrlGenerator;

use Symfony\Component\Config\ConfigCache;

/**
 * A file-based cached DataGenerator which wraps another DataGenerator
 */
class CachedDataGenerator implements DataGeneratorInterface
{
    /**
     * @var DataGeneratorInterface
     */
    private $wrappedGenerator;

    /**
     * @var
     */
    private $cacheFile;

    /**
     * @var bool
     */
    private $debug;

    /**
     * Constructor
     *
     * @param DataGeneratorInterface $wrappedGenerator
     * @param string                 $cacheFile
     * @param bool                   $debug
     */
    public function __construct(DataGeneratorInterface $wrappedGenerator, $cacheFile, $debug = false)
    {
        $this->wrappedGenerator = $wrappedGenerator;
        $this->cacheFile = $cacheFile;
        $this->debug = $debug;
    }

    /**
     * Get formatted route data for use by a URL generator
     *
     * @return array
     */
    public function getData()
    {
        $cache = new ConfigCache($this->cacheFile, $this->debug);
        if (!$cache->isFresh()) {
            $routes = $this->wrappedGenerator->getData();

            $cache->write('<?php return '.var_export($routes, true).';');
        }

        return require $cache;
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Extension;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Extension\Extension;

/**
 * Sets up Session related services
 */
class SessionExtension extends Extension
{
    /**
     * Loads a specific configuration.
     *
     * @param array            $config    An array of configuration values
     * @param ContainerBuilder $container A ContainerBuilder instance
     */
    public function load(array $config, ContainerBuilder $container)
    {
        $container->register('session', 'Symfony\Component\HttpFoundation\Session\Session');

        $container->register('session.session_subscriber', 'Nice\Session\SessionSubscriber')
            ->addArgument(new Reference('service_container'))
            ->addTag('kernel.event_subscriber');
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Router\NamedDataGenerator;

use FastRoute\DataGenerator;
use Nice\Router\NamedDataGeneratorInterface;

/**
 * HandlerWrapperGenerator adds extra metadata to routes to support named routes
 */
class HandlerWrapperGenerator implements NamedDataGeneratorInterface
{
    /**
     * @var \FastRoute\DataGenerator
     */
    private $wrappedGenerator;

    /**
     * Constructor
     *
     * @param DataGenerator $wrappedGenerator
     */
    public function __construct(DataGenerator $wrappedGenerator)
    {
        $this->wrappedGenerator = $wrappedGenerator;
    }

    /**
     * Adds a route to the data generator. The route data uses the
     * same format that is returned by RouterParser::parser().
     *
     * The handler doesn't necessarily need to be a callable, it
     * can be arbitrary data that will be returned when the route
     * matches.
     *
     * @param string $httpMethod
     * @param array  $routeData
     * @param mixed  $handler
     */
    public function addRoute($httpMethod, $routeData, $handler)
    {
        $this->wrappedGenerator->addRoute($httpMethod, $routeData, $handler);
    }

    /**
     * Returns dispatcher data in some unspecified format, which
     * depends on the used method of dispatch.
     */
    public function getData()
    {
        return $this->wrappedGenerator->getData();
    }

    /**
     * Adds a named route to the data generator
     *
     * The handler doesn't necessarily need to be a callable, it
     * can be arbitrary data that will be returned when the route
     * matches.
     *
     * @param string $name
     * @param string $httpMethod
     * @param array  $routeData
     * @param mixed  $handler
     *
     * @return void
     */
    public function addNamedRoute($name, $httpMethod, $routeData, $handler)
    {
        $handler = array(
            'name' => $name,
            'handler' => $handler,
        );

        $this->addRoute($httpMethod, $routeData, $handler);
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Router\RouteCollector;

use Nice\Router\RouteCollectorInterface;
use Symfony\Component\Config\ConfigCache;

/**
 * A cached RouteCollector that wraps another RouteCollector
 */
class CachedCollector implements RouteCollectorInterface
{
    /**
     * @var RouteCollectorInterface
     */
    private $wrappedCollector;

    /**
     * @var string
     */
    private $cacheFile;

    /**
     * @var bool
     */
    private $debug;

    /**
     * Constructor
     *
     * @param RouteCollectorInterface $wrappedCollector
     * @param string                  $cacheFile
     * @param bool                    $debug
     */
    public function __construct(RouteCollectorInterface $wrappedCollector, $cacheFile, $debug = false)
    {
        $this->wrappedCollector = $wrappedCollector;
        $this->cacheFile = $cacheFile;
        $this->debug = $debug;
    }

    /**
     * Returns the collected route data
     *
     * @return array
     */
    public function getData()
    {
        $cache = new ConfigCache($this->cacheFile, $this->debug);
        if (!$cache->isFresh()) {
            $routes = $this->wrappedCollector->getData();

            // TODO: This seems a fragile way to handle this
            if (!$this->isCacheable($routes)) {
                return $routes;
            }

            $cache->write('<?php return '.var_export($routes, true).';');
        }

        return require $cache;
    }

    /**
     * Ensures route data does not contain any Closures
     *
     * @return bool
     */
    private function isCacheable($data)
    {
        $cacheable = true;
        array_walk_recursive($data, function ($value) use (&$cacheable) {
                if ($value instanceof \Closure) {
                    $cacheable = false;
                }
            });

        return $cacheable;
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Router;

use FastRoute\DataGenerator;
use FastRoute\RouteParser;

/**
 * A base class for any RouteCollector
 *
 * This class is based on FastRoute\RouteCollector
 */
abstract class RouteCollector implements RouteCollectorInterface, RouteMapperInterface
{
    /**
     * @var RouteParser
     */
    private $routeParser;

    /**
     * @var DataGenerator
     */
    private $dataGenerator;

    /**
     * @var bool
     */
    private $collected = false;

    /**
     * Constructor
     *
     * @param RouteParser   $routeParser
     * @param DataGenerator $dataGenerator
     */
    public function __construct(RouteParser $routeParser, DataGenerator $dataGenerator)
    {
        $this->routeParser   = $routeParser;
        $this->dataGenerator = $dataGenerator;
    }

    /**
     * Returns the collected route data
     *
     * @return array
     */
    public function getData()
    {
        if (!$this->collected) {
            $this->collectRoutes();

            $this->collected = true;
        }

        return $this->dataGenerator->getData();
    }

    /**
     * Map a handler to the given methods and route
     *
     * @param string          $route   The route to match against
     * @param string          $name    The name of the route
     * @param string|callable $handler The handler for the route
     * @param array|string[]  $methods The HTTP methods for this handler
     */
    public function map($route, $name, $handler, array $methods = array('GET'))
    {
        foreach ($methods as $method) {
            if (null === $name) {
                $this->addRoute($method, $route, $handler);
            } else {
                $this->addNamedRoute($name, $method, $route, $handler);
            }
        }
    }

    /**
     * Add an un-named route to the collection
     *
     * @param string $httpMethod
     * @param string $route
     * @param mixed  $handler
     */
    private function addRoute($httpMethod, $route, $handler)
    {
        $routeData = $this->routeParser->parse($route);

        foreach ($routeData as $routeDatum) {
            $this->dataGenerator->addRoute($httpMethod, $routeDatum, $handler);
        }
    }

    /**
     * Add a named route to the collection
     *
     * @param string $name
     * @param string $httpMethod
     * @param string $route
     * @param mixed  $handler
     *
     * @throws \RuntimeException
     */
    private function addNamedRoute($name, $httpMethod, $route, $handler)
    {
        if (! ($this->dataGenerator instanceof NamedDataGeneratorInterface)) {
            throw new \RuntimeException('The injected generator does not support named routes');
        }

        $routeData = $this->routeParser->parse($route);

        foreach ($routeData as $routeDatum) {
            $this->dataGenerator->addNamedRoute($name, $httpMethod, $routeDatum, $handler);
        }
    }

    /**
     * Perform any collection
     *
     * @return void
     */
    abstract protected function collectRoutes();
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Extension;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Extension\Extension;

/**
 * Sets up routing related services
 */
class RouterExtension extends Extension
{
    /**
     * Loads a specific configuration.
     *
     * @param array            $config    An array of configuration values
     * @param ContainerBuilder $container A ContainerBuilder instance
     */
    public function load(array $config, ContainerBuilder $container)
    {
        $container->register('router.parser', 'FastRoute\RouteParser\Std');
        $container->register('router.data_generator.strategy', 'FastRoute\DataGenerator\GroupCountBased');
        $container->register('router.data_generator', 'Nice\Router\NamedDataGenerator\HandlerWrapperGenerator')
            ->addArgument(new Reference('router.data_generator.strategy'));

        $container->setParameter('router.collector.class', 'Nice\Router\RouteCollector\SimpleCollector');

        $container->register('routes', 'Closure')
            ->setSynthetic(true);

        $container->register('router.collector', '%router.collector.class%')
            ->addArgument(new Reference('router.parser'))
            ->addArgument(new Reference('router.data_generator'))
            ->addArgument(new Reference('routes'));

        $container->register('router.dispatcher_factory', 'Nice\Router\DispatcherFactory\GroupCountBasedFactory')
            ->addArgument(new Reference('router.collector'));

        $container->register('router.dispatcher', 'FastRoute\Dispatcher')
            ->setFactoryService('router.dispatcher_factory')
            ->setFactoryMethod('create');

        $container->register('router.dispatcher_subscriber', 'Nice\Router\RouterSubscriber')
            ->addArgument(new Reference('router.dispatcher'))
            ->addTag('kernel.event_subscriber');

        $container->register('router.wrapped_handler_subscriber', 'Nice\Router\WrappedHandlerSubscriber')
            ->addTag('kernel.event_subscriber');

        $container->register('router.controller_resolver', 'Nice\Router\ContainerAwareControllerResolver')
            ->addMethodCall('setContainer', array(new Reference('service_container')));

        $container->register('router.url_generator.data_generator', 'Nice\Router\UrlGenerator\GroupCountBasedDataGenerator')
            ->addArgument(new Reference('router.collector'));

        $container->register('router.url_generator', 'Nice\Router\UrlGenerator\SimpleUrlGenerator')
            ->addArgument(new Reference('router.url_generator.data_generator'))
            ->addMethodCall('setRequest', array(new Reference(
                    'request',
                    ContainerInterface::NULL_ON_INVALID_REFERENCE,
                    false
                )));

        $container->register('http_kernel', 'Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel')
            ->addArgument(new Reference('event_dispatcher'))
            ->addArgument(new Reference('service_container'))
            ->addArgument(new Reference('router.controller_resolver'));
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Router;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;

/**
 * Extends the basic ControllerResolver to support ContainerAware controllers and controllers as services
 */
class ContainerAwareControllerResolver extends ControllerResolver implements ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * Sets the Container.
     *
     * @param ContainerInterface|null $container A ContainerInterface instance or null
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * Returns a callable for the given controller.
     *
     * @param string $controller A Controller string
     *
     * @return callable
     */
    protected function createController($controller)
    {
        $parts = explode(':', $controller);
        if (count($parts) === 2) {
            $service = $this->container->get($parts[0]);

            return array($service, $parts[1]);
        }

        $controller = parent::createController($controller);
        if ($controller[0] instanceof ContainerAwareInterface) {
            $controller[0]->setContainer($this->container);
        }

        return $controller;
    }
}


<?php
/**
 * ServiceProviderMiddleware
 *
 * PHP version 7+
 *
 * Copyright (c) 2016 Federico Lozada Mosto <mosto.federico@gmail.com>
 * For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
 *
 * @category  Resty
 * @package   Resty\Interfaces
 * @author    Federico Lozada Mosto <mosto.federico@gmail.com>
 * @copyright 2016 Federico Lozada Mosto <mosto.federico@gmail.com>
 * @license   MIT License (http://www.opensource.org/licenses/mit-license.php)
 * @link      http://www.mostofreddy.com.ar
 */
namespace Resty\Slim;

use Slim\Container;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
 * ServiceProviderMiddleware
 *
 * @category  Resty
 * @package   Resty\Interfaces
 * @author    Federico Lozada Mosto <mosto.federico@gmail.com>
 * @copyright 2016 Federico Lozada Mosto <mosto.federico@gmail.com>
 * @license   MIT License (http://www.opensource.org/licenses/mit-license.php)
 * @link      http://www.mostofreddy.com.ar
 */
class ServiceProviderMiddleware
{
    protected $container;

    /**
     * Contructor
     *
     * @param Container $container Instancia de Container
     */
    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * Middleware
     *
     * @param \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
     * @param \Psr\Http\Message\ResponseInterface      $response PSR7 response
     * @param callable                                 $next     Next middleware
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next):ResponseInterface
    {
        $this->setProviders();

        $response = $next($request, $response);

        return $response;
    }

    /**
     * Inicializa y registra todos los providers
     *
     * @return void
     */
    public function setProviders()
    {
        $services = $this->container['services']??null;

        if (is_array($services)) {
            foreach ($services as $service) {
                $service::register($this->container);
                $service::boot($this->container);
            }
        }
    }
}


<?php

namespace SSD\StringConverter\Types;

use SSD\StringConverter\{
    RegEx, Converter
};

class Space extends Converter implements Contract
{
    /**
     * Convert to space format.
     * Call optional function on callback.
     *
     * @param  \SSD\StringConverter\Types\Contract $contract
     * @param  string $string
     * @param  callable|null $callback
     * @return string
     */
    public function from(Contract $contract, string $string, callable $callback = null): string
    {
        return $this->callback(
            trim($contract->recipe($string, 'space')),
            $callback
        );
    }

    /**
     * Conversion recipe.
     *
     * @param  string $string
     * @param  string $method
     * @param  callable|null $callback
     * @return mixed
     */
    public function recipe(string $string, string $method, callable $callback = null): string
    {
        return preg_replace_callback(
            RegEx::REGEX_SPACE,
            [$this, $method],
            $this->callback($string, $callback)
        );
    }
}


<?php
namespace Keboola\Orchestrator;

class OrchestrationTask
{
	private $component;

	private $componentUrl;

	private $action;

	private $actionParameters = array();

	private $continueOnFailure = false;

	private $active = true;

	private $timeoutMinutes;

	private $phase;

	public function __construct()
	{

	}

	/**
	 * Set component name
	 *
	 * List of available components http://docs.keboola.apiary.io/#get-%2Fv2%2Fstorage%2Fcomponents
	 *
	 * @param string $value
	 * @return $this
	 */
	public function setComponent($value)
	{
		$this->component = (string) $value;
		return $this;
	}

	/**
	 * Get component name
	 *
	 * @return null|string
	 */
	public function getComponent()
	{
		return $this->component;
	}

	/**
	 * Set component url
	 *
	 * @param string $value
	 * @return $this
	 */
	public function setComponentUrl($value)
	{
		$this->componentUrl = (string) $value;
		return $this;
	}

	/**
	 * Get component url
	 *
	 * @return null|string
	 */
	public function getComponentUrl()
	{
		return $this->componentUrl;
	}

	/**
	 * Set component action to run
	 *
	 * @param string $value
	 * @return $this
	 */
	public function setAction($value)
	{
		$this->action = (string) $value;
		return $this;
	}

	/**
	 * Get component action to run
	 *
	 * @return null|string
	 */
	public function getAction()
	{
		return $this->action;
	}

	/**
	 * Set action parameters
	 *
	 * Specify action parameters as associative array
	 *
	 * @param array $value
	 * @return $this
	 */
	public function setActionParameters(array $value)
	{
		$this->actionParameters = $value;
		return $this;
	}

	/**
	 * Get action parameters
	 *
	 * @return mixed
	 */
	public function getActionParameters()
	{
		return $this->actionParameters;
	}

	/**
	 * Set continue on failure
	 *
	 * @param bool $value
	 * @return $this
	 */
	public function setContinueOnFailure($value = true)
	{
		$this->continueOnFailure = (bool) $value;
		return $this;
	}

	/**
	 * Get continue on failure
	 *
	 * @return bool
	 */
	public function getContinueOnFailure()
	{
		return $this->continueOnFailure;
	}

	/**
	 * Set active
	 *
	 * @param bool $value
	 * @return $this
	 */
	public function setActive($value = true)
	{
		$this->active = (bool) $value;
		return $this;
	}

	/**
	 * Get active
	 *
	 * @return bool
	 */
	public function getActive()
	{
		return $this->active;
	}

	/**
	 * Set task timeout in minutes
	 *
	 * @param int $value
	 * @return $this
	 */
	public function setTimeoutMinutes($value)
	{
		if ($value)
			$this->timeoutMinutes = (int) $value;
		else
			$this->timeoutMinutes = null;
		return $this;
	}

	/**
	 * Get task timeout in minutes
	 *
	 * @return null|int
	 */
	public function getTimeoutMinutes()
	{
		return $this->timeoutMinutes;
	}

	/**
	 * Set task phase
	 *
	 * @param int $value
	 * @return $this
	 */
	public function setPhase($value)
	{
		$value = (int) $value;
		if ($value)
			$this->phase = $value;
		else
			$this->phase = null;

		return $this;
	}

	/**
	 * Get task phase
	 *
	 * @return null|int
	 */
	public function getPhase()
	{
		return $this->phase;
	}

	/**
	 * @return array
	 */
	public function toArray()
	{
		return array(
			'component' => $this->getComponent(),
			'componentUrl' => $this->getComponentUrl(),
			'action' => $this->getAction(),
			'actionParameters' => $this->getActionParameters(),
			'continueOnFailure' => $this->getContinueOnFailure(),
			'active' => $this->getActive(),
			'timeoutMinutes' => $this->getTimeoutMinutes(),
			'phase' => $this->getPhase(),
		);
	}
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\DependencyInjection\ConfigurationProvider;

use Nice\DependencyInjection\ConfigurationProviderInterface;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\DelegatingLoader;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

/**
 * A ConfigurationProvider that can load from file-based sources.
 */
class FileConfigurationProvider implements ConfigurationProviderInterface
{
    /**
     * @var string
     */
    protected $configDir;

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

    /**
     * Constructor
     *
     * @param string $configFile
     */
    public function __construct($configFile)
    {
        $this->configDir = dirname($configFile);
        $this->configFile = basename($configFile);
    }

    /**
     * Load the given ContainerBuilder with its configuration.
     *
     * @param ContainerBuilder $container
     *
     * @return void
     */
    public function load(ContainerBuilder $container)
    {
        $loader = $this->getContainerLoader($container);

        $loader->load($this->configFile);
    }

    /**
     * Returns a loader for the container.
     *
     * This loader can be used to load extension configurations from various sources.
     *
     * @param ContainerInterface $container The service container
     *
     * @return LoaderInterface
     */
    protected function getContainerLoader(ContainerInterface $container)
    {
        $locator = new FileLocator($this->configDir);
        $resolver = new LoaderResolver(array(
            new XmlFileLoader($container, $locator),
            new YamlFileLoader($container, $locator),
            new IniFileLoader($container, $locator),
            new PhpFileLoader($container, $locator),
        ));

        return new DelegatingLoader($resolver);
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\DependencyInjection\ContainerInitializer;

use Nice\Application;
use Nice\DependencyInjection\CompilerAwareExtensionInterface;
use Nice\DependencyInjection\ConfigurationProviderInterface;
use Nice\DependencyInjection\ContainerInitializerInterface;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Scope;
use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
use Symfony\Component\HttpKernel\DependencyInjection\RegisterListenersPass;

/**
 * Creates and initializes a Service Container, ready for use by the Application
 */
class DefaultInitializer implements ContainerInitializerInterface
{
    /**
     * @var ConfigurationProviderInterface
     */
    private $configProvider;

    /**
     * Constructor
     *
     * @param ConfigurationProviderInterface $configProvider
     */
    public function __construct(ConfigurationProviderInterface $configProvider)
    {
        $this->configProvider = $configProvider;
    }

    /**
     * Returns a fully built, ready to use Container
     *
     * @param Application                   $application
     * @param array|ExtensionInterface[]    $extensions
     * @param array|CompilerPassInterface[] $compilerPasses
     *
     * @return ContainerInterface
     */
    public function initializeContainer(Application $application, array $extensions = array(), array $compilerPasses = array())
    {
        $container = $this->getContainerBuilder();
        $container->addObjectResource($application);
        $container->setParameter('app.env', $application->getEnvironment());
        $container->setParameter('app.debug', $application->isDebug());
        $container->setParameter('app.cache', $application->isCacheEnabled());
        $container->setParameter('app.root_dir', $application->getRootDir());
        $container->setParameter('app.cache_dir', $application->getCacheDir());
        $container->setParameter('app.log_dir', $application->getLogDir());

        $container->register('event_dispatcher', 'Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher')
            ->setArguments(array(new Reference('service_container')));

        $container->register('app', 'Symfony\Component\HttpKernel\HttpKernelInterface')
            ->setSynthetic(true);

        $container->register('request', 'Symfony\Componenet\HttpKernel\Request')
            ->setSynthetic(true)
            ->setSynchronized(true)
            ->setScope('request');

        $container->addScope(new Scope('request'));

        $extensionAliases = array();
        foreach ($extensions as $extension) {
            $container->registerExtension($extension);
            $extensionAliases[] = $extension->getAlias();

            if ($extension instanceof CompilerAwareExtensionInterface) {
                $passes = $extension->getCompilerPasses();
                if (!is_array($passes)) {
                    $passes = array($passes);
                }

                $compilerPasses = array_merge($compilerPasses, $passes);
            }
        }

        $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensionAliases));
        $container->addCompilerPass(new RegisterListenersPass());

        foreach ($compilerPasses as $pass) {
            if (is_array($pass)) {
                $container->addCompilerPass($pass[0], $pass[1]);
            } else {
                $container->addCompilerPass($pass);
            }
        }

        $this->configProvider->load($container);

        $container->compile();

        return $container;
    }

    /**
     * Gets a new ContainerBuilder instance used to build the service container.
     *
     * @return ContainerBuilder
     */
    protected function getContainerBuilder()
    {
        return new ContainerBuilder();
    }
}


<?php

/*
 * Copyright (c) Tyler Sommer
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

namespace Nice\Extension;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Sets up Logging related services
 */
class LogExtension extends Extension
{
    /**
     * @var array
     */
    private $options = array();

    /**
     * Constructor
     *
     * @param array $options
     */
    public function __construct(array $options = array())
    {
        $this->options = $options;
    }

    /**
     * Returns extension configuration
     *
     * @param array            $config    An array of configuration values
     * @param ContainerBuilder $container A ContainerBuilder instance
     *
     * @return LogConfiguration
     */
    public function getConfiguration(array $config, ContainerBuilder $container)
    {
        return new LogConfiguration();
    }

    /**
     * Loads a specific configuration.
     *
     * @param array            $configs   An array of configuration values
     * @param ContainerBuilder $container A ContainerBuilder instance
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configs[] = $this->options;
        $configuration = $this->getConfiguration($configs, $container);
        $config = $this->processConfiguration($configuration, $configs);

        foreach ($config['channels'] as $name => $channelConfig) {
            $channelConfig['name'] = $name;
            switch ($channelConfig['handler']) {
                case 'stream':
                    $this->configureStreamChannel($channelConfig, $container);

                    break;

                case 'error_log':
                    $this->configureErrorLogChannel($channelConfig, $container);

                    break;
            }
        }
    }

    private function configureStreamChannel(array $channelConfig, ContainerBuilder $container)
    {
        $options = $channelConfig['options'];

        if (!isset($options['file'])) {
            throw new \RuntimeException('The option "file" must be specified for the stream handler.');
        }

        $name = $channelConfig['name'];
        $level = (int) $channelConfig['level'];
        $file = $options['file'];

        $loggerService = 'logger.'.$name;
        $handlerService = 'logger.'.$name.'.handler';

        $container->register($handlerService)
            ->setClass('Monolog\Handler\StreamHandler')
            ->addArgument($file)
            ->addArgument($level);

        $container->register($loggerService)
            ->setClass('Monolog\Logger')
            ->addArgument($name)
            ->addMethodCall('pushHandler', array(new Reference($handlerService)));
    }

    private function configureErrorLogChannel(array $channelConfig, ContainerBuilder $container)
    {
        $name = $channelConfig['name'];
        $level = (int) $channelConfig['level'];

        $loggerService = 'logger.'.$name;
        $handlerService = 'logger.'.$name.'.handler';

        $container->register($handlerService)
            ->setClass('Monolog\Handler\ErrorLogHandler')
            ->addArgument(0)
            ->addArgument($level);

        $container->register($loggerService)
            ->setClass('Monolog\Logger')
            ->addArgument($name)
            ->addMethodCall('pushHandler', array(new Reference($handlerService)));
    }
}


<?php
/**
 * @link http://www.tintsoft.com/
 * @copyright Copyright (c) 2012 TintSoft Technology Co. Ltd.
 * @license http://www.tintsoft.com/license/
 */

namespace xutl\snowflake;

use Yii;
use yii\base\Component;
use yii\base\Exception;

/**
 * Class Snowflake
 * @package xutl\snowflake
 */
class Snowflake extends Component
{
    /**
     * @var int 开始时间截
     */
    public $epoch = 1414213562373;

    /**
     * @var int 工作机器ID(0~31)
     */
    public $workerId;

    /**
     * @var int 数据中心ID(0~31)
     */
    public $dataCenterId;

    /**
     * @var int 上次生成ID的时间截
     */
    private $_lastTimestamp;

    /**
     * @var int 毫秒内序列(0~4095)
     */
    private $_sequence = 0;

    const WORKER_BITS = 5;
    const DATA_CENTER_BITS = 5;
    const MAX_WORKER_ID = (-1 ^ (-1 << self::WORKER_BITS));
    const MAX_DATA_CENTER_ID = (-1 ^ (-1 << self::DATA_CENTER_BITS));
    const SEQUENCE_BITS = 12;
    const WORKER_ID_SHIFT = self::SEQUENCE_BITS;
    const DATA_CENTER_ID_SHIFT = self::SEQUENCE_BITS + self::WORKER_BITS;
    const TIMESTAMP_LEFT_SHIFT = self::SEQUENCE_BITS + self::WORKER_BITS + self::DATA_CENTER_BITS;
    const SEQUENCE_MASK = (-1 ^ (-1 << self::SEQUENCE_BITS));

    /**
     * 初始化
     * @throws Exception
     */
    public function init()
    {
        parent::init();
        if ($this->workerId > self::MAX_WORKER_ID || $this->workerId < 0) {
            throw new Exception(sprintf("worker Id can't be greater than %d or less than 0",self::MAX_WORKER_ID));
        }
        if ($this->dataCenterId > self::MAX_DATA_CENTER_ID || $this->dataCenterId < 0) {
            throw new Exception(sprintf("dataCenterId can't be greater than %d or less than 0",self::MAX_DATA_CENTER_ID));
        }
    }

    /**
     * 获得下一个ID (该方法是线程安全的)
     * @return int
     * @throws Exception
     */
    public function next()
    {
        $timestamp = $this->milliTime();
        if ($timestamp < $this->_lastTimestamp) {
            throw new Exception(sprintf("Clock moved backwards.  Refusing to generate id for %d milliseconds", $this->_lastTimestamp - $timestamp));
        }

        if ($this->_lastTimestamp == $timestamp) {
            $this->_sequence = ($this->_sequence + 1) & self::SEQUENCE_MASK;
            if ($this->_sequence == 0) {
                $timestamp = $this->waitNextMilli($this->_lastTimestamp);
            }
        } else {
            $this->_sequence = 0;
        }
        $this->_lastTimestamp = $timestamp;
        return (($timestamp - $this->epoch) << self::TIMESTAMP_LEFT_SHIFT)
            | ($this->dataCenterId << self::DATA_CENTER_ID_SHIFT)
            | ($this->workerId << self::WORKER_ID_SHIFT)
            | $this->_sequence;
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     * @param int $lastTimestamp 上次生成ID的时间截
     * @return int 当前时间戳
     */
    protected function waitNextMilli($lastTimestamp)
    {
        $timestamp = $this->milliTime();
        while ($timestamp <= $lastTimestamp) {
            $timestamp = $this->milliTime();
        }
        return $timestamp;
    }

    /**
     * 返回以毫秒为单位的当前时间
     * @return int 当前时间(毫秒)
     */
    protected function milliTime()
    {
        $microTime = microtime();
        $comps = explode(' ', $microTime);
        // Note: Using a string here to prevent loss of precision
        // in case of "overflow" (PHP converts it to a double)
        return sprintf('%d%03d', $comps[1], $comps[0] * 1000);
    }
}


<?php

namespace Germanazo\CkanApi\Repositories;

use GuzzleHttp\Client;
use Germanazo\CkanApi\Traits\RestApiTrait;
use Psr\Http\Message\ResponseInterface;

class BaseRepository
{
    use RestApiTrait;

    /**
     * URI Api endpoint
     * @var string
     */
    protected $action_name = '';

    /**
     * Per page, paginated results
     *
     * @var int
     */
    protected $per_page = 15;

    /**
     * @var Client
     */
    protected $client;

    /**
     * Standard Ckan HTTP status codes are used to signal method outcomes.
     *
     * @var array
     */
    protected $status_codes = [
        200 => 'Ok',
        201 => 'OK and new object created (referred to in the Location header)',
        301 => 'Moved Permanently',
        400 => 'Bad Request',
        403 => 'Not Authorized',
        404 => 'Not Found',
        409 => 'Conflict (e.g. name already exists)',
        500 => 'Service Error',
    ];

    /**
     * BaseRepository constructor.
     *
     * @param Client $client
     */
    public function __construct(Client $client)
    {
        $this->per_page = config('ckan_api.repositories.per_page', $this->per_page);

        $this->setUri("action/{$this->action_name}_{{METHOD}}");

        $this->client = $client;
    }

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

    /**
     * Set current uri to use for api calls
     *
     * @param string $uriToSet
     */
    protected function setUri($uriToSet)
    {
        $uri_parts = [];

        array_push($uri_parts, 'api');
        array_push($uri_parts, config('ckan_api.api_version'));
        array_push($uri_parts, trim($uriToSet, '/'));

        $uri_parts = array_filter($uri_parts);

        $this->uri = implode('/', $uri_parts);
    }

    /**
     * Convert response to json
     *
     * @param ResponseInterface $response
     * @return mixed
     */
    protected function responseToJson(ResponseInterface $response)
    {
        return json_decode((string) $response->getBody(), true);
    }

    /**
     * Converts data to multipart option for guzzle
     *
     * @param array $data
     * @return array
     */
    protected function dataToMultipart(array $data = [])
    {
        $multipart = [];

        foreach($data as $name => $contents) {
            array_push($multipart, ['name' => $name, 'contents' => $contents]);
        }

        return $multipart;
    }

}


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ApiBundle\Service;

use Elasticsearch\Common\Exceptions\NoDocumentsToGetException;
use ONGR\ElasticsearchBundle\Result\Result;
use ONGR\ElasticsearchBundle\Service\Repository;
use ONGR\ElasticsearchDSL\Query\IdsQuery;
use ONGR\ElasticsearchDSL\Query\MatchAllQuery;

/**
 * Simple CRUD operations service.
 */
class Crud implements CrudInterface
{
    /**
     * {@inheritdoc}
     */
    public function create(Repository $repository, array $data)
    {
        if (!empty($data['_id']) && $this->read($repository, $data['_id'])) {
            throw new \RuntimeException('The resource existed.');
        }

        $repository->getManager()->bulk('create', $repository->getType(), $data);
    }

    /**
     * {@inheritdoc}
     */
    public function read(Repository $repository, $id)
    {
        $search = $repository->createSearch();
        $search->addQuery(new IdsQuery([$id]));
        $search->setSize(1);

        $results = $repository->execute($search, Result::RESULTS_ARRAY);

        if (!isset($results[0])) {
            return null;
        }

        return $results[0];
    }

    /**
     * {@inheritdoc}
     */
    public function update(Repository $repository, $id, array $data)
    {
        $repository->getManager()->bulk(
            'update',
            $repository->getType(),
            [
                '_id' => $id,
                'doc' => $data,
                'doc_as_upsert' => true
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function delete(Repository $repository, $id)
    {
        if (!$id) {
            throw new \RuntimeException('Missing _id field for update operations.');
        }

        if (!$this->read($repository, $id)) {
            throw new NoDocumentsToGetException("Identifier not found!");
        }

        $repository->getManager()->bulk('delete', $repository->getType(), ['_id' => $id]);
    }

    /**
     * {@inheritdoc}
     */
    public function commit(Repository $repository)
    {
        return $repository->getManager()->commit();
    }

    /**
     * {@inheritdoc}
     */
    public function readAll(Repository $repository, array $parameters = [])
    {
        $search = $repository->createSearch();
        $search->addQuery(new MatchAllQuery());

        if (isset($parameters['size'])) {
            $search->setSize($parameters['size']);
        }
        if (isset($parameters['from'])) {
            $search->setFrom($parameters['from']);
        }

        $results = $repository->execute($search, Result::RESULTS_ARRAY);

        if (!isset($results[0])) {
            return null;
        }

        return $results;
    }
}


<?php
/**
 * zf2-cron-helper
 *
 * @link https://github.com/ondrejd/zf2-cron-helper for the canonical source repository
 * @copyright Copyright (c) 2015 Ondřej Doněk.
 * @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License 2.0
 */

namespace CronHelper;

use Zend\Console\Adapter\AdapterInterface as Console;
use Zend\Db\Adapter\Adapter as DbAdapter;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
use Zend\ModuleManager\Feature\ConsoleBannerProviderInterface;
use Zend\ModuleManager\Feature\ConsoleUsageProviderInterface;
use Zend\Mvc\MvcEvent;
use CronHelper\Service\CronService;

/**
 * CronHelper module.
 *
 * @package CronHelper
 */
class Module implements AutoloaderProviderInterface,
	ConfigProviderInterface, ServiceProviderInterface,
	ConsoleBannerProviderInterface, ConsoleUsageProviderInterface
{
	/**
	 * @var string The module's namespace
	 */
	const NS = __NAMESPACE__;

	/**
	 * @var string The module's base path
	 */
	const BASE_PATH = __DIR__;

	/**
	 * @var string
	 */
	const CONSOLE_BANNER = 'ondrejd/zf2-cron-helper 0.1';

	/**
	 * Retrieve autoloader configuration for this module
	 *
	 * @return array
	 */
	public function getAutoloaderConfig()
	{
		return array(
			'Zend\Loader\ClassMapAutoloader' => array(
				self::BASE_PATH . '/autoload_classmap.php',
			),
			'Zend\Loader\StandardAutoloader' => array(
				'namespaces' => array(
					self::NS => self::BASE_PATH . '/src/' . self::NS,
				)
			),
		);
	}

	/**
	 * Retrieve configuration for this module
	 *
	 * @return array
	 */
	public function getConfig()
	{
		return include self::BASE_PATH . '/config/module.config.php';
	}

	/**
	 * Returns console banner.
	 *
	 * @param Console $console
	 * @return string
	 */
	public function getConsoleBanner(Console $console)
	{
		return self::CONSOLE_BANNER;
	}

	/**
	 * Provide console usage messages for console endpoints
	 *
	 * @return array
	 */
	public function getConsoleUsage(Console $console)
	{
		return array(
			'Main commands',
			'cron' => 'Main command which should be added into the crontab',
			'[info|status]' => 'Print info about current CronHelper status',
			'Database-related commands',
			'db create' => 'Create storage for cron-helper',
			'db clear' => 'Clear all data in cron-helper storage',
			'db destroy' => 'Destroy cron-helper storage'
		);
	}

	/**
	 * Retrieve configuration for the service manager
	 *
	 * @return array
	 */
	public function getServiceConfig()
	{
		return array(
			'factories' => array(
				'CronHelper\Service\CronService' => function ($serviceManager) {
					$mainConfig = $serviceManager->get('config');
					$serviceConfig = array();

					if (is_array($mainConfig)) {
						if (array_key_exists('cron_helper', $mainConfig)) {
							$serviceConfig = $mainConfig['cron_helper'];
						}
					}

					$cronService = new CronService($serviceConfig);
					return $cronService;
				},
			),
		);
	}

	/**
	 * On bootstrap.
	 *
	 * @param MvcEvent $event
	 * @return void
	 */
	public function onBootstrap(MvcEvent $event)
	{
		$eventManager = $event->getApplication()->getEventManager();
		$sharedEventManager = $eventManager->getSharedManager();

		//$sharedEventManager->attach('CronHelper\Service\CronService', function($aEvent) {
		//	var_dump($aEvent);
		//}, 100);
	}
}


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ApiBundle\Service;

use ONGR\ElasticsearchBundle\Service\Repository;
use ONGR\ElasticsearchBundle\Service\Manager;
use Symfony\Component\HttpFoundation\Request;

class FieldValidator
{
    /**
     * @var Manager
     */
    private $manager;

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

    /**
     * FieldValidator constructor.
     * @param Manager $manager
     * @param array $versions
     */
    public function __construct(Manager $manager, array $versions)
    {
        $this->manager = $manager;
        $this->versions = $versions;
    }

    /**
     * Validates fields if the allow_extra_fields property
     * is false or allow_fields are set
     *
     * @param Request    $request
     * @param Repository $repository
     * @param array      $data
     *
     * @return array
     */
    public function validateFields(Request $request, Repository $repository, $data)
    {
        $config = [];
        $validation = [];
        foreach ($this->versions as $version) {
            foreach ($version['endpoints'] as $endpoint) {
                if ($endpoint['repository'] == $request->attributes->get('repository')) {
                    $config = $endpoint;
                    break;
                }
            }
            if ($config != []) {
                break;
            }
        }
        if (!$config['allow_extra_fields'] || $config['allow_fields']) {
            $mapping = $this->manager->getMetadataCollector()->getMapping(
                $repository->getClassName()
            );
            $forbiddenFields = $mapping['properties'];
            if ($config['allow_fields']) {
                foreach ($config['allow_fields'] as $field) {
                    unset($forbiddenFields[$field]);
                }
            }
            foreach ($data as $parameter => $value) {
                if (!array_key_exists($parameter, $mapping['properties']) && $parameter != '_id') {
                    $validation['message'] = sprintf(
                        'Property `%s` does not exist in the mapping of `%s`.',
                        $parameter,
                        $repository->getType()
                    );
                    return $validation;
                }
                if ($config['allow_fields'] && array_key_exists($parameter, $forbiddenFields)) {
                    $validation['message'] = sprintf(
                        'You are not allowed to insert or modify the field `%s` in `%s`',
                        $parameter,
                        $repository->getType()
                    );
                    return $validation;
                }
            }
        }
        return $validation;
    }
}


<?php

/*
 * This file is part of the ONGR package.
 *
 * (c) NFQ Technologies UAB <info@nfq.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ONGR\ApiBundle\Controller;

use ONGR\ApiBundle\Service\Crud;
use ONGR\ElasticsearchBundle\Service\Repository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Abstraction for rest api controller.
 */
class AbstractRestController extends Controller
{
    /**
     * Get CRUD Service
     *
     * @return Crud
     */
    public function getCrudService()
    {
        return $this->get('ongr_api.crud');
    }

    /**
     * Renders rest response.
     *
     * @param Request $request
     * @param string  $data
     * @param int     $statusCode
     * @param array   $headers
     *
     * @return Response|array
     */
    public function renderRest(
        $request,
        $data,
        $statusCode = Response::HTTP_OK,
        $headers = []
    ) {
        $requestSerializer = $this->get('ongr_api.request_serializer');

        return new Response(
            $requestSerializer->serializeRequest($request, $data),
            $statusCode,
            array_merge(
                ['Content-Type' => 'application/' . $requestSerializer->checkAcceptHeader($request)],
                $headers
            )
        );
    }

    /**
     * Error Response
     *
     * @param Request $request
     * @param string  $message
     * @param int     $statusCode
     *
     * @return Response
     */
    public function renderError(
        $request,
        $message,
        $statusCode = Response::HTTP_BAD_REQUEST
    ) {
        $response = [
            'errors' => [],
            'message' => $message,
            'code' => $statusCode
        ];

        return $this->renderRest($request, $response, $statusCode);
    }

    /**
     * Returns repository object from it's identifier in request.
     *
     * @param Request $request
     *
     * @return Repository
     */
    protected function getRequestRepository(Request $request)
    {
        return $this->get($request->attributes->get('repository'));
    }
}