3
* Flight: An extensible micro-framework.
5
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
6
* @license MIT, http://flightphp.com/license
12
* The Route class is responsible for routing an HTTP request to
13
* an assigned callback function. The Router tries to match the
14
* requested URL against a series of URL patterns.
18
* @var string URL pattern
23
* @var mixed Callback function
28
* @var array HTTP methods
30
public $methods = array();
33
* @var array Route parameters
35
public $params = array();
38
* @var string Matching regular expression
43
* @var string URL splat content
48
* @var boolean Pass self in callback parameters
55
* @param string $pattern URL pattern
56
* @param mixed $callback Callback function
57
* @param array $methods HTTP methods
58
* @param boolean $pass Pass self in callback parameters
60
public function __construct($pattern, $callback, $methods, $pass) {
61
$this->pattern = $pattern;
62
$this->callback = $callback;
63
$this->methods = $methods;
68
* Checks if a URL matches the route pattern. Also parses named parameters in the URL.
70
* @param string $url Requested URL
71
* @return boolean Match status
73
public function matchUrl($url) {
74
// Wildcard or exact match
75
if ($this->pattern === '*' || $this->pattern === $url) {
77
$this->params[] = $this;
83
$last_char = substr($this->pattern, -1);
86
if ($last_char === '*') {
89
$count = substr_count($this->pattern, '/');
91
for ($i = 0; $i < $len; $i++) {
92
if ($url[$i] == '/') $n++;
93
if ($n == $count) break;
96
$this->splat = (string)substr($url, $i+1);
99
// Build the regex for matching
100
$regex = str_replace(array(')','/*'), array(')?','(/?|/.*?)'), $this->pattern);
102
$regex = preg_replace_callback(
103
'#@([\w]+)(:([^/\(\)]*))?#',
104
function($matches) use (&$ids) {
105
$ids[$matches[1]] = null;
106
if (isset($matches[3])) {
107
return '(?P<'.$matches[1].'>'.$matches[3].')';
109
return '(?P<'.$matches[1].'>[^/\?]+)';
114
// Fix trailing slash
115
if ($last_char === '/') {
118
// Allow trailing slash
123
// Attempt to match route and named parameters
124
if (preg_match('#^'.$regex.'(?:\?.*)?$#i', $url, $matches)) {
125
foreach ($ids as $k => $v) {
126
$this->params[$k] = (array_key_exists($k, $matches)) ? urldecode($matches[$k]) : null;
130
$this->params[] = $this;
133
$this->regex = $regex;
142
* Checks if an HTTP method matches the route methods.
144
* @param string $method HTTP method
145
* @return bool Match status
147
public function matchMethod($method) {
148
return count(array_intersect(array($method, '*'), $this->methods)) > 0;