From ebbfe7804ad7cd07df7398e2b0bf122c01be44d8 Mon Sep 17 00:00:00 2001 From: Danny van Kooten Date: Tue, 31 Jul 2012 20:50:36 +0200 Subject: [PATCH] first commit --- .htaccess | 3 + AltoRouter.php | 192 +++++++++++++++++++++++++++++++++++++++++++++++++ README.MD | 62 ++++++++++++++++ index.php | 26 +++++++ 4 files changed, 283 insertions(+) create mode 100644 .htaccess create mode 100644 AltoRouter.php create mode 100644 README.MD create mode 100644 index.php diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..2c377a9 --- /dev/null +++ b/.htaccess @@ -0,0 +1,3 @@ +RewriteEngine On +RewriteCond %{REQUEST_FILENAME} !-f +RewriteRule . index.php [L] \ No newline at end of file diff --git a/AltoRouter.php b/AltoRouter.php new file mode 100644 index 0000000..25965a6 --- /dev/null +++ b/AltoRouter.php @@ -0,0 +1,192 @@ +basePath = $basePath; + } + /** + * Map a route to a target + */ + public function map($method, $route, $target, array $args = array()) { + + $route = $this->basePath . $route; + $this->routes[] = array($method, $route, $target); + + if(isset($args['name'])) { + $this->namedRoutes[$args['name']] = $route; + } + } + + /** + * Reversed routing + * + * Generate the URL for a named route. Replace regexes with supplied parameters + */ + public function generate($routeName, array $params = array()) { + + // Check if named route exists + if(!isset($this->namedRoutes[$routeName])) { + throw new \Exception("Route '{$routeName}' does not exist."); + } + + // Replace named parameters + $route = $this->namedRoutes[$routeName]; + $url = $route; + + if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) { + + foreach($matches as $match) { + list($block, $pre, $type, $param, $optional) = $match; + + if(isset($params[$param])) { + $url = str_replace(substr($block,1), $params[$param], $url); + } + } + + + } + + return $url; + } + + /** + * Match a given Request Url against stored routes + */ + public function match($requestUrl = null, $requestMethod = null) { + + // set Request Url if it isn't passed as parameter + if($requestUrl === null) { + $requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'; + } + + // Strip query string (?a=b) from Request Url + if (false !== strpos($requestUrl, '?')) { + $requestUrl = strstr($requestUrl, '?', true); + } + + // set Request Method if it isn't passed as a parameter + if($requestMethod === null) { + $requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET'; + } + + // Force request_order to be GP + // http://www.mail-archive.com/internals@lists.php.net/msg33119.html + $_REQUEST = array_merge($_GET, $_POST); + + foreach($this->routes as $handler) { + list($method, $_route, $target) = $handler; + + $methods = explode('|', $method); + $method_match = false; + + // Check if request method matches. If not, abandon early. (CHEAP) + foreach($methods as $method) { + if (strcasecmp($requestMethod, $method) === 0) { + $method_match = true; + break; + } + } + + // Method did not match, continue to next route. + if(!$method_match) continue; + + // Check for a wildcard (matches all) + if ($_route === '*') { + $match = true; + } elseif (isset($_route[0]) && $_route[0] === '@') { + $match = preg_match('`' . substr($_route, 1) . '`', $requestUrl, $params); + } else { + $route = null; + $regex = false; + $j = 0; + $n = isset($_route[0]) ? $_route[0] : null; + $i = 0; + + // Find the longest non-regex substring and match it against the URI + while (true) { + if (!isset($_route[$i])) { + break; + } elseif (false === $regex) { + $c = $n; + $regex = $c === '[' || $c === '(' || $c === '.'; + if (false === $regex && false !== isset($_route[$i+1])) { + $n = $_route[$i + 1]; + $regex = $n === '?' || $n === '+' || $n === '*' || $n === '{'; + } + if (false === $regex && $c !== '/' && (!isset($requestUrl[$j]) || $c !== $requestUrl[$j])) { + continue 2; + } + $j++; + } + $route .= $_route[$i++]; + } + + $regex = $this->compileRoute($route); + $match = preg_match($regex, $requestUrl, $params); + } + + + + if(isset($match) && $match > 0) { + if($params) { + foreach($params as $key => $value) { + if(is_numeric($key)) unset($params[$key]); + } + } + return array( + 'target' => $target, + 'params' => $params + ); + } + + } + + return false; + + } + + /** + * Compile the regex for a given route (EXPENSIVE) + */ + private function compileRoute($route) { + if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) { + + $match_types = array( + 'i' => '[0-9]++', + 'a' => '[0-9A-Za-z]++', + 'h' => '[0-9A-Fa-f]++', + '*' => '.+?', + '**' => '.++', + '' => '[^/]++' + ); + + foreach ($matches as $match) { + list($block, $pre, $type, $param, $optional) = $match; + + if (isset($match_types[$type])) { + $type = $match_types[$type]; + } + if ($pre === '.') { + $pre = '\.'; + } + + //Older versions of PCRE require the 'P' in (?P) + $pattern = '(?:' + . ($pre !== '' ? $pre : null) + . '(' + . ($param !== '' ? "?P<$param>" : null) + . $type + . '))' + . ($optional !== '' ? '?' : null); + + $route = str_replace($block, $pattern, $route); + } + + } + return "`^$route$`"; + } +} \ No newline at end of file diff --git a/README.MD b/README.MD new file mode 100644 index 0000000..5564797 --- /dev/null +++ b/README.MD @@ -0,0 +1,62 @@ +**AltoRouter is an alternative router to PHP-Router, also lightning fast and flexible. +AltoRouter is heavily inspired by [klein.php](https://github.com/chriso/klein.php/). + +* Flexible regular expression routing (inspired by [Sinatra](http://www.sinatrarb.com/)) +* Reversed routing +* Named parameter in routes + +## Getting started + +1. PHP 5.3.x is required +2. Setup URL rewriting so that all requests are handled by **index.php** +3. Include AltoRouter, map your routes and match a request. +4. Have a look at the supplied example file (index.php). + + + +## Routing +```php +$router = new AltoRouter(); +$router->setBasePath('/AltoRouter'); +$router->map('GET|POST','/', 'home#index', array('name' => 'home')); +$router->map('GET','/users/', array('c' => 'UserController', 'a' => 'ListAction')); +$router->map('GET','/users/[i:id]', 'users#show', array('name' => 'users_show')); +$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', array('name' => 'users_do')); + +``` + +You can use the following limits on your named parameters. AltoRouter will create the correct regexes. +```php +Some examples + + * // Match all request URIs + [i] // Match an integer + [i:id] // Match an integer as 'id' + [a:action] // Match alphanumeric characters as 'action' + [h:key] // Match hexadecimal characters as 'key' + [:action] // Match anything up to the next / or end of the URI as 'action' + [create|edit:action] // Match either 'create' or 'edit' as 'action' + [*] // Catch all (lazy, stops at the next trailing slash) + [*:trailing] // Catch all as 'trailing' (lazy) + [**:trailing] // Catch all (possessive - will match the rest of the URI) + .[:format]? // Match an optional parameter 'format' - a / or . before the block is also optional + +Some more complicated examples + + /posts/[*:title][i:id] // Matches "/posts/this-is-a-title-123" + /output.[xml|json:format]? // Matches "/output", "output.xml", "output.json" + /[:controller]?/[:action]? // Matches the typical /controller/action format + +``` + +## License + +(MIT License) + +Copyright (c) 2012 Danny van Kooten + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/index.php b/index.php new file mode 100644 index 0000000..29e1a1b --- /dev/null +++ b/index.php @@ -0,0 +1,26 @@ +setBasePath('/AltoRouter'); +$router->map('GET|POST','/', 'home#index', array('name' => 'home')); +$router->map('GET','/users/', array('c' => 'UserController', 'a' => 'ListAction')); +$router->map('GET','/users/[i:id]', 'users#show', array('name' => 'users_show')); +$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', array('name' => 'users_do')); + +// match current request +$match = $router->match(); +?> +

AltoRouter

+ +

Current request:

+
+	Target: 
+	Params: 
+
+ +

Try these requests:

+

GET generate('home'); ?>

+

GET generate('users_show', array('id' => 5)); ?>

+

\ No newline at end of file