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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| <?php
class Route {
protected $_template;
protected $_pattern;
protected $_keys;
protected $_params;
protected $_options;
public function __construct ($template, array $params = array(), array $options = array()) {
$this->_template = $template;
$this->_params = $params;
if (isset($options['module']) && is_string($options['module']))
$options['module'] = array($options['module']);
$this->_options = $options;
$this->_keys = array();
}
public function match ($url) {
$url = '/' . trim($url, '/');
if (empty($this->_pattern))
$this->_compileTemplate($this->_template);
if (preg_match($this->_pattern, $url, $matches)) {
unset($matches[0]);
if (!empty($this->_keys) && !empty($matches)) {
$this->_params = array_merge($this->_params, array_combine($this->_keys, $matches));
}
return true;
}
return false;
}
protected function _compileTemplate ($template) {
$token = strtok($template, '/');
$pattern_pieces = array();
$current_key = 1;
do {
if (preg_match('~{:(.+)}~', $token, $matches)) {
if ($matches[1] === 'lang') {
$key = 'lang';
$subpattern = "([a-z]{2})";
}
elseif ($matches[1] === 'id') {
$key = 'id';
$subpattern = "([0-9]+)";
}
elseif ($matches[1] === 'controller' || $matches[1] === 'action') {
$key = $matches[1];
$subpattern = "(\w{3,})";
}
elseif (($offset = strpos($matches[1], ':')) !== false) {
list($key, $subpattern) = explode(':', $matches[1]);
$subpattern = "($subpattern)";
}
else {
$key = $matches[1];
$subpattern = "([^/]+)";
}
$pattern_pieces[] = $subpattern;
$this->_keys[$current_key++] = $key;
}
else {
$pattern_pieces[] = $token;
}
} while ($token = strtok('/'));
$this->_pattern = '~^/' . implode('/', $pattern_pieces) . '$~';
}
public function getParams () {
return $this->_params;
}
public function getOptions () {
return $this->_options;
}
public function getTemplate () {
return $this->_template;
}
public function getPattern () {
return $this->_pattern;
}
} |
Partager