Implement basic router and a controller for simfile API. Need to make some changes...
[rock.divinelegy.git] / Services / Routing / Route.php
1 <?php
2
3 namespace Services\Routing;
4
5 use Services\Routing\IRoute;
6
7 class Route implements IRoute
8 {
9 private $_controllerName;
10 private $_actionName;
11 private $_pattern;
12 private $_methods;
13
14 public function __construct($pattern, array $methods, $controllerName, $actionName = null)
15 {
16 $this->_controllerName = $controllerName;
17 $this->_actionName = $actionName;
18 $this->_pattern = $pattern;
19 $this->_methods = $methods;
20 }
21
22 public function matches($path) {
23 $argNames = array();
24
25 /*
26 * Set up a callback for preg_replace_callback. What this does is
27 * replace the :argName style arguments with named groups to match
28 * against the resource URI. So for example:
29 *
30 * my/:pattern/
31 *
32 * Becomes:
33 *
34 * my/(?P<pattern>[^/]+
35 *
36 * Then we can feed the new regex and the URI in to preg_match to
37 * extract the variables.
38 */
39 $callback = function($m) use ($argNames) {
40 /*
41 * We save away the names of the arguments in a variable so we can
42 * loop through later and put them in $this->arguments.
43 */
44 $argNames[] = $m[1];
45 return '(?P<' . $m[1] . '>[^/]+)';
46 };
47
48 $patternAsRegex = preg_replace_callback('#:([\w]+)\+?#', $callback, $this->_pattern);
49
50 if (!preg_match('#^' . $patternAsRegex . '$#', $path, $argValues))
51 return false;
52
53 return true;
54 }
55
56 public function supports($method)
57 {
58 return in_array($method, $this->_methods);
59 }
60
61 public function getControllerName()
62 {
63 return $this->_controllerName;
64 }
65
66 public function getActionName()
67 {
68 return $this->_actionName;
69 }
70 }
71