1 <?php
2
3 4 5 6 7
8
9 namespace nk2580\wordsmith\Routes;
10
11 use nk2580\wordsmith\Routes\Route;
12 use nk2580\wordsmith\Utillities\JsonResponse;
13
14 15 16 17 18
19 class RouteGroup {
20
21 protected $routes = [];
22 public $name;
23 private $request;
24 private $endpoint;
25
26 public function __construct($name) {
27 $this->name = $name;
28 }
29
30 public function add(Route $route) {
31 $this->routes[] = $route;
32 }
33
34 public function routes() {
35 return $this->routes;
36 }
37
38 public function run($endpoint) {
39 $this->endpoint = $endpoint;
40 $this->parseRequest();
41 $route = $this->determineRoute();
42 if ($route) {
43 $route->invoke($this->request);
44 } else {
45 JsonResponse::showError(404, 'No route matched your request');
46 }
47 }
48
49 private function parseRequest() {
50 global $wp;
51 $this->request = str_replace($this->endpoint, '', $wp->request);
52 }
53
54 private function determineRoute() {
55 foreach ($this->routes as $r) {
56
57 if (($_SERVER['REQUEST_METHOD'] == $r->getMethod())) {
58
59 if ($r->matchesRequest($this->request)) {
60 return $r;
61 }
62 }
63 }
64 }
65
66 }
67