Enchacements

- Added more doctype and descriptions on functionality.
- Renamed methods and properties to make better sense.
- Added IRoute interface for easier extendability.
This commit is contained in:
Simon Sessingø
2016-11-20 18:05:57 +01:00
parent 4a48a3fcf9
commit df3acb6605
6 changed files with 140 additions and 70 deletions
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace Pecee\SimpleRouter;
use Pecee\Http\Request;
interface IRoute
{
public function renderRoute(Request $request);
public function loadMiddleware(Request $request, LoadableRoute &$route);
public function getIdentifier();
public function setRequestMethods(array $methods);
public function getRequestMethods();
public function getParent();
public function getGroup();
public function setGroup(RouterGroup $group);
public function setParent(IRoute $parent);
public function setCallback($callback);
public function getCallback();
public function getMethod();
public function getClass();
public function setMethod($method);
public function setMiddleware($middleware);
public function setMiddlewares(array $middlewares);
public function setNamespace($namespace);
public function setDefaultNamespace($namespace);
public function getDefaultNamespace();
public function getMiddlewares();
public function getNamespace();
public function getParameters();
public function setParameters($parameters);
public function setWhere(array $options);
public function setMatch($regex);
public function toArray();
public function setSettings(array $settings);
public function matchRoute(Request $request);
}
+2 -2
View File
@@ -133,7 +133,7 @@ abstract class LoadableRoute extends RouterEntry implements ILoadableRoute
* @param array $values * @param array $values
* @return static * @return static
*/ */
public function merge(array $values) public function setSettings(array $values)
{ {
if (isset($values['as'])) { if (isset($values['as'])) {
$this->setNames((array)$values['as']); $this->setNames((array)$values['as']);
@@ -143,7 +143,7 @@ abstract class LoadableRoute extends RouterEntry implements ILoadableRoute
$this->setUrl($values['prefix'] . $this->getUrl()); $this->setUrl($values['prefix'] . $this->getUrl());
} }
parent::merge($values); parent::setSettings($values);
return $this; return $this;
} }
+41 -46
View File
@@ -4,7 +4,6 @@ namespace Pecee\SimpleRouter;
use Pecee\Handlers\IExceptionHandler; use Pecee\Handlers\IExceptionHandler;
use Pecee\Http\Middleware\BaseCsrfVerifier; use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request; use Pecee\Http\Request;
use Pecee\Http\Response;
use Pecee\SimpleRouter\Exceptions\HttpException; use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException; use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
@@ -12,6 +11,7 @@ class RouterBase
{ {
/** /**
* The instance of this class
* @var static * @var static
*/ */
protected static $instance; protected static $instance;
@@ -23,14 +23,7 @@ class RouterBase
protected $request; protected $request;
/** /**
* Response * Defines if a route is currently being processed.
* @var Response
*/
protected $response;
/**
* Used to keep track of whether or not a should should be added to
* the backstack-list for group-processing or not.
* @var bool * @var bool
*/ */
protected $processingRoute; protected $processingRoute;
@@ -42,16 +35,17 @@ class RouterBase
protected $routes; protected $routes;
/** /**
* List of * List of processed routes
* @var array * @var array
*/ */
protected $controllerUrlMap; protected $processedRoutes;
/** /**
* Backstack array used to keep track of sub-routes * Stack of routes used to keep track of sub-routes added
* when a route is being processed.
* @var array * @var array
*/ */
protected $backStack; protected $routeStack;
/** /**
* List of added bootmanagers * List of added bootmanagers
@@ -111,23 +105,27 @@ class RouterBase
{ {
$this->processingRoute = false; $this->processingRoute = false;
$this->request = new Request(); $this->request = new Request();
$this->response = new Response($this->request);
$this->routes = []; $this->routes = [];
$this->bootManagers = []; $this->bootManagers = [];
$this->backStack = []; $this->routeStack = [];
$this->controllerUrlMap = []; $this->processedRoutes = [];
$this->exceptionHandlers = []; $this->exceptionHandlers = [];
} }
/** /**
* Add route * Add route
* @param RouterEntry $route * @param IRoute $route
* @return RouterEntry * @return IRoute
*/ */
public function addRoute(RouterEntry $route) public function addRoute(IRoute $route)
{ {
if ($this->processingRoute) { /*
$this->backStack[] = $route; * If a route is currently being processed, that means that the
* route being added are rendered from the parent routes callback,
* so we add them to the stack instead.
*/
if ($this->processingRoute === true) {
$this->routeStack[] = $route;
} else { } else {
$this->routes[] = $route; $this->routes[] = $route;
} }
@@ -135,10 +133,10 @@ class RouterBase
return $route; return $route;
} }
protected function processRoutes(array $routes, RouterGroup $group = null, RouterEntry $parent = null) protected function processRoutes(array $routes, RouterGroup $group = null, IRoute $parent = null)
{ {
// Loop through each route-request // Loop through each route-request
/* @var $route RouterEntry */ /* @var $route IRoute */
foreach ($routes as $route) { foreach ($routes as $route) {
if ($route instanceof RouterGroup) { if ($route instanceof RouterGroup) {
@@ -175,24 +173,24 @@ class RouterBase
$route->setParent($parent); $route->setParent($parent);
/* Add/merge parent settings with child */ /* Add/merge parent settings with child */
$route->merge($parent->toArray()); $route->setSettings($parent->toArray());
} }
if ($route instanceof ILoadableRoute) { if ($route instanceof ILoadableRoute) {
/* Add the route to the map, so we can find the active one when all routes has been loaded */ /* Add the route to the map, so we can find the active one when all routes has been loaded */
$this->controllerUrlMap[] = $route; $this->processedRoutes[] = $route;
} }
if (count($this->backStack) > 0) { if (count($this->routeStack) > 0) {
/* Pop and grap the routes added when executing group callback earlier */ /* Pop and grap the routes added when executing group callback earlier */
$backStack = $this->backStack; $stack = $this->routeStack;
$this->backStack = []; $this->routeStack = [];
/* Route any routes added to the backstack */ /* Route any routes added to the stack */
$this->processRoutes($backStack, $route, $group); $this->processRoutes($stack, $route, $group);
} }
} }
} }
@@ -204,7 +202,7 @@ class RouterBase
try { try {
// Initialize boot-managers /* Initialize boot-managers */
if (count($this->bootManagers) > 0) { if (count($this->bootManagers) > 0) {
/* @var $manager RouterBootManager */ /* @var $manager RouterBootManager */
foreach ($this->bootManagers as $manager) { foreach ($this->bootManagers as $manager) {
@@ -218,7 +216,7 @@ class RouterBase
if ($rewrite === false) { if ($rewrite === false) {
// Loop through each route-request /* Loop through each route-request */
$this->processRoutes($this->routes); $this->processRoutes($this->routes);
if ($this->csrfVerifier !== null) { if ($this->csrfVerifier !== null) {
@@ -230,11 +228,13 @@ class RouterBase
$this->originalUrl = $this->request->getUri(); $this->originalUrl = $this->request->getUri();
} }
/* @var $route RouterEntry */ /* @var $route IRoute */
foreach ($this->controllerUrlMap as $route) { foreach ($this->processedRoutes as $route) {
/* If the route matches */
if ($route->matchRoute($this->request)) { if ($route->matchRoute($this->request)) {
/* Check if request method matches */
if (count($route->getRequestMethods()) > 0 && !in_array($this->request->getMethod(), $route->getRequestMethods())) { if (count($route->getRequestMethods()) > 0 && !in_array($this->request->getMethod(), $route->getRequestMethods())) {
$routeNotAllowed = true; $routeNotAllowed = true;
continue; continue;
@@ -243,6 +243,7 @@ class RouterBase
$this->loadedRoute = $route; $this->loadedRoute = $route;
$this->loadedRoute->loadMiddleware($this->request, $this->loadedRoute); $this->loadedRoute->loadMiddleware($this->request, $this->loadedRoute);
/* If the request has changed, we reinitialize the router */
if ($this->request->getUri() !== $this->originalUrl && !in_array($this->request->getUri(), $this->routeRewrites)) { if ($this->request->getUri() !== $this->originalUrl && !in_array($this->request->getUri(), $this->routeRewrites)) {
$this->routeRewrites[] = $this->request->getUri(); $this->routeRewrites[] = $this->request->getUri();
$this->routeRequest(true); $this->routeRequest(true);
@@ -250,6 +251,7 @@ class RouterBase
return; return;
} }
/* Render route */
$routeNotAllowed = false; $routeNotAllowed = false;
$this->request->setUri($this->originalUrl); $this->request->setUri($this->originalUrl);
$this->loadedRoute->renderRoute($this->request); $this->loadedRoute->renderRoute($this->request);
@@ -284,7 +286,9 @@ class RouterBase
$request = $handler->handleError($this->request, $this->loadedRoute, $e); $request = $handler->handleError($this->request, $this->loadedRoute, $e);
if ($request !== null && $request->getUri() !== $this->originalUrl && !in_array($request->getUri(), $this->routeRewrites)) { /* If the request has changed */
if ($request !== null && $this->request->getUri() !== $this->originalUrl && !in_array($request->getUri(), $this->routeRewrites)) {
$this->request = $request;
$this->routeRewrites[] = $request->getUri(); $this->routeRewrites[] = $request->getUri();
$this->routeRequest(true); $this->routeRequest(true);
@@ -370,7 +374,7 @@ class RouterBase
public function findRoute($name) public function findRoute($name)
{ {
/* @var $route LoadableRoute */ /* @var $route LoadableRoute */
foreach ($this->controllerUrlMap as $route) { foreach ($this->processedRoutes as $route) {
/* Check if the name matches with a name on the route. Should match either router alias or controller alias. */ /* Check if the name matches with a name on the route. Should match either router alias or controller alias. */
if ($route->hasName($name)) { if ($route->hasName($name)) {
@@ -465,7 +469,7 @@ class RouterBase
/* Loop through all the routes to see if we can find a match */ /* Loop through all the routes to see if we can find a match */
/* @var $route LoadableRoute */ /* @var $route LoadableRoute */
foreach ($this->controllerUrlMap as $route) { foreach ($this->processedRoutes as $route) {
/* Check if the route contains the name/alias */ /* Check if the route contains the name/alias */
if ($route->hasName($controller)) { if ($route->hasName($controller)) {
@@ -530,15 +534,6 @@ class RouterBase
return $this->request; return $this->request;
} }
/**
* Get response
* @return Response
*/
public function getResponse()
{
return $this->response;
}
/** /**
* Get csrf verifier class * Get csrf verifier class
* @return BaseCsrfVerifier * @return BaseCsrfVerifier
+5 -7
View File
@@ -6,7 +6,7 @@ use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\HttpException; use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException; use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
abstract class RouterEntry abstract class RouterEntry implements IRoute
{ {
const REQUEST_TYPE_GET = 'get'; const REQUEST_TYPE_GET = 'get';
const REQUEST_TYPE_POST = 'post'; const REQUEST_TYPE_POST = 'post';
@@ -125,7 +125,7 @@ abstract class RouterEntry
return null; return null;
} }
public function loadMiddleware(Request $request, RouterEntry &$route) public function loadMiddleware(Request $request, LoadableRoute &$route)
{ {
if (count($this->getMiddlewares()) > 0) { if (count($this->getMiddlewares()) > 0) {
foreach ($this->getMiddlewares() as $middleware) { foreach ($this->getMiddlewares() as $middleware) {
@@ -241,10 +241,10 @@ abstract class RouterEntry
/** /**
* Set parent route * Set parent route
* *
* @param RouterEntry $parent * @param IRoute $parent
* @return static $this * @return static $this
*/ */
public function setParent(RouterEntry $parent) public function setParent(IRoute $parent)
{ {
$this->parent = $parent; $this->parent = $parent;
@@ -450,7 +450,7 @@ abstract class RouterEntry
* @param array $values * @param array $values
* @return static $this * @return static $this
*/ */
public function merge(array $values) public function setSettings(array $values)
{ {
if (isset($values['namespace']) && $this->namespace === null) { if (isset($values['namespace']) && $this->namespace === null) {
$this->setNamespace($values['namespace']); $this->setNamespace($values['namespace']);
@@ -476,6 +476,4 @@ abstract class RouterEntry
return $this; return $this;
} }
abstract function matchRoute(Request $request);
} }
+2 -2
View File
@@ -88,7 +88,7 @@ class RouterGroup extends RouterEntry
* @param array $values * @param array $values
* @return static * @return static
*/ */
public function merge(array $values) public function setSettings(array $values)
{ {
if (isset($values['prefix'])) { if (isset($values['prefix'])) {
$this->setPrefix($values['prefix'] . $this->prefix); $this->setPrefix($values['prefix'] . $this->prefix);
@@ -102,7 +102,7 @@ class RouterGroup extends RouterEntry
$this->setDomains((array)$values['domain']); $this->setDomains((array)$values['domain']);
} }
parent::merge($values); parent::setSettings($values);
return $this; return $this;
} }
+26 -13
View File
@@ -8,13 +8,24 @@
namespace Pecee\SimpleRouter; namespace Pecee\SimpleRouter;
use Pecee\Http\Middleware\BaseCsrfVerifier; use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Response;
use Pecee\SimpleRouter\Exceptions\HttpException; use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException; use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
class SimpleRouter class SimpleRouter
{ {
/**
* Default namespace added to all routes
* @var string
*/
protected static $defaultNamespace; protected static $defaultNamespace;
/**
* The response object
* @var Response
*/
protected static $response;
/** /**
* Start/route request * Start/route request
* *
@@ -147,7 +158,7 @@ class SimpleRouter
{ {
$group = new RouterGroup(); $group = new RouterGroup();
$group->setCallback($callback); $group->setCallback($callback);
$group->merge($settings); $group->setSettings($settings);
if (is_callable($callback) === false) { if (is_callable($callback) === false) {
throw new \InvalidArgumentException('Invalid callback provided. Only functions or methods supported'); throw new \InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
@@ -194,7 +205,7 @@ class SimpleRouter
* @param string $url * @param string $url
* @param string|\Closure $callback * @param string|\Closure $callback
* @param array|null $settings * @param array|null $settings
* @return RouterEntry|RouterRoute * @return RouterRoute
*/ */
public static function match(array $requestMethods, $url, $callback, array $settings = null) public static function match(array $requestMethods, $url, $callback, array $settings = null)
{ {
@@ -203,7 +214,7 @@ class SimpleRouter
$route = static::addDefaultNamespace($route); $route = static::addDefaultNamespace($route);
if ($settings !== null) { if ($settings !== null) {
$route->merge($settings); $route->setSettings($settings);
} }
static::router()->addRoute($route); static::router()->addRoute($route);
@@ -222,11 +233,10 @@ class SimpleRouter
public static function all($url, $callback, array $settings = null) public static function all($url, $callback, array $settings = null)
{ {
$route = new RouterRoute($url, $callback); $route = new RouterRoute($url, $callback);
$route = static::addDefaultNamespace($route); $route = static::addDefaultNamespace($route);
if ($settings !== null) { if ($settings !== null) {
$route->merge($settings); $route->setSettings($settings);
} }
static::router()->addRoute($route); static::router()->addRoute($route);
@@ -245,11 +255,10 @@ class SimpleRouter
public static function controller($url, $controller, array $settings = null) public static function controller($url, $controller, array $settings = null)
{ {
$route = new RouterController($url, $controller); $route = new RouterController($url, $controller);
$route = static::addDefaultNamespace($route); $route = static::addDefaultNamespace($route);
if ($settings !== null) { if ($settings !== null) {
$route->merge($settings); $route->setSettings($settings);
} }
static::router()->addRoute($route); static::router()->addRoute($route);
@@ -270,7 +279,7 @@ class SimpleRouter
$route = new RouterResource($url, $controller); $route = new RouterResource($url, $controller);
if ($settings !== null) { if ($settings !== null) {
$route->merge($settings); $route->setSettings($settings);
} }
static::router()->addRoute($route); static::router()->addRoute($route);
@@ -338,11 +347,15 @@ class SimpleRouter
/** /**
* Get the response object * Get the response object
* *
* @return \Pecee\Http\Response * @return Response
*/ */
public static function response() public static function response()
{ {
return static::router()->getResponse(); if(static::$response === null) {
static::$response = new Response(static::request());
}
return static::$response;
} }
/** /**
@@ -358,10 +371,10 @@ class SimpleRouter
/** /**
* Prepends the default namespace to all new routes added. * Prepends the default namespace to all new routes added.
* *
* @param RouterEntry $route * @param IRoute $route
* @return RouterEntry * @return IRoute
*/ */
protected static function addDefaultNamespace(RouterEntry $route) protected static function addDefaultNamespace(IRoute $route)
{ {
if (static::$defaultNamespace !== null) { if (static::$defaultNamespace !== null) {
$namespace = static::$defaultNamespace; $namespace = static::$defaultNamespace;