Skip to content

Commit

Permalink
Merge pull request #23 from codeburnerframework/dev
Browse files Browse the repository at this point in the history
pull minor features and patchs
  • Loading branch information
Alex Rohleder committed Feb 22, 2016
2 parents 300e850 + 709f371 commit 022ed45
Show file tree
Hide file tree
Showing 9 changed files with 383 additions and 136 deletions.
183 changes: 70 additions & 113 deletions src/Collector.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
* because the routes will not be used until the collector is used.
*/

if (!class_exists(Parser::class, false)) {
include __DIR__ . "/Parser.php";
}

include __DIR__ . "/Route.php";
include __DIR__ . "/Group.php";
include __DIR__ . "/Collectors/ControllerCollectorTrait.php";
Expand All @@ -36,14 +40,6 @@ class Collector
use Collectors\ControllerCollectorTrait;
use Collectors\ResourceCollectorTrait;

/**
* These regex define the structure of a dynamic segment in a pattern.
*
* @var string
*/

const DYNAMIC_REGEX = "{\s*(\w*)\s*(?::\s*([^{}]*(?:{(?-1)}*)*))?\s*}";


/**
* All the supported http methods separated by spaces.
Expand Down Expand Up @@ -73,24 +69,23 @@ class Collector
protected $dynamics = [];

/**
* Some regex wildcards for easily definition of dynamic routes. ps. all keys and values must start with :
* The pattern parser instance.
*
* @var array
* @var Parser
*/

protected $wildcards = [
":uid" => ":uid-[a-zA-Z0-9]",
":slug" => ":[a-z0-9-]",
":string" => ":\w",
":int" => ":\d",
":integer" => ":\d",
":float" => ":[-+]?\d*?[.]?\d",
":double" => ":[-+]?\d*?[.]?\d",
":hex" => ":0[xX][0-9a-fA-F]",
":octal" => ":0[1-7][0-7]",
":bool" => ":1|0|true|false|yes|no",
":boolean" => ":1|0|true|false|yes|no",
];
protected $parser;

/**
* Collector constructor.
*
* @param Parser|null $parser
*/

public function __construct(Parser $parser = null)
{
$this->parser = $parser ?: new Parser;
}

/**
* @param string $method
Expand All @@ -105,8 +100,8 @@ class Collector

public function set($method, $pattern, $action)
{
$method = $this->parseMethod($method);
$patterns = $this->parsePattern($pattern);
$method = $this->getValidMethod($method);
$patterns = $this->parser->parsePattern($pattern);
$group = new Group;

foreach ($patterns as $pattern)
Expand Down Expand Up @@ -205,87 +200,6 @@ public function forget($method, $pattern)
} else unset($this->dynamics[$this->getDynamicIndex($method, $pattern)][$pattern]);
}

/**
* Determine if the http method is valid.
*
* @param string $method
* @throws MethodNotSupportedException
* @return string
*/

protected function parseMethod($method)
{
$method = strtolower($method);

if (strpos(self::HTTP_METHODS, $method) === false) {
throw new MethodNotSupportedException($method);
}

return $method;
}

/**
* Separate routes pattern with optional parts into n new patterns.
*
* @param string $pattern
* @return array
*/

protected function parsePattern($pattern)
{
$withoutClosing = rtrim($pattern, "]");
$closingNumber = strlen($pattern) - strlen($withoutClosing);

$segments = preg_split("~" . self::DYNAMIC_REGEX . "(*SKIP)(*F)|\[~x", $withoutClosing);
$this->parseSegments($segments, $closingNumber, $withoutClosing);

return $this->buildSegments($segments);
}

/**
* Parse all the possible patterns seeking for an incorrect or incompatible pattern.
*
* @param string[] $segments Segments are all the possible patterns made on top of a pattern with optional segments.
* @param int $closingNumber The count of optional segments.
* @param string $withoutClosing The pattern without the closing token of an optional segment. aka: ]
*
* @throws BadRouteException
*/

protected function parseSegments(array $segments, $closingNumber, $withoutClosing)
{
if ($closingNumber !== count($segments) - 1) {
if (preg_match("~" . self::DYNAMIC_REGEX . "(*SKIP)(*F)|\]~x", $withoutClosing)) {
throw new BadRouteException(BadRouteException::OPTIONAL_SEGMENTS_ON_MIDDLE);
} else throw new BadRouteException(BadRouteException::UNCLOSED_OPTIONAL_SEGMENTS);
}
}

/**
* @param string[] $segments
*
* @throws BadRouteException
* @return array
*/

protected function buildSegments(array $segments)
{
$pattern = "";
$patterns = [];
$wildcardTokens = array_keys($this->wildcards);
$wildcardRegex = $this->wildcards;

foreach ($segments as $n => $segment) {
if ($segment === "" && $n !== 0) {
throw new BadRouteException(BadRouteException::EMPTY_OPTIONAL_PARTS);
}

$patterns[] = $pattern .= str_replace($wildcardTokens, $wildcardRegex, $segment);
}

return $patterns;
}

/**
* @param string $method
* @param string $pattern
Expand Down Expand Up @@ -326,16 +240,33 @@ protected function getDynamicIndex($method, $pattern)
return crc32(strtolower($method)) + substr_count($pattern, "/");
}

/**
* Determine if the http method is valid.
*
* @param string $method
*
* @throws MethodNotSupportedException
* @return string
*/

