1 <?php
2
3 4 5 6 7
8
9 namespace nk2580\wordsmith\Routes;
10
11 use nk2580\wordsmith\Routes\RouteFactory;
12
13 14 15 16 17
18 class Route {
19
20 protected $method;
21 protected $uri;
22 protected $group;
23 protected $action;
24 protected $parameters;
25
26 public function __construct($method, $group, $uri, $action) {
27 $this->method = $method;
28 $this->uri = $uri;
29 $this->group = $group;
30 $this->action = $action;
31 }
32
33 public function getGroup() {
34 return $this->group;
35 }
36
37 public function getURI() {
38 return $this->uri;
39 }
40
41 public function getAction() {
42 return $this->action;
43 }
44
45 public function getMethod() {
46 return $this->method;
47 }
48
49 public static function get($group, $uri, $action) {
50 $route = new self('GET', $group, $uri, $action);
51 RouteFactory::addRoute($route);
52 }
53
54 public static function post($group, $uri, $action) {
55 $route = new self('POST', $group, $uri, $action);
56 RouteFactory::addRoute($route);
57 }
58
59 public function invoke($request) {
60 if (is_object($this->action) && ($this->action instanceof Closure)) {
61 $this->action();
62 } else {
63 $parts = $pieces = explode("@", $this->action);
64 $class = $parts[0];
65 $method = $parts[1];
66 $obj = new $class();
67 if ($this->hasParameters()) {
68 $this->setupParams($request);
69 call_user_func_array(array($obj, $method), $this->parameters);
70 } else {
71 $obj->$method();
72 }
73 }
74 }
75
76 public function matchesRequest($request) {
77 if ($request == $this->getURI()) {
78 return true;
79 } else if ($this->hasParameters()) {
80 return preg_match($this->regexURI(), $request);
81 } else {
82 return false;
83 }
84 }
85
86 private function hasParameters() {
87 return preg_match('/\{(.*?)\}/', $this->uri);
88 }
89
90 public function regexURI() {
91 $raw = preg_replace('/\{(.*?)\}/', "([a-zA-Z0-9]+)", $this->uri);
92 $processed = preg_replace("/\//", "\/", $raw);
93 return "/" . $processed . "$/";
94 }
95
96 private function setupParams($request) {
97 $params = array();
98 preg_match($this->regexURI(), $request, $params);
99 unset($params[0]);
100 $this->parameters = $params;
101 }
102
103 }
104