Compare commits

..

24 Commits

Author SHA1 Message Date
Simon Sessingø f2fd5261c1 Merge pull request #34 from skipperbent/development
[BUGFIX] Fixed parameters on custom regex match.
2015-11-21 20:34:45 +01:00
Simon Sessingø 02de9572fa [BUGFIX] Fixed parameters on custom regex match. 2015-11-21 20:31:44 +01:00
Simon Sessingø e2a618fadd Merge pull request #33 from skipperbent/development
[BUGFIX] Fixed optinal parameters not availible when getting route.
2015-11-21 19:44:19 +01:00
Simon Sessingø e5700477e0 [BUGFIX] Fixed optinal parameters not availible when getting route.
[BUGFIX] Fixed optinal parameters not availible in url.
2015-11-21 19:43:23 +01:00
Simon Sessingø 750817e451 Merge pull request #32 from skipperbent/development
[FEATURE] Optimised route matching, added optional parameters.
2015-11-21 19:36:09 +01:00
Simon Sessingø 3b4954821a [FEATURE] Optimised route matching, added optional parameters.
- Optimised route matching. This should be way more officient and also
  seems to fix issues with getting the current route using the getRoute class.

- Added support for optional routes, for example: {id?}.

- Updated documentation to reflect new changes.
2015-11-21 19:31:06 +01:00
Simon Sessingø 5c36e9c652 Merge pull request #31 from skipperbent/development
[BUGFIX] Fixed support for urls like /path/{param}/path
2015-11-20 07:18:31 +01:00
Simon Sessingø b930c06683 [BUGFIX] Fixed support for urls like /path/{param}/path 2015-11-20 07:17:49 +01:00
Simon Sessingø 0f8bba7c32 Merge pull request #30 from skipperbent/development
[FEATURE] Added getIsSecure method to Request class.
2015-11-18 19:20:11 +01:00
Simon Sessingø 19dc295199 [FEATURE] Added getIsSecure method to Request class. 2015-11-18 19:19:15 +01:00
Simon Sessingø c93e0f2ce6 Merge pull request #29 from skipperbent/development
[BUGFIX] Group will now always be rendered no matter of what prefix is.
2015-11-17 00:56:28 +01:00
Simon Sessingø 388c027d04 [BUGFIX] Group will now always be rendered no matter of what prefix is. 2015-11-17 00:55:59 +01:00
Simon Sessingø 2c8e65f25b Merge pull request #28 from skipperbent/development
[BUGFIX] Fixed routeMatch in RouterEntry not matching routes with multiple  arguments.
2015-11-14 22:22:00 +01:00
Simon Sessingø eb93584d85 [BUGFIX] Fixed routeMatch in RouterEntry not matching routes with multiple
arguments.
2015-11-14 22:21:11 +01:00
Simon Sessingø bd5d17b6fb Merge pull request #27 from skipperbent/development
[TASK] Removed Pecee folder.
2015-11-02 08:09:43 +01:00
Simon Sessingø 7c0ac390fd [TASK] Undid changes to composer.json 2015-11-02 08:09:13 +01:00
Simon Sessingø 3fc81b6492 [TASK] Readded Pecee folder. 2015-11-02 08:08:49 +01:00
Simon Sessingø b400b86322 [TASK] Removed Pecee folder. 2015-11-02 08:06:49 +01:00
Simon Sessingø 1d338e9aa9 Merge pull request #26 from skipperbent/development
[OPTIMISATION] Fixed Group only loading middleware when initialised.
2015-11-01 10:24:51 +01:00
Simon Sessingø 889ceaa37f [OPTIMISATION] Fixed Group only loading middleware when initialised. 2015-11-01 10:24:05 +01:00
Simon Sessingø 363338c92f Merge pull request #25 from skipperbent/development
Development
2015-11-01 10:14:57 +01:00
Simon Sessingø 3dd9dba029 [FEATURE] All headers in Request class now has lowercased keys. 2015-11-01 10:13:00 +01:00
Simon Sessingø be277f276f [FEATURE] Added support for patch.
- Put now also allow patch request types.
2015-11-01 09:21:47 +01:00
Simon Sessingø f215eaa9cf [BUGFIX] Bugfixes and optimisations
- Fixed support for multiple middlewares using array.
- Fixed match and parameters-match not not being merged when used on group.
2015-11-01 09:11:17 +01:00
7 changed files with 136 additions and 124 deletions
+8 -6
View File
@@ -28,12 +28,12 @@ Add the latest version pf Simple PHP Router to your ```composer.json```
- Namespaces.
- Route prefixes.
- CSRF protection.
- Optional parameters
### Features currently "in-the-works"
- Global Constraints
- Sub-Domain Routing
- Optional parameters
- Sub-domain routing
## Initialising the router
@@ -74,8 +74,10 @@ SimpleRouter::group(['prefix' => 'v1', 'middleware' => '\MyWebsite\Middleware\So
SimpleRouter::group(['prefix' => 'services'], function() {
SimpleRouter::get('/answers/{id}', 'ControllerAnswers@show')
->where(['id' => '[0-9]+');
SimpleRouter::get('/answers/{id}', 'ControllerAnswers@show')->where(['id' => '[0-9]+');
// Optional parameter
SimpleRouter::get('/answers/{id?}', 'ControllerAnswers@show');
/**
* This example will route url when matching the regular expression to the method.
@@ -83,7 +85,7 @@ SimpleRouter::group(['prefix' => 'v1', 'middleware' => '\MyWebsite\Middleware\So
*/
SimpleRouter::all('/ajax', 'ControllerAjax@process')->match('ajax\\/([A-Za-z0-9\\/]+)');
// Resetful resource
// Restful resource
SimpleRouter::resource('/rest', 'ControllerRessource');
// Load the entire controller (where url matches method names - getIndex(), postIndex() etc)
@@ -251,7 +253,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
+6 -2
View File
@@ -27,7 +27,11 @@ class Request {
$this->host = $_SERVER['HTTP_HOST'];
$this->uri = $_SERVER['REQUEST_URI'];
$this->method = (isset($_POST['_method'])) ? strtolower($_POST['_method']) : strtolower($_SERVER['REQUEST_METHOD']);
$this->headers = getallheaders();
$this->headers = array_change_key_case(getallheaders(), CASE_LOWER);
}
public function getIsSecure() {
return isset($_SERVER['HTTPS']) ? true : (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] === 443);
}
/**
@@ -105,7 +109,7 @@ class Request {
* @return string|null
*/
public function getHeader($name) {
return (isset($this->headers[$name])) ? $this->headers[$name] : null;
return (isset($this->headers[strtolower($name)])) ? $this->headers[strtolower($name)] : null;
}
/**
+2 -1
View File
@@ -58,6 +58,7 @@ class RouterBase {
$newPrefixes = $prefixes;
$mergedSettings = array_merge($settings, $route->getMergeableSettings());
if($route->getPrefix()) {
array_push($newPrefixes, rtrim($route->getPrefix(), '/'));
}
@@ -223,7 +224,7 @@ class RouterBase {
$i = 0;
foreach($params as $param => $value) {
$value = (isset($parameters[$param])) ? $parameters[$param] : $value;
$url = str_ireplace('{' . $param. '}', $value, $url);
$url = str_ireplace(array('{' . $param. '}', '{' . $param. '?}'), $value, $url);
$i++;
}
} else {
+22 -10
View File
@@ -10,26 +10,26 @@ abstract class RouterEntry {
const REQUEST_TYPE_POST = 'post';
const REQUEST_TYPE_GET = 'get';
const REQUEST_TYPE_PUT = 'put';
const REQUEST_TYPE_PATCH = 'patch';
const REQUEST_TYPE_DELETE = 'delete';
public static $allowedRequestTypes = array(
self::REQUEST_TYPE_DELETE,
self::REQUEST_TYPE_GET,
self::REQUEST_TYPE_POST,
self::REQUEST_TYPE_PUT
self::REQUEST_TYPE_PUT,
self::REQUEST_TYPE_PATCH
);
protected $settings;
protected $callback;
protected $parameters;
protected $parametersRegex;
protected $regexMatch;
public function __construct() {
$this->settings = array();
$this->settings['requestMethods'] = array();
$this->settings['parametersRegex'] = array();
$this->parameters = array();
$this->parametersRegex = array();
}
/**
@@ -245,13 +245,25 @@ abstract class RouterEntry {
public function loadMiddleware(Request $request) {
if($this->getMiddleware()) {
$middleware = $this->loadClass($this->getMiddleware());
if (!($middleware instanceof IMiddleware)) {
throw new RouterException($this->getMiddleware() . ' must be instance of Middleware');
}
if(is_array($this->getMiddleware())) {
foreach($this->getMiddleware() as $middleware) {
$middleware = $this->loadClass($middleware);
if (!($middleware instanceof IMiddleware)) {
throw new RouterException($middleware . ' must be instance of Middleware');
}
/* @var $class Middleware */
$middleware->handle($request);
/* @var $class Middleware */
$middleware->handle($request);
}
} else {
$middleware = $this->loadClass($this->getMiddleware());
if (!($middleware instanceof IMiddleware)) {
throw new RouterException($this->getMiddleware() . ' must be instance of Middleware');
}
/* @var $class Middleware */
$middleware->handle($request);
}
}
}
+11 -20
View File
@@ -12,30 +12,21 @@ class RouterGroup extends RouterEntry {
public function renderRoute(Request $request) {
// Check if request method is allowed
$hasAccess = (!$this->method);
if(trim($this->prefix) === '' || strtolower($request->getUri()) == strtolower($this->prefix) || stripos($request->getUri(), $this->prefix) === 0) {
$hasAccess = (!$this->method);
if($this->method) {
if(is_array($this->method)) {
$hasAccess = (in_array($request->getMethod(), $this->getRequestMethods()));
} else {
$hasAccess = strtolower($this->getRequestMethods()) == strtolower($request->getMethod());
}
if($this->method) {
if(is_array($this->method)) {
$hasAccess = (in_array($request->getMethod(), $this->getRequestMethods()));
} else {
$hasAccess = strtolower($this->getRequestMethods()) == strtolower($request->getMethod());
}
if(!$hasAccess) {
throw new RouterException('Method not allowed');
}
$this->loadMiddleware($request);
return parent::renderRoute($request);
}
// No match here, move on...
return null;
if(!$hasAccess) {
throw new RouterException('Method not allowed');
}
return parent::renderRoute($request);
}
public function matchRoute(Request $request) {
+85 -83
View File
@@ -6,7 +6,7 @@ use Pecee\Http\Request;
class RouterRoute extends RouterEntry {
const PARAMETERS_REGEX_MATCH = '{([A-Za-z\-\_]*?)}';
const PARAMETERS_REGEX_MATCH = '{([A-Za-z\-\_]*?\?{0,1})}';
protected $url;
@@ -18,95 +18,93 @@ class RouterRoute extends RouterEntry {
$this->settings['aliases'] = array();
}
protected function parseParameters($url, $multiple = false, $regex = self::PARAMETERS_REGEX_MATCH) {
$url = rtrim($url, '/');
$parameters = array();
if($multiple) {
preg_match_all('/'.$regex.'/is', $url, $parameters);
} else {
preg_match('/'.$regex.'/is', $url, $parameters);
}
if(isset($parameters[1]) && count($parameters[1]) > 0) {
return $parameters[1];
}
return null;
}
public function matchRoute(Request $request) {
// Check if request method is allowed
$url = parse_url($request->getUri());
$url = $url['path'];
$url = rtrim($url['path'], '/') . '/';
$route = $this->url;
$routeMatch = preg_replace('/'.self::PARAMETERS_REGEX_MATCH.'/is', '', $route);
// Check if url parameter count matches
if(stripos($url, $routeMatch) === 0) {
$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 {
$matches = (count(explode('/', rtrim($url, '/'))) == count(explode('/', rtrim($route, '/'))));
$url = explode('/', $url);
$route = explode('/', rtrim($route, '/'));
$parameters = array();
// Check if url matches
foreach ($route as $i => $path) {
$parameter = $this->parseParameters($path, false);
// 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, if it doesn't exist - replace it with null value
$parameters[$parameter] = ($parameterValue === '') ? null : $parameterValue;
}
}
}
// This route matches
if($matches) {
$this->parameters = $parameters;
// Match on custom defined regular expression
if($this->regexMatch) {
$parameters = array();
if(preg_match('/('.$this->regexMatch.')/is', $url, $parameters)) {
$this->parameters = (!is_array($parameters[0]) ? array($parameters[0]) : $parameters[0]);
return $this;
}
}
// No match here, move on...
// Make regular expression based on route
$route = rtrim($this->url, '/') . '/';
$parameterNames = array();
$regex = '';
$lastCharacter = '';
$isParameter = false;
$parameter = '';
for($i = 0; $i < strlen($route); $i++) {
$character = $route[$i];
// Skip "/" if we are at the end of a parameter
if($lastCharacter === '}' && $character === '/') {
$lastCharacter = $character;
continue;
}
if($character === '{') {
// Remove "/" and "\" from regex
if(substr($regex, strlen($regex)-1) === '/') {
$regex = substr($regex, 0, strlen($regex) - 2);
}
$isParameter = true;
} elseif($isParameter && $character === '}') {
// Check for optional parameter
if($lastCharacter === '?') {
$parameter = substr($parameter, 0, strlen($parameter)-1);
$regex .= '(?:(?:\/(?P<'.$parameter.'>[0-9]*?)){0,1}\\/)';
} else {
// Use custom parameter regex if it exists
$parameterRegex = '[0-9]*?';
if(is_array($this->parametersRegex) && isset($this->parametersRegex[$parameter])) {
$parameterRegex = $this->parametersRegex[$parameter];
}
$regex .= '(?:\\/(?P<' . $parameter . '>'. $parameterRegex .')\\/)';
}
$parameterNames[] = $parameter;
$parameter = '';
$isParameter = false;
} elseif($isParameter) {
$parameter .= $character;
} elseif($character === '/') {
$regex .= '\\' . $character;
} else {
$regex .= $character;
}
$lastCharacter = $character;
}
$parameterValues = array();
if(preg_match('/^'.$regex.'$/is', $url, $parameterValues)) {
$parameters = array();
if(count($parameterNames)) {
foreach($parameterNames as $name) {
$parameters[$name] = isset($parameterValues[$name]) ? $parameterValues[$name] : null;
}
}
$this->parameters = $parameters;
return $this;
}
return null;
}
@@ -123,7 +121,11 @@ class RouterRoute extends RouterEntry {
*/
public function setUrl($url) {
$parameters = $this->parseParameters($url, true);
$parameters = array();
preg_match_all('/'.self::PARAMETERS_REGEX_MATCH.'/is', $url, $parameters);
$parameters = $parameters[1];
if($parameters !== null) {
foreach($parameters as $param) {
+2 -2
View File
@@ -4,7 +4,7 @@
* ---------------------------
* Router helper class
* ---------------------------
* This class is added so calls can be made staticly like Router::get() making the code look more pretty.
* This class is added so calls can be made statically like Router::get() making the code look more pretty.
*/
namespace Pecee\SimpleRouter;
@@ -57,7 +57,7 @@ class SimpleRouter {
public static function put($url, $callback, array $settings = null) {
$route = new RouterRoute($url, $callback);
$route->addSettings($settings);
$route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_PUT));
$route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_PUT, RouterRoute::REQUEST_TYPE_PATCH));
$router = RouterBase::getInstance();
$router->addRoute($route);