protected function getValidMethod($method)
{
$method = strtolower($method);

if (strpos(self::HTTP_METHODS, $method) === false) {
throw new MethodNotSupportedException($method);
}

return $method;
}

/**
* @return string[]
*/

public function getWildcards()
{
$wildcards = [];
foreach ($this->wildcards as $token => $regex)
$wildcards[substr($token, 1)] = substr($regex, 1);
return $wildcards;
return $this->parser->getWildcards();
}

/**
Expand All @@ -344,7 +275,7 @@ public function getWildcards()

public function getWildcardTokens()
{
return $this->wildcards;
return $this->parser->getWildcardTokens();
}

/**
Expand All @@ -354,7 +285,7 @@ public function getWildcardTokens()

public function getWildcard($wildcard)
{
return isset($this->wildcards[":$wildcard"]) ? substr($this->wildcards[":$wildcard"], 1) : null;
return $this->parser->getWildcard($wildcard);
}

/**
Expand All @@ -366,7 +297,33 @@ public function getWildcard($wildcard)

public function setWildcard($wildcard, $pattern)
{
$this->wildcards[":$wildcard"] = ":$pattern";
$this->parser->setWildcard($wildcard, $pattern);
return $this;
}

/**
* @return Parser
*/

public function getParser()
{
return $this->parser;
}

/**
* @param Parser $parser
*
* @throws \LogicException
* @return self
*/

public function setParser(Parser $parser)
{
if (!empty($this->statics) || !empty($this->dynamics)) {
throw new \LogicException("You can't define a route parser after registering a route.");
}

$this->parser = $parser;
return $this;
}

Expand Down
20 changes: 16 additions & 4 deletions src/Collectors/ControllerCollectorTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@

use Codeburner\Router\Collector;
use Codeburner\Router\Group;
use Codeburner\Router\Parser;
use ReflectionClass;
use ReflectionMethod;
use ReflectionParameter;
use Reflector;

/**
* Methods for enable the collector to make routes from a controller.
Expand All @@ -26,7 +26,20 @@
trait ControllerCollectorTrait
{

abstract public function getWildcards();
/**
* @return Parser
*/

abstract public function getParser();

/**
* @param string $method
* @param string $pattern
* @param callable $action
*
* @return Group
*/

abstract public function set($method, $pattern, $action);

/**
Expand Down Expand Up @@ -128,7 +141,6 @@ protected function collectControllerRoutes(ReflectionClass $controller, array $m
$dynamic = $this->getMethodConstraints($method);
$strategy = $this->getAnnotatedStrategy($method);

/** @var \Codeburner\Router\Route $route */
$route = $this->set($http, "$action$dynamic", [$controller->name, $method->name]);

if ($strategy !== null) {
Expand Down Expand Up @@ -201,7 +213,7 @@ protected function getPathConstraint(ReflectionParameter $parameter, $types)
protected function getParamsConstraint(ReflectionMethod $method)
{
$params = [];
preg_match_all("~\@param\s(" . implode("|", array_keys($this->getWildcards())) . "|\(.+\))\s\\$([a-zA-Z0-1_]+)~i",
preg_match_all("~\@param\s(" . implode("|", array_keys($this->getParser()->getWildcards())) . "|\(.+\))\s\\$([a-zA-Z0-1_]+)~i",
$method->getDocComment(), $types, PREG_SET_ORDER);

foreach ((array) $types as $type) {
Expand Down
15 changes: 10 additions & 5 deletions src/Collectors/ResourceCollectorTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@

namespace Codeburner\Router\Collectors;

use Codeburner\Router\Resource;
/**
* Just a fix to phpstorm parser, as it intends that Resource is
* a datatype of php7 and not a class in router package.
*/

use Codeburner\Router\Resource as RouteResource;

/**
* Methods for enable the collector to be resourceful and make
Expand Down Expand Up @@ -49,15 +54,15 @@ abstract public function set($method, $pattern, $action);
* @param array $options Some options like, "as" to name the route pattern, "only" to
* explicit say that only this routes will be registered, and
* "except" that register all the routes except the indicates.
* @return Resource
* @return RouteResource
*/

public function resource($controller, array $options = array())
{
$name = isset($options["prefix"]) ? $options["prefix"] : "";
$name .= $this->getResourceName($controller, $options);
$actions = $this->getResourceActions($options);
$resource = new Resource;
$resource = new RouteResource;

foreach ($actions as $action => $map) {
$resource->set($this->set($map[0], $this->getResourcePath($action, $map[1], $name, $options), [$controller, $action]));
Expand All @@ -70,12 +75,12 @@ public function resource($controller, array $options = array())
* Collect several resources at same time.
*
* @param array $controllers Several controller names as parameters or an array with all controller names.
* @return Resource
* @return RouteResource
*/

public function resources(array $controllers)
{
$resource = new Resource;
$resource = new RouteResource;
foreach ($controllers as $controller)
$resource->set($this->resource($controller));
return $resource;
Expand Down
Loading

0 comments on commit 022ed45

Please sign in to comment.