Files
spa-api/system/router.php

102 lines
2.3 KiB
PHP
Raw Normal View History

2011-06-08 23:45:08 -05:00
<?php namespace System;
class Router {
/**
* All of the loaded routes.
*
* @var array
*/
public static $routes;
/**
* Search a set of routes for the route matching a method and URI.
*
* @param string $method
* @param string $uri
* @return Route
*/
public static function route($method, $uri)
{
if (is_null(static::$routes))
{
static::$routes = static::load($uri);
}
2011-06-08 23:45:08 -05:00
2011-07-07 12:18:53 -07:00
// Put the request method and URI in route form. Routes begin with the request method and a forward slash.
2011-07-07 12:17:55 -07:00
$uri = $method.' /'.trim($uri, '/');
2011-06-08 23:45:08 -05:00
// Is there an exact match for the request?
2011-07-07 12:17:55 -07:00
if (isset(static::$routes[$uri]))
2011-06-08 23:45:08 -05:00
{
2011-07-07 12:17:55 -07:00
return Request::$route = new Route($uri, static::$routes[$uri]);
2011-06-08 23:45:08 -05:00
}
foreach (static::$routes as $keys => $callback)
{
2011-07-07 12:18:53 -07:00
// Only check routes that have multiple URIs or wildcards. Other routes would be caught by a literal match.
2011-06-08 23:45:08 -05:00
if (strpos($keys, '(') !== false or strpos($keys, ',') !== false )
{
foreach (explode(', ', $keys) as $key)
2011-06-08 23:45:08 -05:00
{
$key = str_replace(':num', '[0-9]+', str_replace(':any', '[a-zA-Z0-9\-_]+', $key));
2011-06-08 23:45:08 -05:00
2011-07-07 12:17:55 -07:00
if (preg_match('#^'.$key.'$#', $uri))
2011-06-08 23:45:08 -05:00
{
2011-07-07 11:38:30 -07:00
return Request::$route = new Route($keys, $callback, static::parameters($uri, $key));
2011-06-08 23:45:08 -05:00
}
}
}
}
}
/**
* Load the appropriate route file for the request URI.
*
* @param string $uri
* @return array
*/
2011-07-07 09:12:20 -07:00
public static function load($uri)
{
if ( ! is_dir(APP_PATH.'routes'))
{
return require APP_PATH.'routes'.EXT;
}
if ( ! file_exists(APP_PATH.'routes/home'.EXT))
{
throw new \Exception("A [home] route file is required when using a route directory.");
}
if ($uri == '/')
{
return require APP_PATH.'routes/home'.EXT;
}
else
{
2011-07-07 12:17:55 -07:00
$segments = explode('/', $uri);
if ( ! file_exists(APP_PATH.'routes/'.$segments[0].EXT))
{
return require APP_PATH.'routes/home'.EXT;
}
return array_merge(require APP_PATH.'routes/'.$segments[0].EXT, require APP_PATH.'routes/home'.EXT);
}
}
/**
* Extract the parameters from a URI based on a route URI.
*
* Any route segment wrapped in parentheses is considered a parameter.
*
2011-07-07 11:38:30 -07:00
* @param string $uri
* @param string $route
* @return array
*/
public static function parameters($uri, $route)
{
2011-07-07 11:38:30 -07:00
return array_values(array_intersect_key(explode('/', $uri), preg_grep('/\(.+\)/', explode('/', $route))));
}
2011-06-08 23:45:08 -05:00
}