forked from simonhamp/routes
/
routes.php
61 lines (51 loc) · 1.61 KB
/
routes.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
class Routes {
protected static $allow_query = true;
protected static $routes = array();
public static function add( $src, $dest = null ) {
// TODO: Validate the routes?
if ( is_array( $src ) ) {
foreach ( $src as $key => $val ) {
static::$routes[ $key ] = $val;
}
}
elseif ( $dest ) {
static::$routes[ $src ] = $dest;
}
}
public static function route( $uri ) {
$qs = '';
if ( static::$allow_query && strpos( $uri, '?' ) !== false ) {
// Break the query string off and attach later
$qs = parse_url( $uri, PHP_URL_QUERY );
$uri = str_replace( '?' . $qs, '', $uri );
$qs = '&' . $qs;
}
// Empty URI?
if (empty($uri))
$uri = '/';
// Is there a literal match?
if ( isset( static::$routes[ $uri ] ) ) {
return static::$routes[ $uri ] . $qs;
}
// Loop through the route array looking for wild-cards
foreach ( static::$routes as $key => $val) {
// Convert wild-cards to RegEx
$key = str_replace( ':any', '.+', $key );
$key = str_replace( ':num', '[0-9]+', $key );
$key = str_replace( ':nonum', '[^0-9]+', $key );
$key = str_replace( ':alpha', '[A-Za-z]+', $key );
$key = str_replace( ':alnum', '[A-Za-z0-9]+', $key );
$key = str_replace( ':hex', '[A-Fa-f0-9]+', $key );
// Does the RegEx match?
if ( preg_match( '#^' . $key . '$#', $uri ) ) {
// Do we have a back-reference?
if ( strpos( $val, '$' ) !== false && strpos( $key, '(' ) !== false ) {
$val = preg_replace( '#^' . $key . '$#', $val, $uri );
}
return $val . $qs;
}
}
return $uri . $qs;
}
}