1: <?php
2:
3: namespace PHPixie\Route\Matcher;
4:
5: class Pattern
6: {
7: protected $pattern;
8: protected $defaultParameterPattern;
9: protected $parameterPatterns;
10:
11: protected $regex;
12: protected $parameterNames = array();
13:
14: public function __construct($pattern, $defaultParameterPattern = '.+?', $parameterPatterns = array())
15: {
16: $this->pattern = $pattern;
17: $this->defaultParameterPattern = $defaultParameterPattern;
18: $this->parameterPatterns = $parameterPatterns;
19: }
20:
21: protected function prepareRegex()
22: {
23: $pattern = str_replace(
24: array('(', ')'),
25: array('(?:', ')?'),
26: $this->pattern
27: );
28:
29: $parameterNames = array();
30: $parameterPatterns = $this->parameterPatterns;
31:
32: $this->regex = preg_replace_callback(
33: '#<(.*?)>#',
34: function($matches) use($parameterPatterns, &$parameterNames) {
35: $parameterNames[]= $matches[1];
36: if(array_key_exists($matches[1], $parameterPatterns)) {
37: $regexp = $parameterPatterns[$matches[1]];
38:
39: }else{
40: $regexp = '[^/]+';
41: }
42: return '('.$regexp.')';
43: },
44: $pattern
45: );
46:
47: $this->parameterNames = $parameterNames;
48: }
49:
50: protected function requireRegex()
51: {
52: if($this->regex === null) {
53: $this->prepareRegex();
54: }
55: }
56:
57: public function pattern()
58: {
59: return $this->pattern;
60: }
61:
62: public function regex()
63: {
64: $this->requireRegex();
65: return $this->regex;
66: }
67:
68: public function parameterNames()
69: {
70: $this->requireRegex();
71: return $this->parameterNames;
72: }
73:
74: public function generate($parameters)
75: {
76: $search = array();
77: $replace = array();
78: foreach($parameters as $key => $value) {
79: $search []= '<'.$key.'>';
80: $replace[]= $value;
81: }
82:
83: $remove = array('(', ')', '//');
84: foreach($remove as $string) {
85: $search[]= $string;
86: }
87:
88: $string = str_replace($search, $replace, $this->pattern);
89:
90: return $string;
91: }
92: }