Implement UrlMap::LookupAction()
[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 // Check if this is a regular expression rule and match it.
107 if ($rule[0] == '/' && substr($rule, -1) == '/') {
108 $matches = array();
109 if (preg_match($rule, $request->url, $matches)) {
110 // This pattern matched, so fill out the request and return.
111 $request->data['url_pattern'] = $matches;
112 return $action;
113 }
114 }
115 // Otherwise, this is just a normal string match.
116 else {
117 // Patterns that end with two slashes are exact.
118 $is_strict = substr($rule, -2) == '//';
119 if ($is_strict)
120 $rule = substr($rule, 0, -2);
121
122 // Set up some variables for the loop.
123 $is_match = TRUE;
124 $rule_fragments = explode('/', $rule);
125 $count_rule_fragments = count($rule_fragments);
126 $count_fragments = count($fragments);
127 $extractions = array();
128
129 // If this is a strict matcher, then do a quick test based on fragments.
130 if ($is_strict && $count_rule_fragments != $count_fragments)
131 continue;
132
133 // Loop over the pieces of the rule, matching the fragments to that of
134 // the request.
135 foreach ($rule_fragments as $i => $rule_frag) {
136 // Don't iterate past the length of the request. Prefix matching means
137 // that this can still be a match.
138 if ($i >= $count_fragments)
139 break;
140
141 // If this fragment is a key to be extracted, do so into a temporary
142 // array.
143 if ($rule_frag[0] == '{' && substr($rule_frag, -1) == '}') {
144 $key = substr($rule_frag, 1, -1);
145 $extractions[$key] = $fragments[$i];
146 }
147 // Otherwise, the path components mutch match.
148 else if ($rule_frag != $fragments[$i]) {
149 $is_match = FALSE;
150 break;
151 }
152 }
153
154 // If no match was made, try the next rule.
155 if (!$is_match)
156 continue;
157
158 // A match was made, so merge the path components that were extracted by
159 // key and return the match.
160 $request->data = array_merge($extractions, $request->data);
161 return $action;
162 }
163 }
164 }
165
166 /*! @brief Takes a value from the map and returns an Action object.
167 The values in the map are either an Action class name or a relative path to
168 a file containing an Action class.
169
170 Mapping to a class requires that the value start with an upper-case letter.
171
172 Paths start with a lower-case letter. The last path component will be
173 transformed into a class name via ::_ClassNameFromFileName(). Note that if
174 the file extension is not included in the path, .php will be automatically
175 appended.
176
177 @return Action|NULL The loaded action, or NULL on error.
178 */
179 public function LookupAction($map_value)
180 {
181 // If the first character is uppercase or a namespaced class, simply return
182 // the value.
183 $first_char = $map_value[0];
184 if ($first_char == '\\' || ctype_upper($first_char))
185 return $map_value;
186
187 // Otherwise this is a path. Check if an extension is present, and if not,
188 // add one.
189 $pathinfo = pathinfo($map_value);
190 if (!isset($pathinfo['extension'])) {
191 $map_value .= '.php';
192 $pathinfo['extension'] = 'php';
193 }
194
195 return $this->_ClassNameFromFileName($pathinfo);
196 }
197
198 /*!
199 Takes a file name and returns the name of an Action class. This uses an
200 under_score to CamelCase transformation with an 'Action' suffix:
201 lost_password -> LostPasswordAction
202
203 This can be overridden to provide a custom transformation.
204
205 @param array Result of a pathinfo() call
206
207 @return string Action class name.
208 */
209 protected function _ClassNameFromFileName($pathinfo)
210 {
211 $filename = $pathinfo['filename'];
212 return \hoplite\base\UnderscoreToCamelCase($filename);
213 }
214 }