bzr branch
http://bzr.ed.am/www/slight
1
by Tim Marston
initial commit |
1 |
<?php |
2 |
/** |
|
3 |
* Flight: An extensible micro-framework. |
|
4 |
* |
|
5 |
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com> |
|
6 |
* @license MIT, http://flightphp.com/license |
|
7 |
*/ |
|
8 |
||
9 |
namespace flight\net; |
|
10 |
||
11 |
/** |
|
12 |
* The Router 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. |
|
15 |
*/ |
|
16 |
class Router { |
|
17 |
/** |
|
18 |
* Mapped routes. |
|
19 |
* |
|
20 |
* @var array |
|
21 |
*/ |
|
22 |
protected $routes = array(); |
|
23 |
||
24 |
/** |
|
25 |
* Pointer to current route |
|
26 |
* |
|
27 |
* @var int |
|
28 |
*/ |
|
29 |
protected $index = 0; |
|
30 |
||
31 |
/** |
|
32 |
* Gets mapped routes. |
|
33 |
* |
|
34 |
* @return array Array of routes |
|
35 |
*/ |
|
36 |
public function getRoutes() { |
|
37 |
return $this->routes; |
|
38 |
} |
|
39 |
||
40 |
/** |
|
41 |
* Clears all routes in the router. |
|
42 |
*/ |
|
43 |
public function clear() { |
|
44 |
$this->routes = array(); |
|
45 |
} |
|
46 |
||
47 |
/** |
|
48 |
* Maps a URL pattern to a callback function. |
|
49 |
* |
|
50 |
* @param string $pattern URL pattern to match |
|
51 |
* @param callback $callback Callback function |
|
52 |
* @param boolean $pass_route Pass the matching route object to the callback |
|
53 |
*/ |
|
54 |
public function map($pattern, $callback, $pass_route = false) { |
|
55 |
$url = $pattern; |
|
56 |
$methods = array('*'); |
|
57 |
||
58 |
if (strpos($pattern, ' ') !== false) { |
|
59 |
list($method, $url) = explode(' ', trim($pattern), 2); |
|
60 |
||
61 |
$methods = explode('|', $method); |
|
62 |
} |
|
63 |
||
64 |
$this->routes[] = new Route($url, $callback, $methods, $pass_route); |
|
65 |
} |
|
66 |
||
67 |
/** |
|
68 |
* Routes the current request. |
|
69 |
* |
|
70 |
* @param Request $request Request object |
|
71 |
* @return Route Matching route |
|
72 |
*/ |
|
73 |
public function route(Request $request) { |
|
74 |
while ($route = $this->current()) { |
|
75 |
if ($route !== false && $route->matchMethod($request->method) && $route->matchUrl($request->url)) { |
|
76 |
return $route; |
|
77 |
} |
|
78 |
$this->next(); |
|
79 |
} |
|
80 |
||
81 |
return false; |
|
82 |
} |
|
83 |
||
84 |
/** |
|
85 |
* Gets the current route. |
|
86 |
* |
|
87 |
* @return Route |
|
88 |
*/ |
|
89 |
public function current() { |
|
90 |
return isset($this->routes[$this->index]) ? $this->routes[$this->index] : false; |
|
91 |
} |
|
92 |
||
93 |
/** |
|
94 |
* Gets the next route. |
|
95 |
* |
|
96 |
* @return Route |
|
97 |
*/ |
|
98 |
public function next() { |
|
99 |
$this->index++; |
|
100 |
} |
|
101 |
||
102 |
/** |
|
103 |
* Reset to the first route. |
|
104 |
*/ |
|
105 |
public function reset() { |
|
106 |
$this->index = 0; |
|
107 |
} |
|
108 |
} |
|
109 |