mirror of
https://github.com/skipperbent/simple-php-router.git
synced 2026-06-17 08:47:52 +00:00
Major overhaul
This commit is contained in:
+1
-1
@@ -1,5 +1,5 @@
|
||||
<?php
|
||||
namespace Pecee\Controller;
|
||||
namespace Pecee\Controllers;
|
||||
|
||||
interface IRestController {
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
<?php
|
||||
namespace Pecee\Exception;
|
||||
|
||||
class RouterException extends \Exception
|
||||
{
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
<?php
|
||||
namespace Pecee\Handler;
|
||||
namespace Pecee\Handlers;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\RouterEntry;
|
||||
@@ -2,7 +2,7 @@
|
||||
namespace Pecee\Http\Middleware;
|
||||
|
||||
use Pecee\CsrfToken;
|
||||
use Pecee\Exception\TokenMismatchException;
|
||||
use Pecee\Exceptions\TokenMismatchException;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\RouterEntry;
|
||||
|
||||
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
namespace Pecee\Exception;
|
||||
namespace Pecee\Exceptions;
|
||||
|
||||
class TokenMismatchException extends \Exception
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace Pecee\SimpleRouter\Exceptions;
|
||||
|
||||
class HttpException extends \Exception
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
namespace Pecee\SimpleRouter\Exceptions;
|
||||
|
||||
class NotFoundHttpException extends HttpException
|
||||
{
|
||||
}
|
||||
@@ -8,7 +8,7 @@ abstract class LoadableRoute extends RouterEntry implements ILoadableRoute
|
||||
const PARAMETER_OPTIONAL_SYMBOL = '?';
|
||||
|
||||
protected $url;
|
||||
protected $alias;
|
||||
protected $names = array();
|
||||
|
||||
public function getUrl()
|
||||
{
|
||||
@@ -36,44 +36,90 @@ abstract class LoadableRoute extends RouterEntry implements ILoadableRoute
|
||||
}
|
||||
|
||||
/**
|
||||
* Get alias for the url which can be used when getting the url route.
|
||||
* Returns the provided name of the router (first if multiple).
|
||||
* Alias for LoadableRoute::getName().
|
||||
*
|
||||
* @see LoadableRoute::getName()
|
||||
* @return string|array
|
||||
*/
|
||||
public function getAlias()
|
||||
{
|
||||
return $this->alias;
|
||||
return $this->getName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if route has given alias.
|
||||
* Returns the provided name for the router (first if multiple).
|
||||
* @return string
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return $this->names[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get route names
|
||||
* @return array
|
||||
*/
|
||||
public function getNames() {
|
||||
return $this->names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if route has given name.
|
||||
* Alias for LoadableRoute::hasName();
|
||||
*
|
||||
* @see LoadableRoute::hasName()
|
||||
* @param $name
|
||||
*/
|
||||
public function hasAlias($name)
|
||||
{
|
||||
$this->hasName($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if route has given name.
|
||||
*
|
||||
* @param string $name
|
||||
* @return bool
|
||||
*/
|
||||
public function hasAlias($name)
|
||||
public function hasName($name)
|
||||
{
|
||||
if ($this->getAlias() !== null) {
|
||||
if (is_array($this->getAlias()) === true) {
|
||||
foreach ($this->getAlias() as $alias) {
|
||||
if (strtolower($alias) === strtolower($name)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return strtolower($this->getAlias()) === strtolower($name);
|
||||
}
|
||||
|
||||
return false;
|
||||
return (in_array($name, $this->names, false) !== false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the url alias for easier getting the url route.
|
||||
* @param string|array $alias
|
||||
* Sets the router name, which makes it easier to obtain the url or router at a later point.
|
||||
* Alias for LoadableRoute::setName().
|
||||
*
|
||||
* @see LoadableRoute::setName()
|
||||
* @param string|array $name
|
||||
* @return static
|
||||
*/
|
||||
public function setAlias($alias)
|
||||
public function setAlias($name)
|
||||
{
|
||||
$this->alias = $alias;
|
||||
return $this->setName($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the router name, which makes it easier to obtain the url or router at a later point.
|
||||
*
|
||||
* @param string $name
|
||||
* @return static $this
|
||||
*/
|
||||
public function setName($name)
|
||||
{
|
||||
array_push($this->names, $name);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set multiple names for the route
|
||||
*
|
||||
* @param array $names
|
||||
* @return static $this
|
||||
*/
|
||||
public function setNames(array $names) {
|
||||
$this->names = $names;
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -85,12 +131,16 @@ abstract class LoadableRoute extends RouterEntry implements ILoadableRoute
|
||||
*/
|
||||
public function merge(array $values)
|
||||
{
|
||||
// Change as to alias
|
||||
if (isset($values['as'])) {
|
||||
$this->setAlias($values['as']);
|
||||
$this->setNames((array)$values['as']);
|
||||
}
|
||||
|
||||
if (isset($values['prefix'])) {
|
||||
$this->setUrl($values['prefix'] . $this->getUrl());
|
||||
}
|
||||
|
||||
parent::merge($values);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
<?php
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Exception\RouterException;
|
||||
use Pecee\Handler\IExceptionHandler;
|
||||
use Pecee\Handlers\IExceptionHandler;
|
||||
use Pecee\Http\Middleware\BaseCsrfVerifier;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\Http\Response;
|
||||
use Pecee\SimpleRouter\Exceptions\HttpException;
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
|
||||
class RouterBase
|
||||
{
|
||||
@@ -111,11 +112,11 @@ class RouterBase
|
||||
$this->processingRoute = false;
|
||||
$this->request = new Request();
|
||||
$this->response = new Response($this->request);
|
||||
$this->routes = array();
|
||||
$this->bootManagers = array();
|
||||
$this->backStack = array();
|
||||
$this->controllerUrlMap = array();
|
||||
$this->exceptionHandlers = array();
|
||||
$this->routes = [];
|
||||
$this->bootManagers = [];
|
||||
$this->backStack = [];
|
||||
$this->controllerUrlMap = [];
|
||||
$this->exceptionHandlers = [];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -134,25 +135,16 @@ class RouterBase
|
||||
return $route;
|
||||
}
|
||||
|
||||
protected function processRoutes(array $routes, array $settings = array(), array $prefixes = array(), RouterEntry $parent = null)
|
||||
protected function processRoutes(array $routes, RouterGroup $group = null, RouterEntry $parent = null)
|
||||
{
|
||||
// Loop through each route-request
|
||||
/* @var $route RouterEntry */
|
||||
foreach ($routes as $route) {
|
||||
|
||||
$newPrefixes = $prefixes;
|
||||
$newSettings = $settings;
|
||||
|
||||
if ($parent !== null) {
|
||||
$route->setParent($parent);
|
||||
}
|
||||
|
||||
if (count($settings)) {
|
||||
$route->merge($settings);
|
||||
}
|
||||
|
||||
if ($route instanceof RouterGroup) {
|
||||
|
||||
$group = $route;
|
||||
|
||||
if ($route->getCallback() !== null && is_callable($route->getCallback())) {
|
||||
|
||||
$this->processingRoute = true;
|
||||
@@ -160,33 +152,47 @@ class RouterBase
|
||||
$this->processingRoute = false;
|
||||
|
||||
if ($route->matchRoute($this->request)) {
|
||||
// Add ExceptionHandler
|
||||
|
||||
/* Add exceptionhandlers */
|
||||
if (count($route->getExceptionHandlers()) > 0) {
|
||||
$this->exceptionHandlers = array_merge($route->getExceptionHandlers(), $this->exceptionHandlers);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$newPrefixes[] = trim($route->getPrefix(), '/');
|
||||
$newSettings = array_merge($settings, $route->toArray());
|
||||
if($group !== null) {
|
||||
|
||||
/* Add the parent group */
|
||||
$route->setGroup($group);
|
||||
|
||||
}
|
||||
|
||||
if ($parent !== null) {
|
||||
|
||||
/* Add the parent route */
|
||||
$route->setParent($parent);
|
||||
|
||||
/* Add/merge parent settings with child */
|
||||
$route->merge($parent->toArray());
|
||||
|
||||
}
|
||||
|
||||
if ($route instanceof ILoadableRoute) {
|
||||
|
||||
if (count($prefixes)) {
|
||||
$route->setUrl(trim(join('/', $prefixes) . $route->getUrl(), '/'));
|
||||
}
|
||||
|
||||
/* Add the route to the map, so we can find the active one when all routes has been loaded */
|
||||
$this->controllerUrlMap[] = $route;
|
||||
}
|
||||
|
||||
if (count($this->backStack) > 0) {
|
||||
|
||||
/* Pop and grap the routes added when executing group callback earlier */
|
||||
$backStack = $this->backStack;
|
||||
$this->backStack = [];
|
||||
|
||||
// Route any routes added to the backstack
|
||||
$this->processRoutes($backStack, $newSettings, $newPrefixes, $route);
|
||||
/* Route any routes added to the backstack */
|
||||
$this->processRoutes($backStack, $route, $group);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -205,7 +211,7 @@ class RouterBase
|
||||
$this->request = $manager->boot($this->request);
|
||||
|
||||
if (!($this->request instanceof Request)) {
|
||||
throw new RouterException('Custom router bootmanager "' . get_class($manager) . '" must return instance of Request.');
|
||||
throw new HttpException('Bootmanager "' . get_class($manager) . '" must return instance of ' . Request::class, 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -240,6 +246,7 @@ class RouterBase
|
||||
if ($this->request->getUri() !== $this->originalUrl && !in_array($this->request->getUri(), $this->routeRewrites)) {
|
||||
$this->routeRewrites[] = $this->request->getUri();
|
||||
$this->routeRequest(true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -255,12 +262,12 @@ class RouterBase
|
||||
$this->handleException($e);
|
||||
}
|
||||
|
||||
if ($routeNotAllowed) {
|
||||
$this->handleException(new RouterException('Route or method not allowed', 403));
|
||||
if ($routeNotAllowed === true) {
|
||||
$this->handleException(new HttpException('Route or method not allowed', 403));
|
||||
}
|
||||
|
||||
if ($this->loadedRoute === null) {
|
||||
$this->handleException(new RouterException(sprintf('Route not found: %s', $this->request->getUri()), 404));
|
||||
$this->handleException(new NotFoundHttpException('Route not found: ' . $this->request->getUri(), 404));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,7 +279,7 @@ class RouterBase
|
||||
$handler = new $handler();
|
||||
|
||||
if (!($handler instanceof IExceptionHandler)) {
|
||||
throw new RouterException('Exception handler must implement the IExceptionHandler interface.');
|
||||
throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500);
|
||||
}
|
||||
|
||||
$request = $handler->handleError($this->request, $this->loadedRoute, $e);
|
||||
@@ -280,17 +287,17 @@ class RouterBase
|
||||
if ($request !== null && $request->getUri() !== $this->originalUrl && !in_array($request->getUri(), $this->routeRewrites)) {
|
||||
$this->routeRewrites[] = $request->getUri();
|
||||
$this->routeRequest(true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
public function arrayToParams(array $getParams = null, $includeEmpty = true)
|
||||
public function arrayToParams(array $getParams = [], $includeEmpty = true)
|
||||
{
|
||||
if (is_array($getParams) === true && count($getParams) > 0) {
|
||||
if (count($getParams) > 0) {
|
||||
|
||||
if ($includeEmpty === false) {
|
||||
$getParams = array_filter($getParams, function ($item) {
|
||||
@@ -304,151 +311,168 @@ class RouterBase
|
||||
return '';
|
||||
}
|
||||
|
||||
protected function processUrl(LoadableRoute $route, $method = null, $parameters = null, $getParams = null)
|
||||
protected function processUrl(LoadableRoute $route, $method = null, $parameters = null, array $getParams = [])
|
||||
{
|
||||
$domain = '';
|
||||
$parent = $route->getParent();
|
||||
$url = '';
|
||||
|
||||
$parameters = (array)$parameters;
|
||||
|
||||
if ($parent !== null && $parent instanceof RouterGroup && count($parent->getDomains()) > 0) {
|
||||
$domain = $parent->getDomains();
|
||||
$domain = '//' . $domain[0];
|
||||
if ($route->getGroup() !== null && count($route->getGroup()->getDomains()) > 0) {
|
||||
$url .= '//' . $route->getGroup()->getDomains()[0];
|
||||
}
|
||||
|
||||
$url = $domain . '/' . trim($route->getUrl(), '/');
|
||||
$url .= '/' . trim($route->getUrl(), '/');
|
||||
|
||||
if ($route instanceof IControllerRoute && $method !== null) {
|
||||
|
||||
$url .= '/' . $method . '/';
|
||||
|
||||
if (count($parameters) > 0) {
|
||||
$url .= join('/', (array)$parameters);
|
||||
$url .= join('/', $parameters);
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
if ($parameters !== null && count($parameters) > 0) {
|
||||
$params = array_merge($route->getParameters(), (array)$parameters);
|
||||
} else {
|
||||
$params = $route->getParameters();
|
||||
}
|
||||
$params = array_merge($route->getParameters(), $parameters);
|
||||
|
||||
$otherParams = array();
|
||||
/* Url that contains parameters that aren't recognized */
|
||||
$unknownParams = [];
|
||||
|
||||
/* Let's parse the values of any {} parameter in the url */
|
||||
foreach ($params as $param => $value) {
|
||||
$value = (isset($parameters[$param])) ? $parameters[$param] : $value;
|
||||
|
||||
/* Create the param string - {} */
|
||||
$param1 = LoadableRoute::PARAMETER_MODIFIERS[0] . $param . LoadableRoute::PARAMETER_MODIFIERS[1];
|
||||
|
||||
/* Create the param string with the optional symbol - {?} */
|
||||
$param2 = LoadableRoute::PARAMETER_MODIFIERS[0] . $param . LoadableRoute::PARAMETER_OPTIONAL_SYMBOL . LoadableRoute::PARAMETER_MODIFIERS[1];
|
||||
|
||||
if (stripos($url, $param1) !== false || stripos($url, $param) !== false) {
|
||||
$url = str_ireplace([$param1, $param2], $value, $url);
|
||||
} else {
|
||||
$otherParams[$param] = $value;
|
||||
$unknownParams[$param] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$url = rtrim($url, '/') . '/' . join('/', $otherParams);
|
||||
$url = rtrim($url, '/') . '/' . join('/', $unknownParams);
|
||||
}
|
||||
|
||||
$url = rtrim($url, '/') . '/';
|
||||
|
||||
if ($getParams !== null) {
|
||||
$url .= $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
return $url;
|
||||
return rtrim($url, '/') . '/' . $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find route by alias, class, callback or method.
|
||||
*
|
||||
* @param string $query
|
||||
* @param string $name
|
||||
* @return LoadableRoute|null
|
||||
*/
|
||||
public function findRoute($query)
|
||||
public function findRoute($name)
|
||||
{
|
||||
/* @var $route LoadableRoute */
|
||||
foreach ($this->controllerUrlMap as $route) {
|
||||
|
||||
// Check an alias exist, if the matches - use it
|
||||
// Matches either Router alias or controller alias.
|
||||
if ($route->hasAlias($query)) {
|
||||
/* Check if the name matches with a name on the route. Should match either router alias or controller alias. */
|
||||
if ($route->hasName($name)) {
|
||||
return $route;
|
||||
}
|
||||
|
||||
// Direct match to controller
|
||||
if ($route instanceof IControllerRoute) {
|
||||
if (strtolower($route->getController()) === strtolower($query)) {
|
||||
return $route;
|
||||
}
|
||||
/* Direct match to controller */
|
||||
if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($name)) {
|
||||
return $route;
|
||||
}
|
||||
|
||||
// Using @ is most definitely a controller@method or alias@method
|
||||
if (strpos($query, '@') !== false) {
|
||||
list($controller, $method) = array_map('strtolower', explode('@', $query));
|
||||
/* Using @ is most definitely a controller@method or alias@method */
|
||||
if (strpos($name, '@') !== false) {
|
||||
list($controller, $method) = array_map('strtolower', explode('@', $name));
|
||||
|
||||
if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) {
|
||||
return $route;
|
||||
}
|
||||
}
|
||||
|
||||
// Use callback if it's not a function
|
||||
if (strpos($query, '@') !== false && strpos($route->getCallback(), '@') !== false && !is_callable($route->getCallback())) {
|
||||
/* Check if callback matches (if it's not a function) */
|
||||
if (strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && !is_callable($route->getCallback())) {
|
||||
|
||||
if (strtolower($query) === strtolower($route->getClass())) {
|
||||
/* Check if the entire callback is matching */
|
||||
if (strtolower($route->getCallback()) === strtolower($name) || strpos($route->getCallback(), $name) === 0) {
|
||||
return $route;
|
||||
}
|
||||
|
||||
if (strtolower($route->getCallback()) === strtolower($query) || strpos($route->getCallback(), $query) === 0) {
|
||||
/* Check if the class part of the callback matches (class@method) */
|
||||
if (strtolower($name) === strtolower($route->getClass())) {
|
||||
return $route;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getRoute($controller = null, $parameters = null, $getParams = null)
|
||||
public function getRoute($name = null, $parameters = null, array $getParams = null)
|
||||
{
|
||||
return $this->getUrl($name, $parameters, $getParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get url for a route by using either name/alias, class or method name.
|
||||
*
|
||||
* The name parameter supports the following values:
|
||||
* - Route name
|
||||
* - Controller/resource name (with or without method)
|
||||
* - Controller class name
|
||||
*
|
||||
* When searching for controller/resource by name, you can use this syntax "route.name@method".
|
||||
* You can also use the same syntax when searching for a specific controller-class "MyController@home".
|
||||
* If no arguments is specified, it will return the url for the current loaded route.
|
||||
*
|
||||
* @param string|null $name
|
||||
* @param string|array|null $parameters
|
||||
* @param array|null $getParams
|
||||
* @return string
|
||||
*/
|
||||
public function getUrl($name = null, $parameters = null, array $getParams = null)
|
||||
{
|
||||
if ($getParams !== null && is_array($getParams) === false) {
|
||||
throw new \InvalidArgumentException('Invalid type for getParams. Must be array or null');
|
||||
}
|
||||
|
||||
// Return current route if no options has been specified
|
||||
if ($controller === null && $parameters === null) {
|
||||
|
||||
$getParams = ($getParams !== null) ? $getParams : $_GET;
|
||||
$url = parse_url($this->request->getUri(), PHP_URL_PATH) . $this->arrayToParams($getParams);
|
||||
|
||||
return $url;
|
||||
if($getParams === null) {
|
||||
$getParams = $_GET;
|
||||
}
|
||||
|
||||
// If nothing is defined and a route is loaded we use that
|
||||
if ($controller === null && $this->loadedRoute !== null) {
|
||||
/* Return current route if no options has been specified */
|
||||
if ($name === null && $parameters === null) {
|
||||
return '/' . trim(parse_url($this->request->getUri(), PHP_URL_PATH), '/') . '/' . $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
/* If nothing is defined and a route is loaded we use that */
|
||||
if ($name === null && $this->loadedRoute !== null) {
|
||||
return $this->processUrl($this->loadedRoute, $this->loadedRoute->getMethod(), $parameters, $getParams);
|
||||
}
|
||||
|
||||
$route = $this->findRoute($controller);
|
||||
/* We try to find a match on the given name */
|
||||
$route = $this->findRoute($name);
|
||||
|
||||
if ($route !== null) {
|
||||
return $this->processUrl($route, $route->getMethod(), $parameters, $getParams);
|
||||
}
|
||||
|
||||
// Using @ is most definitely a controller@method or alias@method
|
||||
if (stripos($controller, '@') !== false) {
|
||||
list($controller, $method) = explode('@', $controller);
|
||||
/* Using @ is most definitely a controller@method or alias@method */
|
||||
if (stripos($name, '@') !== false) {
|
||||
list($controller, $method) = explode('@', $name);
|
||||
|
||||
/* Loop through all the routes to see if we can find a match */
|
||||
|
||||
/* @var $route LoadableRoute */
|
||||
foreach ($this->controllerUrlMap as $route) {
|
||||
|
||||
if ($route->hasAlias($controller)) {
|
||||
/* Check if the route contains the name/alias */
|
||||
if ($route->hasName($controller)) {
|
||||
return $this->processUrl($route, $method, $parameters, $getParams);
|
||||
}
|
||||
|
||||
// Match controllers either by: "alias @ method" or "controller@method"
|
||||
/* Check if the route controller is equal to the name */
|
||||
if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($controller)) {
|
||||
return $this->processUrl($route, $method, $parameters, $getParams);
|
||||
}
|
||||
@@ -456,19 +480,8 @@ class RouterBase
|
||||
}
|
||||
}
|
||||
|
||||
$url = [($controller === null) ? '/' : $controller];
|
||||
|
||||
if ($parameters !== null && count($parameters) > 0) {
|
||||
$url = array_merge($url, (array)$parameters);
|
||||
}
|
||||
|
||||
$url = '/' . trim(join('/', $url), '/') . '/';
|
||||
|
||||
if ($getParams !== null) {
|
||||
$url .= $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
return $url;
|
||||
/* No result so we assume that someone is using a hardcoded url and join everything together. */
|
||||
return '/' . trim(join('/', array_merge((array)$name, (array)$parameters)), '/') . '/' . $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -543,6 +556,7 @@ class RouterBase
|
||||
public function setCsrfVerifier(BaseCsrfVerifier $csrfVerifier)
|
||||
{
|
||||
$this->csrfVerifier = $csrfVerifier;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<?php
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Exception\RouterException;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
|
||||
class RouterController extends LoadableRoute implements IControllerRoute
|
||||
{
|
||||
@@ -31,7 +31,7 @@ class RouterController extends LoadableRoute implements IControllerRoute
|
||||
$method = $request->getMethod() . ucfirst($controller[1]);
|
||||
|
||||
if (!method_exists($class, $method)) {
|
||||
throw new RouterException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
|
||||
throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
|
||||
}
|
||||
|
||||
call_user_func_array(array($class, $method), $this->getParameters());
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<?php
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Exception\RouterException;
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Exceptions\HttpException;
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
|
||||
abstract class RouterEntry
|
||||
{
|
||||
@@ -23,21 +24,23 @@ abstract class RouterEntry
|
||||
self::REQUEST_TYPE_DELETE,
|
||||
];
|
||||
|
||||
protected $group;
|
||||
protected $parent;
|
||||
protected $callback;
|
||||
|
||||
protected $namespace;
|
||||
protected $defaultNamespace;
|
||||
|
||||
/* Default options */
|
||||
protected $namespace;
|
||||
protected $regex;
|
||||
protected $requestMethods = array();
|
||||
protected $where = array();
|
||||
protected $parameters = array();
|
||||
protected $middlewares = array();
|
||||
protected $requestMethods = [];
|
||||
protected $where = [];
|
||||
protected $parameters = [];
|
||||
protected $middlewares = [];
|
||||
|
||||
protected function loadClass($name)
|
||||
{
|
||||
if (!class_exists($name)) {
|
||||
throw new RouterException(sprintf('Class %s does not exist', $name));
|
||||
throw new HttpException(sprintf('Class %s does not exist', $name), 500);
|
||||
}
|
||||
|
||||
return new $name();
|
||||
@@ -45,19 +48,18 @@ abstract class RouterEntry
|
||||
|
||||
protected function parseParameters($route, $url, $parameterRegex = '[\w]+')
|
||||
{
|
||||
$parameterNames = array();
|
||||
$parameterNames = [];
|
||||
$regex = '';
|
||||
$lastCharacter = '';
|
||||
$isParameter = false;
|
||||
$parameter = '';
|
||||
|
||||
$routeLength = strlen($route);
|
||||
for ($i = 0; $i < $routeLength; $i++) {
|
||||
for ($i = 0; $i < strlen($route); $i++) {
|
||||
|
||||
$character = $route[$i];
|
||||
|
||||
if ($character === '{') {
|
||||
// Remove "/" and "\" from regex
|
||||
/* Remove "/" and "\" from regex */
|
||||
if (substr($regex, strlen($regex) - 1) === '/') {
|
||||
$regex = substr($regex, 0, strlen($regex) - 2);
|
||||
}
|
||||
@@ -66,7 +68,7 @@ abstract class RouterEntry
|
||||
} elseif ($isParameter && $character === '}') {
|
||||
$required = true;
|
||||
|
||||
// Check for optional parameter and use custom parameter regex if it exists
|
||||
/* Check for optional parameter and use custom parameter regex if it exists */
|
||||
if (is_array($this->where) === true && isset($this->where[$parameter])) {
|
||||
$parameterRegex = $this->where[$parameter];
|
||||
}
|
||||
@@ -80,8 +82,8 @@ abstract class RouterEntry
|
||||
}
|
||||
|
||||
$parameterNames[] = [
|
||||
'name' => $parameter,
|
||||
'required' => $required
|
||||
'name' => $parameter,
|
||||
'required' => $required,
|
||||
];
|
||||
|
||||
$parameter = '';
|
||||
@@ -97,17 +99,17 @@ abstract class RouterEntry
|
||||
$lastCharacter = $character;
|
||||
}
|
||||
|
||||
$parameterValues = array();
|
||||
$parameterValues = [];
|
||||
|
||||
if (preg_match('/^' . $regex . '\/?$/is', $url, $parameterValues)) {
|
||||
|
||||
$parameters = array();
|
||||
$parameters = [];
|
||||
|
||||
foreach ($parameterNames as $name) {
|
||||
$parameterValue = isset($parameterValues[$name['name']]) ? $parameterValues[$name['name']] : null;
|
||||
|
||||
if ($name['required'] && $parameterValue === null) {
|
||||
throw new RouterException('Missing required parameter ' . $name['name'], 404);
|
||||
throw new HttpException('Missing required parameter ' . $name['name'], 404);
|
||||
}
|
||||
|
||||
if ($name['required'] === false && $parameterValue === null) {
|
||||
@@ -130,12 +132,10 @@ abstract class RouterEntry
|
||||
|
||||
$middleware = $this->loadClass($middleware);
|
||||
if (!($middleware instanceof IMiddleware)) {
|
||||
throw new RouterException($middleware . ' must be instance of Middleware');
|
||||
throw new HttpException($middleware . ' must be instance of Middleware');
|
||||
}
|
||||
|
||||
/* @var $class IMiddleware */
|
||||
$middleware->handle($request, $route);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,12 +144,12 @@ abstract class RouterEntry
|
||||
{
|
||||
if ($this->getCallback() !== null && is_callable($this->getCallback())) {
|
||||
|
||||
// When the callback is a function
|
||||
/* When the callback is a function */
|
||||
call_user_func_array($this->getCallback(), $this->getParameters());
|
||||
|
||||
} else {
|
||||
|
||||
// When the callback is a method
|
||||
/* When the callback is a method */
|
||||
$controller = explode('@', $this->getCallback());
|
||||
$className = $this->getNamespace() . '\\' . $controller[0];
|
||||
|
||||
@@ -157,14 +157,14 @@ abstract class RouterEntry
|
||||
$method = $controller[1];
|
||||
|
||||
if (!method_exists($class, $method)) {
|
||||
throw new RouterException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
|
||||
throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
|
||||
}
|
||||
|
||||
$parameters = array_filter($this->getParameters(), function ($var) {
|
||||
return ($var !== null);
|
||||
});
|
||||
|
||||
call_user_func_array(array($class, $method), $parameters);
|
||||
call_user_func_array([$class, $method], $parameters);
|
||||
|
||||
return $class;
|
||||
}
|
||||
@@ -184,6 +184,7 @@ abstract class RouterEntry
|
||||
if (strpos($this->callback, '@') !== false) {
|
||||
return $this->callback;
|
||||
}
|
||||
|
||||
return 'function_' . md5($this->callback);
|
||||
}
|
||||
|
||||
@@ -209,13 +210,33 @@ abstract class RouterEntry
|
||||
}
|
||||
|
||||
/**
|
||||
* @return RouterEntry
|
||||
* @return LoadableRoute
|
||||
*/
|
||||
public function getParent()
|
||||
{
|
||||
return $this->parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the group for the route.
|
||||
*
|
||||
* @return RouterGroup|null
|
||||
*/
|
||||
public function getGroup()
|
||||
{
|
||||
return $this->group;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set group
|
||||
*
|
||||
* @param RouterGroup $group
|
||||
*/
|
||||
public function setGroup(RouterGroup $group)
|
||||
{
|
||||
$this->group = $group;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set parent route
|
||||
*
|
||||
@@ -250,8 +271,10 @@ abstract class RouterEntry
|
||||
{
|
||||
if (strpos($this->callback, '@') !== false) {
|
||||
$tmp = explode('@', $this->callback);
|
||||
|
||||
return $tmp[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -259,8 +282,10 @@ abstract class RouterEntry
|
||||
{
|
||||
if (strpos($this->callback, '@') !== false) {
|
||||
$tmp = explode('@', $this->callback);
|
||||
|
||||
return $tmp[0];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -306,12 +331,14 @@ abstract class RouterEntry
|
||||
* @param string $namespace
|
||||
* @return static $this
|
||||
*/
|
||||
public function setDefaultNamespace($namespace) {
|
||||
public function setDefaultNamespace($namespace)
|
||||
{
|
||||
$this->defaultNamespace = $namespace;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getDefaultNamespace() {
|
||||
public function getDefaultNamespace()
|
||||
{
|
||||
return $this->defaultNamespace;
|
||||
}
|
||||
|
||||
@@ -355,19 +382,19 @@ abstract class RouterEntry
|
||||
* @param array $options
|
||||
* @return static
|
||||
*/
|
||||
public function where(array $options)
|
||||
public function setWhere(array $options)
|
||||
{
|
||||
$this->where = $options;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add regular expression match for url
|
||||
* Add regular expression match for the entire route.
|
||||
*
|
||||
* @param string $regex
|
||||
* @return static
|
||||
*/
|
||||
public function match($regex)
|
||||
public function setMatch($regex)
|
||||
{
|
||||
$this->regex = $regex;
|
||||
return $this;
|
||||
@@ -380,7 +407,7 @@ abstract class RouterEntry
|
||||
*/
|
||||
public function toArray()
|
||||
{
|
||||
$values = array();
|
||||
$values = [];
|
||||
|
||||
if ($this->namespace !== null) {
|
||||
$values['namespace'] = $this->namespace;
|
||||
@@ -413,25 +440,25 @@ abstract class RouterEntry
|
||||
*/
|
||||
public function merge(array $values)
|
||||
{
|
||||
if (isset($values['namespace'])) {
|
||||
if (isset($values['namespace']) && $this->namespace === null) {
|
||||
$this->setNamespace($values['namespace']);
|
||||
}
|
||||
|
||||
// Push middleware if multiple
|
||||
if (isset($values['middleware'])) {
|
||||
$this->middlewares = array_merge((array)$values['middleware'], $this->middlewares);
|
||||
$this->setMiddlewares(array_merge((array)$values['middleware'], $this->middlewares));
|
||||
}
|
||||
|
||||
if (isset($values['method'])) {
|
||||
$this->setRequestMethods((array)$values['method']);
|
||||
$this->setRequestMethods(array_merge($this->requestMethods, (array)$values['method']));
|
||||
}
|
||||
|
||||
if (isset($values['where'])) {
|
||||
$this->where($values['where']);
|
||||
$this->setWhere(array_merge($this->where, (array)$values['where']));
|
||||
}
|
||||
|
||||
if (isset($values['parameters'])) {
|
||||
$this->setParameters($values['parameters']);
|
||||
$this->setParameters(array_merge($this->parameters, (array)$values['parameters']));
|
||||
}
|
||||
|
||||
return $this;
|
||||
|
||||
@@ -87,7 +87,7 @@ class RouterGroup extends RouterEntry
|
||||
public function merge(array $values)
|
||||
{
|
||||
if (isset($values['prefix'])) {
|
||||
$this->setPrefix($values['prefix']);
|
||||
$this->setPrefix($values['prefix'] . $this->prefix);
|
||||
}
|
||||
|
||||
if (isset($values['exceptionHandler'])) {
|
||||
@@ -103,4 +103,20 @@ class RouterGroup extends RouterEntry
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Export route settings to array so they can be merged with another route.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function toArray()
|
||||
{
|
||||
$values = array();
|
||||
|
||||
if ($this->prefix !== null) {
|
||||
$values['prefix'] = $this->getPrefix();
|
||||
}
|
||||
|
||||
return array_merge($values, parent::toArray());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
<?php
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Exception\RouterException;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
|
||||
class RouterResource extends LoadableRoute implements IControllerRoute
|
||||
{
|
||||
@@ -27,7 +27,7 @@ class RouterResource extends LoadableRoute implements IControllerRoute
|
||||
$method = strtolower($controller[1]);
|
||||
|
||||
if (!method_exists($class, $method)) {
|
||||
throw new RouterException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
|
||||
throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
|
||||
}
|
||||
|
||||
call_user_func_array([$class, $method], $this->getParameters());
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
*/
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Exception\RouterException;
|
||||
use Pecee\Http\Middleware\BaseCsrfVerifier;
|
||||
use Pecee\SimpleRouter\Exceptions\HttpException;
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
|
||||
class SimpleRouter
|
||||
{
|
||||
@@ -17,7 +18,8 @@ class SimpleRouter
|
||||
/**
|
||||
* Start/route request
|
||||
*
|
||||
* @throws \Pecee\Exception\RouterException
|
||||
* @throws HttpException
|
||||
* @throws NotFoundHttpException
|
||||
*/
|
||||
public static function start()
|
||||
{
|
||||
@@ -138,17 +140,17 @@ class SimpleRouter
|
||||
*
|
||||
* @param array $settings
|
||||
* @param \Closure $callback
|
||||
* @throws RouterException
|
||||
* @throws \InvalidArgumentException
|
||||
* @return RouterGroup
|
||||
*/
|
||||
public static function group(array $settings = array(), \Closure $callback)
|
||||
public static function group(array $settings = [], \Closure $callback)
|
||||
{
|
||||
$group = new RouterGroup();
|
||||
$group->setCallback($callback);
|
||||
$group->merge($settings);
|
||||
|
||||
if (is_callable($callback) === false) {
|
||||
throw new RouterException('Invalid callback provided. Only functions or methods supported');
|
||||
throw new \InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
|
||||
}
|
||||
|
||||
static::router()->addRoute($group);
|
||||
@@ -277,16 +279,50 @@ class SimpleRouter
|
||||
}
|
||||
|
||||
/**
|
||||
* Get url by controller or alias.
|
||||
* Get url for a route by using either name/alias, class or method name.
|
||||
*
|
||||
* @param string $controller
|
||||
* @param array|null $parameters
|
||||
* The name parameter supports the following values:
|
||||
* - Route name
|
||||
* - Controller/resource name (with or without method)
|
||||
* - Controller class name
|
||||
*
|
||||
* When searching for controller/resource by name, you can use this syntax "route.name@method".
|
||||
* You can also use the same syntax when searching for a specific controller-class "MyController@home".
|
||||
* If no arguments is specified, it will return the url for the current loaded route.
|
||||
*
|
||||
* This method is an alias for SimpleRouter::getUrl().
|
||||
*
|
||||
* @see SimpleRouter::getUrl()
|
||||
* @param string|null $name
|
||||
* @param string|array|null $parameters
|
||||
* @param array|null $getParams
|
||||
* @return string
|
||||
*/
|
||||
public static function getRoute($controller = null, $parameters = null, $getParams = null)
|
||||
public static function getRoute($name = null, $parameters = null, array $getParams = [])
|
||||
{
|
||||
return static::router()->getRoute($controller, $parameters, $getParams);
|
||||
return static::getUrl($name, $parameters, $getParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get url for a route by using either name/alias, class or method name.
|
||||
*
|
||||
* The name parameter supports the following values:
|
||||
* - Route name
|
||||
* - Controller/resource name (with or without method)
|
||||
* - Controller class name
|
||||
*
|
||||
* When searching for controller/resource by name, you can use this syntax "route.name@method".
|
||||
* You can also use the same syntax when searching for a specific controller-class "MyController@home".
|
||||
* If no arguments is specified, it will return the url for the current loaded route.
|
||||
*
|
||||
* @param string|null $name
|
||||
* @param string|array|null $parameters
|
||||
* @param array|null $getParams
|
||||
* @return string
|
||||
*/
|
||||
public static function getUrl($name = null, $parameters = null, array $getParams = [])
|
||||
{
|
||||
return static::router()->getUrl($name, $parameters, $getParams);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user