From 25244289261b703cfea00212e56cb30d3bbfe1d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sessing=C3=B8?= Date: Tue, 20 Oct 2015 23:54:05 +0200 Subject: [PATCH 1/5] [BUGFIX] Bugfixing - Urls now always returns ending slash when using getRoute(). - Fixed common errors with routing. - Simplified getRoute method. --- src/Pecee/SimpleRouter/RouterBase.php | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/Pecee/SimpleRouter/RouterBase.php b/src/Pecee/SimpleRouter/RouterBase.php index 4fd9d76..0817c9f 100644 --- a/src/Pecee/SimpleRouter/RouterBase.php +++ b/src/Pecee/SimpleRouter/RouterBase.php @@ -165,10 +165,10 @@ class RouterBase { protected function processUrl($route, $method = null, $parameters = null, $getParams = null) { - $url = rtrim($route->getUrl(), '/') . '/'; + $url = $route->getUrl(); if(($route instanceof RouterController || $route instanceof RouterRessource) && $method !== null) { - $url .= $method . '/'; + $url .= $method; } if($route instanceof RouterController || $route instanceof RouterRessource) { @@ -182,18 +182,17 @@ class RouterBase { $i = 0; foreach($params as $param => $value) { $value = (isset($parameters[$param])) ? $parameters[$param] : $value; - $url = str_ireplace('{' . $param. '}', $value, $route->getUrl()); + $url = str_ireplace('{' . $param. '}', $value, $url); $i++; } } } - $p = ''; - if($getParams !== null && count($getParams)) { - $p = '?'.Url::arrayToParams($getParams); - } + $url = rtrim($url, '/') . '/'; - $url .= $p; + if($getParams !== null && count($getParams)) { + $url .= '?'.Url::arrayToParams($getParams); + } return $url; } @@ -208,6 +207,10 @@ class RouterBase { throw new \InvalidArgumentException('Invalid type for getParams. Must be array or null'); } + if($controller === null && $parameters === null) { + return $this->processUrl($this->loadedRoute, null, $getParams); + } + $c = ''; $method = null; @@ -252,6 +255,7 @@ class RouterBase { if(is_array($parameters)) { ArrayUtil::append($url, $parameters); } + return join('/', $url); } From 7863df6325d971b9ff63d0c1ae0fad357eee257e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sessing=C3=B8?= Date: Tue, 20 Oct 2015 23:59:35 +0200 Subject: [PATCH 2/5] [TASK] Updated readme --- README.md | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 3867cb4..ecb598c 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,11 @@ Add the latest version pf Simple PHP Router to your ```composer.json``` - Sub-Domain Routing - CSRF Protection - Optinal/required parameters +- Aliases for ```RouterRoute``` + +### Known issues + +- Posting invalid/unsupported request-type throws 404 instead of "method not allowed" exception, unless defined within a group. ## Initialising the router @@ -44,7 +49,7 @@ SimpleRouter::init($defaultControllerNamespace); ``` ## Adding routes -Remember the ```routes.php``` file you required in your ```index.php```? This file will contain all your custom rules for routing. +Remember the ```routes.php``` file you required in your ```index.php```? This file will contain all your custom rules for routing. This router is heavily inspired by the Laravel 5.* router, so anything you find in the Laravel documentation should work here as well. ### Basic example @@ -54,8 +59,8 @@ use Pecee\SimpleRouter\SimpleRouter; /* * This route will match the url /v1/services/answers/1/ - - * The middleware is just a class that renders before the + + * The middleware is just a class that renders before the * Controller or callback is loaded. This is useful for stopping * the request, for instance if a user is not authenticated. */ @@ -66,13 +71,13 @@ SimpleRouter::group(['prefix' => 'v1', 'middleware' => '\MyWebsite\Middleware\So SimpleRouter::get('/answers/{id}', 'ControllerAnswers@show') ->where(['id' => '[0-9]+'); - + // Resetful ressource SimpleRouter::ressource('/rest', 'ControllerRessource'); - + // Load the entire controller (where url matches method names - getIndex(), postIndex() etc) SimpleRouter::controller('/controller', 'ControllerDefault'); - + // Example of providing callback instead of Controller SimpleRouter::get('/something', function() { die('Callback example'); @@ -84,7 +89,7 @@ SimpleRouter::group(['prefix' => 'v1', 'middleware' => '\MyWebsite\Middleware\So ### Doing it the object oriented (hardcore) way -The ```SimpleRouter``` class referenced in the previous example, is just a simple helper class that knows how to communicate with the ```RouterBase``` class. +The ```SimpleRouter``` class referenced in the previous example, is just a simple helper class that knows how to communicate with the ```RouterBase``` class. If you are up for a challenge, want the full control or simply just want to create your own ```Router``` helper class, this example is for you. ```php @@ -171,7 +176,7 @@ In ```routes.php``` we have added this route: In the template we then call: -```url('myController@show', ['id' => 22], ['category' => 'shoes']);``` +```url('myController@show', ['id' => 22], ['category' => 'shoes']);``` Result url is: @@ -183,4 +188,4 @@ While I work on a better documentation, please refer to the Laravel 5 routing do http://laravel.com/docs/5.1/routing ## Easily extendable -The router can be easily extended to customize your needs. +The router can be easily extended to customize your needs. From 626a3b2f6af407d2cd159317ff6f88b910887c9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sessing=C3=B8?= Date: Wed, 21 Oct 2015 00:27:47 +0200 Subject: [PATCH 3/5] [TASK] Changes - Added support for alias on RouterRoute. - Added typo in resource (renamed class from Ressource to Resource). - Added optional settings parameter in most of the methods in the SimpleRouter class. --- src/Pecee/Http/Response.php | 5 + src/Pecee/SimpleRouter/RouterBase.php | 13 +- src/Pecee/SimpleRouter/RouterResource.php | 155 ++++++++++++++++++++++ src/Pecee/SimpleRouter/RouterRoute.php | 56 ++++---- src/Pecee/SimpleRouter/SimpleRouter.php | 26 ++-- 5 files changed, 216 insertions(+), 39 deletions(-) create mode 100644 src/Pecee/SimpleRouter/RouterResource.php diff --git a/src/Pecee/Http/Response.php b/src/Pecee/Http/Response.php index 566aa5e..5d1a0c3 100644 --- a/src/Pecee/Http/Response.php +++ b/src/Pecee/Http/Response.php @@ -22,6 +22,11 @@ class Response { */ public function redirect($url) { header('location: ' . $url); + die(); + } + + public function refresh() { + $this->redirect(url()); } } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/RouterBase.php b/src/Pecee/SimpleRouter/RouterBase.php index 0817c9f..b5a69e3 100644 --- a/src/Pecee/SimpleRouter/RouterBase.php +++ b/src/Pecee/SimpleRouter/RouterBase.php @@ -167,11 +167,11 @@ class RouterBase { $url = $route->getUrl(); - if(($route instanceof RouterController || $route instanceof RouterRessource) && $method !== null) { + if(($route instanceof RouterController || $route instanceof RouterResource) && $method !== null) { $url .= $method; } - if($route instanceof RouterController || $route instanceof RouterRessource) { + if($route instanceof RouterController || $route instanceof RouterResource) { if(count($parameters)) { $url .= join('/', $parameters); } @@ -217,9 +217,14 @@ class RouterBase { /* @var $route RouterRoute */ foreach($this->controllerUrlMap as $route) { + // Check an alias exist, if the matches - use it + if($route instanceof RouterRoute && strtolower($route->getAlias()) === strtolower($controller)) { + return $this->processUrl($route, $route->getMethod(), $parameters, $getParams); + } + if($route instanceof RouterRoute && !is_callable($route->getCallback()) && stripos($route->getCallback(), '@') !== false) { $c = $route->getCallback(); - } else if($route instanceof RouterController || $route instanceof RouterRessource) { + } else if($route instanceof RouterController || $route instanceof RouterResource) { $c = $route->getController(); } @@ -234,7 +239,7 @@ class RouterBase { foreach($this->controllerUrlMap as $route) { if($route instanceof RouterRoute && !is_callable($route->getCallback()) && stripos($route->getCallback(), '@') !== false) { $c = $route->getClass(); - } else if($route instanceof RouterController || $route instanceof RouterRessource) { + } else if($route instanceof RouterController || $route instanceof RouterResource) { $c = $route->getController(); } diff --git a/src/Pecee/SimpleRouter/RouterResource.php b/src/Pecee/SimpleRouter/RouterResource.php new file mode 100644 index 0000000..071ff40 --- /dev/null +++ b/src/Pecee/SimpleRouter/RouterResource.php @@ -0,0 +1,155 @@ +url = $url; + $this->controller = $controller; + $this->postMethod = strtolower(($_SERVER['REQUEST_METHOD'] != 'GET') ? 'post' : 'get'); + } + + public function renderRoute(Request $request) { + // Load middleware + $this->loadMiddleware($request); + + if(is_object($this->getCallback()) && is_callable($this->getCallback())) { + // When the callback is a function + call_user_func_array($this->getCallback(), $this->getParameters()); + } else { + // When the callback is a method + $controller = explode('@', $this->getCallback()); + $className = $this->getNamespace() . '\\' . $controller[0]; + $class = $this->loadClass($className); + $method = strtolower($controller[1]); + + if (!method_exists($class, $method)) { + throw new RouterException(sprintf('Method %s does not exist in class %s', $method, $className), 404); + } + + call_user_func_array(array($class, $method), $this->getParameters()); + + return $class; + } + + return null; + } + + protected function call($method, $parameters) { + $this->setCallback($this->controller . '@' . $method); + $this->parameters = $parameters; + return $this; + } + + public function matchRoute(Request $request) { + $url = parse_url($request->getUri()); + $url = rtrim($url['path'], '/') . '/'; + + if(strtolower($url) == strtolower($this->url) || stripos($url, $this->url) === 0) { + $url = rtrim($url, '/'); + + $strippedUrl = trim(substr($url, strlen($this->url)), '/'); + $path = explode('/', $strippedUrl); + + $args = $path; + $action = ''; + + if(count($args)) { + $action = $args[0]; + array_shift($args); + } + + if (count($path)) { + + // Delete + if($request->getMethod() === self::REQUEST_TYPE_DELETE && $this->postMethod === self::REQUEST_TYPE_POST) { + return $this->call('destroy', $args); + } + + // Update + if(in_array($request->getMethod(), array('put', 'patch')) && $this->postMethod === self::REQUEST_TYPE_POST) { + return $this->call('update', array_merge(array($action), $args)); + } + + // Edit + if(isset($args[0]) && strtolower($args[0]) === 'edit' && $this->postMethod === self::REQUEST_TYPE_GET) { + return $this->call('edit', array_merge(array($action), array_slice($args, 1))); + } + + // Create + if(strtolower($action) === 'create' && $request->getMethod() === self::REQUEST_TYPE_GET) { + return $this->call('create', $args); + } + + // Save + if($this->postMethod === self::REQUEST_TYPE_POST) { + return $this->call('store', $args); + } + + // Show + if($action && $this->postMethod === self::REQUEST_TYPE_GET) { + return $this->call('show', array_merge(array($action), $args)); + } + + // Index + return $this->call('index', $args); + } + } + + return null; + } + + /** + * @return string + */ + public function getUrl() { + return $this->url; + } + + /** + * @param string $url + */ + public function setUrl($url) { + $url = rtrim($url, '/') . '/'; + $this->url = $url; + } + + /** + * @return string + */ + public function getController() { + return $this->controller; + } + + /** + * @param string $controller + */ + public function setController($controller) { + $this->controller = $controller; + } + + /** + * @return string + */ + public function getMethod() { + return $this->method; + } + + /** + * @param string $method + */ + public function setMethod($method) { + $this->method = $method; + } + +} \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/RouterRoute.php b/src/Pecee/SimpleRouter/RouterRoute.php index 162ce03..a5d012a 100644 --- a/src/Pecee/SimpleRouter/RouterRoute.php +++ b/src/Pecee/SimpleRouter/RouterRoute.php @@ -136,32 +136,6 @@ class RouterRoute extends RouterEntry { return $this; } - /** - * @param array $aliases - * @return self - */ - public function setAliases(array $aliases) { - $this->aliases = $aliases; - return $this; - } - - /** - * Add alias - * - * @param $alias - * @return self - */ - public function addAlias($alias) { - $arr = $this->aliases; - $arr[] = $alias; - $this->aliases = $arr; - return $this; - } - - public function getAliases() { - $this->aliases; - } - /** * Add request type * @@ -184,4 +158,34 @@ class RouterRoute extends RouterEntry { public function getRequestTypes() { return $this->requestTypes; } + + /** + * Get alias for the url which can be used when getting the url route. + * @return string + */ + public function getAlias(){ + return $this->alias; + } + + /** + * Set the url alias for easier getting the url route. + * @param string $alias + * @return self + */ + public function setAlias($alias){ + $this->alias = $alias; + return $this; + } + + public function setSettings($settings) { + + // Change as to alias + if(isset($settings{'as'})) { + $this->setAlias($settings['as']); + } + + return parent::setSettings($settings); + } + + } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/SimpleRouter.php b/src/Pecee/SimpleRouter/SimpleRouter.php index e99671d..8820c17 100644 --- a/src/Pecee/SimpleRouter/SimpleRouter.php +++ b/src/Pecee/SimpleRouter/SimpleRouter.php @@ -17,8 +17,9 @@ class SimpleRouter { $router->routeRequest(); } - public static function get($url, $callback) { + public static function get($url, $callback, array $settings = null) { $route = new RouterRoute($url, $callback); + $route->addSettings($settings); $route->addRequestType(RouterRoute::REQUEST_TYPE_GET); $router = RouterBase::getInstance(); @@ -27,8 +28,9 @@ class SimpleRouter { return $route; } - public static function post($url, $callback) { + public static function post($url, $callback, array $settings = null) { $route = new RouterRoute($url, $callback); + $route->addSettings($settings); $route->addRequestType(RouterRoute::REQUEST_TYPE_POST); $router = RouterBase::getInstance(); @@ -37,8 +39,9 @@ class SimpleRouter { return $route; } - public static function put($url, $callback) { + public static function put($url, $callback, array $settings = null) { $route = new RouterRoute($url, $callback); + $route->addSettings($settings); $route->addRequestType(RouterRoute::REQUEST_TYPE_PUT); $router = RouterBase::getInstance(); @@ -47,8 +50,9 @@ class SimpleRouter { return $route; } - public static function delete($url, $callback) { + public static function delete($url, $callback, array $settings = null) { $route = new RouterRoute($url, $callback); + $route->addSettings($settings); $route->addRequestType(RouterRoute::REQUEST_TYPE_DELETE); $router = RouterBase::getInstance(); @@ -71,8 +75,9 @@ class SimpleRouter { return $group; } - public static function match(array $requestTypes, $url, $callback) { + public static function match(array $requestTypes, $url, $callback, array $settings = null) { $route = new RouterRoute($url, $callback); + $route->addSettings($settings); foreach($requestTypes as $requestType) { $route->addRequestType($requestType); } @@ -83,24 +88,27 @@ class SimpleRouter { return $route; } - public static function all($url, $callback) { + public static function all($url, $callback, array $settings = null) { $route = new RouterRoute($url, $callback); + $route->addSettings($settings); $router = RouterBase::getInstance(); $router->addRoute($route); return $route; } - public static function controller($url, $controller) { + public static function controller($url, $controller, array $settings = null) { $route = new RouterController($url, $controller); + $route->addSettings($settings); $router = RouterBase::getInstance(); $router->addRoute($route); return $route; } - public static function ressource($url, $controller) { - $route = new RouterRessource($url, $controller); + public static function resource($url, $controller, array $settings = null) { + $route = new RouterResource($url, $controller); + $route->addSettings($settings); $router = RouterBase::getInstance(); $router->addRoute($route); From 8db60f85a1f0bccf725dd93768318d05f68a0c74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sessing=C3=B8?= Date: Wed, 21 Oct 2015 00:30:00 +0200 Subject: [PATCH 4/5] [TASK] Updated documentation. --- README.md | 3 +- src/Pecee/SimpleRouter/RouterRessource.php | 155 --------------------- 2 files changed, 1 insertion(+), 157 deletions(-) delete mode 100644 src/Pecee/SimpleRouter/RouterRessource.php diff --git a/README.md b/README.md index ecb598c..c454ebe 100644 --- a/README.md +++ b/README.md @@ -23,8 +23,7 @@ Add the latest version pf Simple PHP Router to your ```composer.json``` - Named Routes - Sub-Domain Routing - CSRF Protection -- Optinal/required parameters -- Aliases for ```RouterRoute``` +- Optional/required parameters ### Known issues diff --git a/src/Pecee/SimpleRouter/RouterRessource.php b/src/Pecee/SimpleRouter/RouterRessource.php deleted file mode 100644 index e3e929e..0000000 --- a/src/Pecee/SimpleRouter/RouterRessource.php +++ /dev/null @@ -1,155 +0,0 @@ -url = $url; - $this->controller = $controller; - $this->postMethod = strtolower(($_SERVER['REQUEST_METHOD'] != 'GET') ? 'post' : 'get'); - } - - public function renderRoute(Request $request) { - // Load middleware - $this->loadMiddleware($request); - - if(is_object($this->getCallback()) && is_callable($this->getCallback())) { - // When the callback is a function - call_user_func_array($this->getCallback(), $this->getParameters()); - } else { - // When the callback is a method - $controller = explode('@', $this->getCallback()); - $className = $this->getNamespace() . '\\' . $controller[0]; - $class = $this->loadClass($className); - $method = strtolower($controller[1]); - - if (!method_exists($class, $method)) { - throw new RouterException(sprintf('Method %s does not exist in class %s', $method, $className), 404); - } - - call_user_func_array(array($class, $method), $this->getParameters()); - - return $class; - } - - return null; - } - - protected function call($method, $parameters) { - $this->setCallback($this->controller . '@' . $method); - $this->parameters = $parameters; - return $this; - } - - public function matchRoute(Request $request) { - $url = parse_url($request->getUri()); - $url = rtrim($url['path'], '/') . '/'; - - if(strtolower($url) == strtolower($this->url) || stripos($url, $this->url) === 0) { - $url = rtrim($url, '/'); - - $strippedUrl = trim(substr($url, strlen($this->url)), '/'); - $path = explode('/', $strippedUrl); - - $args = $path; - $action = ''; - - if(count($args)) { - $action = $args[0]; - array_shift($args); - } - - if (count($path)) { - - // Delete - if($request->getMethod() === self::REQUEST_TYPE_DELETE && $this->postMethod === self::REQUEST_TYPE_POST) { - return $this->call('destroy', $args); - } - - // Update - if(in_array($request->getMethod(), array('put', 'patch')) && $this->postMethod === self::REQUEST_TYPE_POST) { - return $this->call('update', array_merge(array($action), $args)); - } - - // Edit - if(isset($args[0]) && strtolower($args[0]) === 'edit' && $this->postMethod === self::REQUEST_TYPE_GET) { - return $this->call('edit', array_merge(array($action), array_slice($args, 1))); - } - - // Create - if(strtolower($action) === 'create' && $request->getMethod() === self::REQUEST_TYPE_GET) { - return $this->call('create', $args); - } - - // Save - if($this->postMethod === self::REQUEST_TYPE_POST) { - return $this->call('store', $args); - } - - // Show - if($action && $this->postMethod === self::REQUEST_TYPE_GET) { - return $this->call('show', array_merge(array($action), $args)); - } - - // Index - return $this->call('index', $args); - } - } - - return null; - } - - /** - * @return string - */ - public function getUrl() { - return $this->url; - } - - /** - * @param string $url - */ - public function setUrl($url) { - $url = rtrim($url, '/') . '/'; - $this->url = $url; - } - - /** - * @return string - */ - public function getController() { - return $this->controller; - } - - /** - * @param string $controller - */ - public function setController($controller) { - $this->controller = $controller; - } - - /** - * @return string - */ - public function getMethod() { - return $this->method; - } - - /** - * @param string $method - */ - public function setMethod($method) { - $this->method = $method; - } - -} \ No newline at end of file From 58e4eb85bbdcfdeb98747fb910c314053ec7cac1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sessing=C3=B8?= Date: Wed, 21 Oct 2015 10:14:21 +0200 Subject: [PATCH 5/5] =?UTF-8?q?[BUGFIX]=C2=A0Fixed=20method=20not=20allowe?= =?UTF-8?q?d=20exception.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Method request type are now checked on all classes in the RouterBase class. --- README.md | 6 +- src/Pecee/SimpleRouter/RouterBase.php | 16 ++++ src/Pecee/SimpleRouter/RouterEntry.php | 31 ++++++- src/Pecee/SimpleRouter/RouterGroup.php | 4 +- src/Pecee/SimpleRouter/RouterRoute.php | 117 +++++++++--------------- src/Pecee/SimpleRouter/SimpleRouter.php | 14 ++- 6 files changed, 99 insertions(+), 89 deletions(-) diff --git a/README.md b/README.md index d2558a6..cc74051 100644 --- a/README.md +++ b/README.md @@ -25,10 +25,6 @@ Add the latest version pf Simple PHP Router to your ```composer.json``` - CSRF Protection - Optional/required parameters -### Known issues - -- Posting invalid/unsupported request-type throws 404 instead of "method not allowed" exception, unless defined within a group. - ## Initialising the router In your ```index.php``` require your ```routes.php``` and call the ```routeRequest()``` method when all your custom routes has been loaded. This will trigger and do the actual routing of the requests. @@ -197,7 +193,7 @@ The router can be easily extended to customize your needs. ## The MIT License (MIT) -Copyright (c) 2015 Simon Sessingø / simple-php-router +Copyright (c) 2015 Simon Sessing� / simple-php-router Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/src/Pecee/SimpleRouter/RouterBase.php b/src/Pecee/SimpleRouter/RouterBase.php index b5a69e3..b5cc3d0 100644 --- a/src/Pecee/SimpleRouter/RouterBase.php +++ b/src/Pecee/SimpleRouter/RouterBase.php @@ -94,16 +94,32 @@ class RouterBase { return strcmp($b->getUrl(), $a->getUrl()); }); + $routeNotAllowed = false; + + /* @var $route RouterEntry */ foreach($this->controllerUrlMap as $route) { $routeMatch = $route->matchRoute($this->request); + if($routeMatch && !($routeMatch instanceof RouterGroup)) { + + if(count($route->getRequestMethods()) && !in_array($this->request->getMethod(), $route->getRequestMethods())) { + $routeNotAllowed = true; + continue; + } + + $routeNotAllowed = false; + $this->loadedRoute = $routeMatch; $routeMatch->renderRoute($this->request); break; } } + if($routeNotAllowed) { + throw new RouterException('Route or method not allowed', 403); + } + if(!$this->loadedRoute) { throw new RouterException(sprintf('Route not found: %s', $this->request->getUri()), 404); } diff --git a/src/Pecee/SimpleRouter/RouterEntry.php b/src/Pecee/SimpleRouter/RouterEntry.php index 32085aa..03a88fe 100644 --- a/src/Pecee/SimpleRouter/RouterEntry.php +++ b/src/Pecee/SimpleRouter/RouterEntry.php @@ -27,6 +27,7 @@ abstract class RouterEntry { public function __construct() { $this->settings = array(); + $this->settings['requestMethods'] = array(); $this->parameters = array(); $this->parametersRegex = array(); } @@ -193,8 +194,10 @@ abstract class RouterEntry { * @param array $settings * @return self */ - public function addSettings(array $settings) { - $this->settings = array_merge($this->settings, $settings); + public function addSettings(array $settings = null) { + if(is_array($settings)) { + $this->settings = array_merge($this->settings, $settings); + } return $this; } @@ -280,6 +283,30 @@ abstract class RouterEntry { return null; } + /** + * Set allowed request methods + * + * @param array $methods + * @return self $this + */ + public function setRequestMethods(array $methods) { + $this->settings['requestMethods'] = $methods; + return $this; + } + + /** + * Get allowed requeset methods + * + * @return array + */ + public function getRequestMethods() { + if(!isset($this->settings['requestMethods']) || isset($this->settings['requestMethods']) && !is_array($this->settings['requestMethods'])) { + $value = isset($this->settings['requestMethods']) ? $this->settings['requestMethods'] : null; + return array($value); + } + return $this->settings['requestMethods']; + } + abstract function matchRoute(Request $request); } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/RouterGroup.php b/src/Pecee/SimpleRouter/RouterGroup.php index 49de9b5..1537a71 100644 --- a/src/Pecee/SimpleRouter/RouterGroup.php +++ b/src/Pecee/SimpleRouter/RouterGroup.php @@ -19,9 +19,9 @@ class RouterGroup extends RouterEntry { if($this->method) { if(is_array($this->method)) { - $hasAccess = (in_array($request->getMethod(), $this->method)); + $hasAccess = (in_array($request->getMethod(), $this->getRequestMethods())); } else { - $hasAccess = strtolower($this->method) == strtolower($request->getMethod()); + $hasAccess = strtolower($this->getRequestMethods()) == strtolower($request->getMethod()); } } diff --git a/src/Pecee/SimpleRouter/RouterRoute.php b/src/Pecee/SimpleRouter/RouterRoute.php index a5d012a..029c242 100644 --- a/src/Pecee/SimpleRouter/RouterRoute.php +++ b/src/Pecee/SimpleRouter/RouterRoute.php @@ -9,7 +9,6 @@ class RouterRoute extends RouterEntry { const PARAMETERS_REGEX_MATCH = '{([A-Za-z\-\_]*?)}'; protected $url; - protected $requestTypes; public function __construct($url, $callback) { parent::__construct(); @@ -17,7 +16,6 @@ class RouterRoute extends RouterEntry { $this->setCallback($callback); $this->settings['aliases'] = array(); - $this->requestTypes = array(); } protected function parseParameters($url, $multiple = false, $regex = self::PARAMETERS_REGEX_MATCH) { @@ -39,71 +37,69 @@ class RouterRoute extends RouterEntry { public function matchRoute(Request $request) { // Check if request method is allowed - if(count($this->requestTypes) === 0 || in_array($request->getMethod(), $this->requestTypes)) { - $url = parse_url($request->getUri()); - $url = $url['path']; + $url = parse_url($request->getUri()); + $url = $url['path']; - $route = $this->url; + $route = $this->url; - $routeMatch = preg_replace('/'.self::PARAMETERS_REGEX_MATCH.'/is', '', $route); + $routeMatch = preg_replace('/'.self::PARAMETERS_REGEX_MATCH.'/is', '', $route); - // Check if url parameter count matches - if(stripos($url, $routeMatch) === 0) { + // Check if url parameter count matches + if(stripos($url, $routeMatch) === 0) { - $matches = true; + $matches = true; - if($this->regexMatch) { - $parameters = $this->parseParameters($url, true, $this->regexMatch); - - // If regex doesn't match, make sure to return an array - if(!is_array($parameters)) { - $parameters = array(); - } - - } else { - - $url = explode('/', $url); - $route = explode('/', $route); + if($this->regexMatch) { + $parameters = $this->parseParameters($url, true, $this->regexMatch); + // If regex doesn't match, make sure to return an array + if(!is_array($parameters)) { $parameters = array(); + } - // Check if url matches - foreach ($route as $i => $path) { - $parameter = $this->parseParameters($path, false); + } else { - // Check if parameter of path matches, otherwise quit.. - if (is_null($parameter) && strtolower($path) != strtolower($url[$i])) { - $matches = false; - break; - } + $url = explode('/', $url); + $route = explode('/', $route); - // Save parameter if we have one - if ($parameter) { - $parameterValue = $url[$i]; - $regex = (isset($this->parametersRegex[$parameter]) ? $this->parametersRegex[$parameter] : null); + $parameters = array(); - if ($regex !== null) { - // Use the regular expression rule provided to filter the value - $matches = array(); - preg_match('/' . $regex . '/is', $url[$i], $matches); + // Check if url matches + foreach ($route as $i => $path) { + $parameter = $this->parseParameters($path, false); - if (count($matches)) { - $parameterValue = $matches[0]; - } + // Check if parameter of path matches, otherwise quit.. + if (is_null($parameter) && strtolower($path) != strtolower($url[$i])) { + $matches = false; + break; + } + + // Save parameter if we have one + if ($parameter) { + $parameterValue = $url[$i]; + $regex = (isset($this->parametersRegex[$parameter]) ? $this->parametersRegex[$parameter] : null); + + if ($regex !== null) { + // Use the regular expression rule provided to filter the value + $matches = array(); + preg_match('/' . $regex . '/is', $url[$i], $matches); + + if (count($matches)) { + $parameterValue = $matches[0]; } - - // Add parameter value - $parameters[$parameter] = $parameterValue; } + + // Add parameter value + $parameters[$parameter] = $parameterValue; } } + } - // This route matches - if($matches) { - $this->parameters = $parameters; - return $this; - } + // This route matches + if($matches) { + $this->parameters = $parameters; + return $this; } } @@ -136,29 +132,6 @@ class RouterRoute extends RouterEntry { return $this; } - /** - * Add request type - * - * @param $type - * @return self - * @throws RouterException - */ - public function addRequestType($type) { - if(!in_array($type, self::$allowedRequestTypes)) { - throw new RouterException('Invalid request method: ' . $type); - } - - $this->requestTypes[] = $type; - return $this; - } - - /** - * @return mixed - */ - public function getRequestTypes() { - return $this->requestTypes; - } - /** * Get alias for the url which can be used when getting the url route. * @return string diff --git a/src/Pecee/SimpleRouter/SimpleRouter.php b/src/Pecee/SimpleRouter/SimpleRouter.php index 8820c17..99b050a 100644 --- a/src/Pecee/SimpleRouter/SimpleRouter.php +++ b/src/Pecee/SimpleRouter/SimpleRouter.php @@ -20,7 +20,7 @@ class SimpleRouter { public static function get($url, $callback, array $settings = null) { $route = new RouterRoute($url, $callback); $route->addSettings($settings); - $route->addRequestType(RouterRoute::REQUEST_TYPE_GET); + $route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_GET)); $router = RouterBase::getInstance(); $router->addRoute($route); @@ -31,7 +31,7 @@ class SimpleRouter { public static function post($url, $callback, array $settings = null) { $route = new RouterRoute($url, $callback); $route->addSettings($settings); - $route->addRequestType(RouterRoute::REQUEST_TYPE_POST); + $route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_POST)); $router = RouterBase::getInstance(); $router->addRoute($route); @@ -42,7 +42,7 @@ class SimpleRouter { public static function put($url, $callback, array $settings = null) { $route = new RouterRoute($url, $callback); $route->addSettings($settings); - $route->addRequestType(RouterRoute::REQUEST_TYPE_PUT); + $route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_PUT)); $router = RouterBase::getInstance(); $router->addRoute($route); @@ -53,7 +53,7 @@ class SimpleRouter { public static function delete($url, $callback, array $settings = null) { $route = new RouterRoute($url, $callback); $route->addSettings($settings); - $route->addRequestType(RouterRoute::REQUEST_TYPE_DELETE); + $route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_DELETE)); $router = RouterBase::getInstance(); $router->addRoute($route); @@ -75,12 +75,10 @@ class SimpleRouter { return $group; } - public static function match(array $requestTypes, $url, $callback, array $settings = null) { + public static function match(array $requestMethods, $url, $callback, array $settings = null) { $route = new RouterRoute($url, $callback); + $route->setRequestMethods($requestMethods); $route->addSettings($settings); - foreach($requestTypes as $requestType) { - $route->addRequestType($requestType); - } $router = RouterBase::getInstance(); $router->addRoute($route);