| 1 |
<?php if (! defined('ABSPATH')) exit; // Exit if accessed directly |
| 2 |
interface HC3_Router_ |
| 3 |
{ |
| 4 |
public function register( $slug, $handler ); |
| 5 |
public function getHandlerArgs( $slug ); |
| 6 |
} |
| 7 |
|
| 8 |
class HC3_Router implements HC3_Router_ |
| 9 |
{ |
| 10 |
protected $handlers = array(); |
| 11 |
|
| 12 |
public function __construct() |
| 13 |
{ |
| 14 |
// echo "INIT ROUTER!"; |
| 15 |
} |
| 16 |
|
| 17 |
public function register( $slug, $handler ) |
| 18 |
{ |
| 19 |
// echo "REGISTERING '$slug'<br><br>"; |
| 20 |
$this->handlers[$slug] = $handler; |
| 21 |
return $this; |
| 22 |
} |
| 23 |
|
| 24 |
public function getHandlerArgs( $slug ) |
| 25 |
{ |
| 26 |
// echo "GETTING FOR '$slug'<br><br>"; |
| 27 |
// print_r( array_keys($this->handlers) ); |
| 28 |
list( $handler, $args ) = $this->_findHandlerArgs( $slug, $this->handlers ); |
| 29 |
$return = array( $handler, $args ); |
| 30 |
return $return; |
| 31 |
} |
| 32 |
|
| 33 |
protected function _findHandlerArgs( $slug, $array ) |
| 34 |
{ |
| 35 |
$handler = NULL; |
| 36 |
$args = array(); |
| 37 |
|
| 38 |
// exact match |
| 39 |
if( isset($array[$slug]) ){ |
| 40 |
$handler = $array[$slug]; |
| 41 |
} |
| 42 |
// wildcards |
| 43 |
else { |
| 44 |
// if we have wildcards |
| 45 |
$config_keys = array_keys($array); |
| 46 |
|
| 47 |
if( strpos($slug, ':') !== FALSE ){ |
| 48 |
$slug = str_replace(':', '/', $slug); |
| 49 |
} |
| 50 |
|
| 51 |
$sluga = explode('/', $slug); |
| 52 |
$count_sluga = count($sluga); |
| 53 |
// echo "SLUG: '$slug'<br>"; |
| 54 |
// _print_r( $sluga ); |
| 55 |
|
| 56 |
$parametered_keys = array(); |
| 57 |
foreach( $config_keys as $k ){ |
| 58 |
if( strpos($k, '{') === FALSE ){ |
| 59 |
continue; |
| 60 |
} |
| 61 |
$parametered_keys[] = $k; |
| 62 |
} |
| 63 |
|
| 64 |
reset( $parametered_keys ); |
| 65 |
foreach( $parametered_keys as $k ){ |
| 66 |
$kk = $k; |
| 67 |
if( strpos($kk, ':') !== FALSE ){ |
| 68 |
$kk = str_replace(':', '/', $kk); |
| 69 |
} |
| 70 |
$ka = explode('/', $kk); |
| 71 |
|
| 72 |
// check if this one matches |
| 73 |
if( count($ka) != $count_sluga ){ |
| 74 |
continue; |
| 75 |
} |
| 76 |
|
| 77 |
$match = TRUE; |
| 78 |
$parametered_args = array(); |
| 79 |
for( $ii = 0; $ii < $count_sluga; $ii++ ){ |
| 80 |
if( strpos($ka[$ii], '{') !== FALSE ){ |
| 81 |
$parametered_args[] = $sluga[$ii]; |
| 82 |
} |
| 83 |
else { |
| 84 |
if( $ka[$ii] != $sluga[$ii] ){ |
| 85 |
$match = FALSE; |
| 86 |
} |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
if( $match ){ |
| 91 |
$handler = $array[$k]; |
| 92 |
foreach( $parametered_args as $parametered_arg ){ |
| 93 |
$args[] = $parametered_arg; |
| 94 |
} |
| 95 |
break; |
| 96 |
} |
| 97 |
} |
| 98 |
} |
| 99 |
|
| 100 |
$return = array( $handler, $args ); |
| 101 |
return $return; |
| 102 |
} |
| 103 |
} |