4 * This class can take patterns such as /wiki/$1 and use them to
5 * parse query parameters out of REQUEST_URI paths.
7 * $router->add( "/wiki/$1" );
8 * - Matches /wiki/Foo style urls and extracts the title
9 * $router->add( array( 'edit' => "/edit/$1" ), array( 'action' => '$key' ) );
10 * - Matches /edit/Foo style urls and sets action=edit
11 * $router->add( '/$2/$1',
12 * array( 'variant' => '$2' ),
13 * array( '$2' => array( 'zh-hant', 'zh-hans' )
15 * - Matches /zh-hant/Foo or /zh-hans/Foo
16 * $router->addStrict( "/foo/Bar", array( 'title' => 'Baz' ) );
17 * - Matches /foo/Bar explicitly and uses "Baz" as the title
18 * $router->add( '/help/$1', array( 'title' => 'Help:$1' ) );
19 * - Matches /help/Foo with "Help:Foo" as the title
20 * $router->add( '/$1', array( 'foo' => array( 'value' => 'bar$2' ) );
21 * - Matches /Foo and sets 'foo' to 'bar$2' without $2 being replaced
22 * $router->add( '/$1', array( 'data:foo' => 'bar' ), array( 'callback' => 'functionname' ) );
23 * - Matches /Foo, adds the key 'foo' with the value 'bar' to the data array
24 * and calls functionname( &$matches, $data );
27 * - Paths may contain $# patterns such as $1, $2, etc...
28 * - $1 will match 0 or more while the rest will match 1 or more
29 * - Unless you use addStrict "/wiki" and "/wiki/" will be expanded to "/wiki/$1"
32 * - In a pattern $1, $2, etc... will be replaced with the relevant contents
33 * - If you used a keyed array as a path pattern, $key will be replaced with
34 * the relevant contents
35 * - The default behavior is equivalent to `array( 'title' => '$1' )`,
36 * if you don't want the title parameter you can explicitly use `array( 'title' => false )`
37 * - You can specify a value that won't have replacements in it
38 * using `'foo' => array( 'value' => 'bar' );`
41 * - The option keys $1, $2, etc... can be specified to restrict the possible values
42 * of that variable. A string can be used for a single value, or an array for multiple.
43 * - When the option key 'strict' is set (Using addStrict is simpler than doing this directly)
44 * the path won't have $1 implicitly added to it.
45 * - The option key 'callback' can specify a callback that will be run when a path is matched.
46 * The callback will have the arguments ( &$matches, $data ) and the matches array can
50 * @author Daniel Friesen
55 * Protected helper to do the actual bulk work of adding a single pattern.
56 * This is in a separate method so that add() can handle the difference between
57 * a single string $path and an array() $path that contains multiple path
58 * patterns each with an associated $key to pass on.
60 protected function doAdd( $path, $params, $options, $key = null ) {
61 // Make sure all paths start with a /
62 if ( $path[0] !== '/' ) {
66 if ( !isset( $options['strict'] ) ||
!$options['strict'] ) {
67 // Unless this is a strict path make sure that the path has a $1
68 if ( strpos( $path, '$1' ) === false ) {
69 if ( substr( $path, -1 ) !== '/' ) {
76 // If 'title' is not specified and our path pattern contains a $1
77 // Add a default 'title' => '$1' rule to the parameters.
78 if ( !isset( $params['title'] ) && strpos( $path, '$1' ) !== false ) {
79 $params['title'] = '$1';
81 // If the user explicitly marked 'title' as false then omit it from the matches
82 if ( isset( $params['title'] ) && $params['title'] === false ) {
83 unset( $params['title'] );
86 // Loop over our parameters and convert basic key => string
87 // patterns into fully descriptive array form
88 foreach ( $params as $paramName => $paramData ) {
89 if ( is_string( $paramData ) ) {
90 if ( preg_match( '/\$(\d+|key)/u', $paramData ) ) {
91 $paramArrKey = 'pattern';
93 // If there's no replacement use a value instead
94 // of a pattern for a little more efficiency
95 $paramArrKey = 'value';
97 $params[$paramName] = array(
98 $paramArrKey => $paramData
103 // Loop over our options and convert any single value $# restrictions
104 // into an array so we only have to do in_array tests.
105 foreach ( $options as $optionName => $optionData ) {
106 if ( preg_match( '/^\$\d+$/u', $optionName ) ) {
107 if ( !is_array( $optionData ) ) {
108 $options[$optionName] = array( $optionData );
113 $pattern = (object)array(
116 'options' => $options,
119 $pattern->weight
= self
::makeWeight( $pattern );
120 $this->patterns
[] = $pattern;
124 * Add a new path pattern to the path router
126 * @param $path string The path pattern to add
127 * @param $params array The params for this path pattern
128 * @param $options array The options for this path pattern
130 public function add( $path, $params = array(), $options = array() ) {
131 if ( is_array( $path ) ) {
132 foreach ( $path as $key => $onePath ) {
133 $this->doAdd( $onePath, $params, $options, $key );
136 $this->doAdd( $path, $params, $options );
141 * Add a new path pattern to the path router with the strict option on
144 public function addStrict( $path, $params = array(), $options = array() ) {
145 $options['strict'] = true;
146 $this->add( $path, $params, $options );
150 * Protected helper to re-sort our patterns so that the most specific
151 * (most heavily weighted) patterns are at the start of the array.
153 protected function sortByWeight() {
155 foreach( $this->patterns
as $key => $pattern ) {
156 $weights[$key] = $pattern->weight
;
158 array_multisort( $weights, SORT_DESC
, SORT_NUMERIC
, $this->patterns
);
161 protected static function makeWeight( $pattern ) {
162 # Start with a weight of 0
165 // Explode the path to work with
166 $path = explode( '/', $pattern->path
);
168 # For each level of the path
169 foreach( $path as $piece ) {
170 if ( preg_match( '/^\$(\d+|key)$/u', $piece ) ) {
171 # For a piece that is only a $1 variable add 1 points of weight
173 } elseif ( preg_match( '/\$(\d+|key)/u', $piece ) ) {
174 # For a piece that simply contains a $1 variable add 2 points of weight
177 # For a solid piece add a full 3 points of weight
182 foreach ( $pattern->options
as $key => $option ) {
183 if ( preg_match( '/^\$\d+$/u', $key ) ) {
184 # Add 0.5 for restrictions to values
185 # This way given two separate "/$2/$1" patterns the
186 # one with a limited set of $2 values will dominate
187 # the one that'll match more loosely
196 * Parse a path and return the query matches for the path
198 * @param $path string The path to parse
199 * @return Array The array of matches for the path
201 public function parse( $path ) {
202 // Make sure our patterns are sorted by weight so the most specific
203 // matches are tested first
204 $this->sortByWeight();
208 foreach ( $this->patterns
as $pattern ) {
209 $matches = self
::extractTitle( $path, $pattern );
210 if ( !is_null( $matches ) ) {
215 // We know the difference between null (no matches) and
216 // array() (a match with no data) but our WebRequest caller
217 // expects array() even when we have no matches so return
218 // a array() when we have null
219 return is_null( $matches ) ?
array() : $matches;
222 protected static function extractTitle( $path, $pattern ) {
223 // Convert the path pattern into a regexp we can match with
224 $regexp = preg_quote( $pattern->path
, '#' );
226 $regexp = preg_replace( '#\\\\\$1#u', '(?P<par1>.*)', $regexp );
227 // .+ for the rest of the parameter numbers
228 $regexp = preg_replace( '#\\\\\$(\d+)#u', '(?P<par$1>.+?)', $regexp );
229 $regexp = "#^{$regexp}$#";
234 // Try to match the path we were asked to parse with our regexp
235 if ( preg_match( $regexp, $path, $m ) ) {
236 // Ensure that any $# restriction we have set in our {$option}s
237 // matches properly here.
238 foreach ( $pattern->options
as $key => $option ) {
239 if ( preg_match( '/^\$\d+$/u', $key ) ) {
240 $n = intval( substr( $key, 1 ) );
241 $value = rawurldecode( $m["par{$n}"] );
242 if ( !in_array( $value, $option ) ) {
243 // If any restriction does not match return null
244 // to signify that this rule did not match.
250 // Give our $data array a copy of every $# that was matched
251 foreach ( $m as $matchKey => $matchValue ) {
252 if ( preg_match( '/^par\d+$/u', $matchKey ) ) {
253 $n = intval( substr( $matchKey, 3 ) );
254 $data['$'.$n] = rawurldecode( $matchValue );
257 // If present give our $data array a $key as well
258 if ( isset( $pattern->key
) ) {
259 $data['$key'] = $pattern->key
;
262 // Go through our parameters for this match and add data to our matches and data arrays
263 foreach ( $pattern->params
as $paramName => $paramData ) {
265 // Differentiate data: from normal parameters and keep the correct
266 // array key around (ie: foo for data:foo)
267 if ( preg_match( '/^data:/u', $paramName ) ) {
269 $key = substr( $paramName, 5 );
275 if ( isset( $paramData['value'] ) ) {
276 // For basic values just set the raw data as the value
277 $value = $paramData['value'];
278 } elseif ( isset( $paramData['pattern'] ) ) {
279 // For patterns we have to make value replacements on the string
280 $value = $paramData['pattern'];
281 $replacer = new PathRouterPatternReplacer
;
282 $replacer->params
= $m;
283 if ( isset( $pattern->key
) ) {
284 $replacer->key
= $pattern->key
;
286 $value = $replacer->replace( $value );
287 if ( $value === false ) {
288 // Pattern required data that wasn't available, abort
293 // Send things that start with data: to $data, the rest to $matches
295 $data[$key] = $value;
297 $matches[$key] = $value;
301 // If this match includes a callback, execute it
302 if ( isset( $pattern->options
['callback'] ) ) {
303 call_user_func_array( $pattern->options
['callback'], array( &$matches, $data ) );
306 // Our regexp didn't match, return null to signify no match.
309 // Fall through, everything went ok, return our matches array
315 class PathRouterPatternReplacer
{
317 public $key, $params, $error;
320 * Replace keys inside path router patterns with text.
321 * We do this inside of a replacement callback because after replacement we can't tell the
322 * difference between a $1 that was not replaced and a $1 that was part of
323 * the content a $1 was replaced with.
325 public function replace( $value ) {
326 $this->error
= false;
327 $value = preg_replace_callback( '/\$(\d+|key)/u', array( $this, 'callback' ), $value );
328 if ( $this->error
) {
334 protected function callback( $m ) {
335 if ( $m[1] == "key" ) {
336 if ( is_null( $this->key
) ) {
343 if ( !isset( $this->params
["par$d"] ) ) {
347 return rawurldecode( $this->params
["par$d"] );