Special case the empty rule.
[hoplite.git] / http / url_map.php
1 <?php
2 // Hoplite
3 // Copyright (c) 2011 Blue Static
4 //
5 // This program is free software: you can redistribute it and/or modify it
6 // under the terms of the GNU General Public License as published by the Free
7 // Software Foundation, either version 3 of the License, or any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License along with
15 // this program. If not, see <http://www.gnu.org/licenses/>.
16
17 namespace hoplite\http;
18
19 require_once HOPLITE_ROOT . '/base/functions.php';
20
21 /*!
22 A UrlMap will translate a raw HTTP request into a http\Request object. It does
23 so by matching the incoming URL to a pattern. For information on the format of
24 patterns @see ::set_map().
25 */
26 class UrlMap
27 {
28 /*! @var RootController */
29 private $controller;
30
31 /*! @var array The map of URLs to actions. */
32 private $map = array();
33
34 /*!
35 Constructs the object with a reference to the RootController.
36 @param RootController
37 */
38 public function __construct(RootController $controller)
39 {
40 $this->controller = $controller;
41 }
42
43 /*! Accessor for the RootController */
44 public function controller() { return $this->controller; }
45
46 /*! Gets the URL map */
47 public function map() { return $this->map; }
48 /*! @brief Sets the URL map.
49 The URL map is an associative array of URL prefix patterns to Actions or
50 file paths containing actions.
51
52 The keys can be either a URL prefix or a regular expression.
53
54 For URL prefixes, the pattern is matched relative to the root of the entry-
55 point as specified by the RootController. Patterns should not begin with a
56 slash. Path fragment parameter extraction can be performed as well. For
57 example, the pattern 'user/view/{id}' will match a URL like
58 http://example.com/webapp/user/view/42
59 And the http\Request's data will have a member called 'id' with value 42.
60
61 Typically prefix matching will be done for the above patterns. This may be
62 unwanted if a more general path needs to execute before a more descendent
63 one. Using strict matching, invoked by ending a pattern with two slashes,
64 pattern matching becomes exact in that all path components must match.
65
66 Regular expression matching is not limited to prefix patterns and can match
67 any part of the URL (though prefix matching can be enforced using the
68 the standard regex '^' character). Regex patterns must begin and end with
69 '/' characters. During evaluation, if any pattern groups are matched, the
70 resulting matches will be placed in Request data via the 'url_pattern' key.
71 The following will match the same URL as above:
72 '/^user\/view\/([0-9]+)/'
73
74 Values can be a class name or a relative path to a file that contains an
75 Action class by the same name, or just the name of an Action class. The
76 conventions for each are governed by ::LookupAction().
77
78 @see ::Evaluate()
79 @see ::LookupAction()
80 */
81 public function set_map(array $map) { $this->map = $map; }
82
83 /*! @brief Evalutes the URL map and finds a match.
84 This will take the incoming URL from the request and will match it against
85 the patterns in the internal map.
86
87 Matching occurs in a linear scan of the URL map, so precedence can be
88 enforced by ordering rules appropriately. Regular expressions are matched
89 and URL parameter extraction occurs each time a different rule is evaluated.
90
91 This may mutate the request with extracted data if a match is made and
92 returned.
93 @see ::set_map() for more information.
94
95 If a match is made, this will return the corresponding value for the matched
96 key in the map. To get an Action object from this, use ::LookupAction().
97
98 @return string|NULL A matched value in the ::map() or NULL if no match.
99 */
100 public function Evaluate(Request $request)
101 {
102 $fragments = explode('/', $request->url);
103 $path_length = strlen($request->url);
104
105 foreach ($this->map as $rule => $action) {
106 // First check if this is the empty rule.
107 if (empty($rule)) {
108 if (empty($request->url))
109 return $action;
110 else
111 continue;
112 }
113
114 // Check if this is a regular expression rule and match it.
115 if ($rule[0] == '/' && substr($rule, -1) == '/') {
116 $matches = array();
117 if (preg_match($rule, $request->url, $matches)) {
118 // This pattern matched, so fill out the request and return.
119 $request->data['url_pattern'] = $matches;
120 return $action;
121 }
122 }
123 // Otherwise, this is just a normal string match.
124 else {
125 // Patterns that end with two slashes are exact.
126 $is_strict = substr($rule, -2) == '//';
127 if ($is_strict)
128 $rule = substr($rule, 0, -2);
129
130 // Set up some variables for the loop.
131 $is_match = TRUE;
132 $rule_fragments = explode('/', $rule);
133 $count_rule_fragments = count($rule_fragments);
134 $count_fragments = count($fragments);
135 $extractions = array();
136
137 // If this is a strict matcher, then do a quick test based on fragments.
138 if ($is_strict && $count_rule_fragments != $count_fragments)
139 continue;
140
141 // Loop over the pieces of the rule, matching the fragments to that of
142 // the request.
143 foreach ($rule_fragments as $i => $rule_frag) {
144 // Don't iterate past the length of the request. Prefix matching means
145 // that this can still be a match.
146 if ($i >= $count_fragments)
147 break;
148
149 // If this fragment is a key to be extracted, do so into a temporary
150 // array.
151 if ($rule_frag[0] == '{' && substr($rule_frag, -1) == '}') {
152 $key = substr($rule_frag, 1, -1);
153 $extractions[$key] = $fragments[$i];
154 }
155 // Otherwise, the path components mutch match.
156 else if ($rule_frag != $fragments[$i]) {
157 $is_match = FALSE;
158 break;
159 }
160 }
161
162 // If no match was made, try the next rule.
163 if (!$is_match)
164 continue;
165
166 // A match was made, so merge the path components that were extracted by
167 // key and return the match.
168 $request->data = array_merge($extractions, $request->data);
169 return $action;
170 }
171 }
172 }
173
174 /*! @brief Takes a value from the map and returns an Action object.
175 The values in the map are either an Action class name or a relative path to
176 a file containing an Action class.
177
178 Mapping to a class requires that the value start with an upper-case letter.
179
180 Paths start with a lower-case letter. The last path component will be
181 transformed into a class name via ::_ClassNameFromFileName(). Note that if
182 the file extension is not included in the path, .php will be automatically
183 appended.
184
185 @return Action|NULL The loaded action, or NULL on error.
186 */
187 public function LookupAction($map_value)
188 {
189 // If the first character is uppercase or a namespaced class, simply return
190 // the value.
191 $first_char = $map_value[0];
192 if ($first_char == '\\' || ctype_upper($first_char))
193 return $map_value;
194
195 // Otherwise this is a path. Check if an extension is present, and if not,
196 // add one.
197 $pathinfo = pathinfo($map_value);
198 if (!isset($pathinfo['extension'])) {
199 $map_value .= '.php';
200 $pathinfo['extension'] = 'php';
201 }
202
203 return $this->_ClassNameFromFileName($pathinfo);
204 }
205
206 /*!
207 Takes a file name and returns the name of an Action class. This uses an
208 under_score to CamelCase transformation with an 'Action' suffix:
209 lost_password -> LostPasswordAction
210
211 This can be overridden to provide a custom transformation.
212
213 @param array Result of a pathinfo() call
214
215 @return string Action class name.
216 */
217 protected function _ClassNameFromFileName($pathinfo)
218 {
219 $filename = $pathinfo['filename'];
220 return \hoplite\base\UnderscoreToCamelCase($filename);
221 }
222 }