|
| 1 | +<?php |
| 2 | +namespace Com\Tqdev\CrudApi\Router; |
| 3 | + |
| 4 | +use Com\Tqdev\CrudApi\Data\ErrorCode; |
| 5 | +use Com\Tqdev\CrudApi\Data\PathTree; |
| 6 | +use Com\Tqdev\CrudApi\Controller\Responder; |
| 7 | +use Com\Tqdev\CrudApi\Request; |
| 8 | +use Com\Tqdev\CrudApi\Response; |
| 9 | + |
| 10 | +class SimpleRouter implements Router |
| 11 | +{ |
| 12 | + private $responder; |
| 13 | + private $routes; |
| 14 | + private $midlewares; |
| 15 | + |
| 16 | + public function __construct(Responder $responder) |
| 17 | + { |
| 18 | + $this->responder = $responder; |
| 19 | + $this->routes = new PathTree(); |
| 20 | + $this->middlewares = array(); |
| 21 | + } |
| 22 | + |
| 23 | + public function register(String $method, String $path, array $handler) |
| 24 | + { |
| 25 | + $parts = explode('/', trim($path, '/')); |
| 26 | + array_unshift($parts, $method); |
| 27 | + $this->routes->put($parts, $handler); |
| 28 | + } |
| 29 | + |
| 30 | + public function load(Middleware $middleware)/*: void*/ |
| 31 | + { |
| 32 | + if (count($this->middlewares) > 0) { |
| 33 | + $next = $this->middlewares[0]; |
| 34 | + } else { |
| 35 | + $next = $this; |
| 36 | + } |
| 37 | + $middleware->setNext($next); |
| 38 | + array_unshift($this->middlewares, $middleware); |
| 39 | + } |
| 40 | + |
| 41 | + public function route(Request $request): Response |
| 42 | + { |
| 43 | + $obj = $this; |
| 44 | + if (count($this->middlewares) > 0) { |
| 45 | + $obj = $this->middlewares[0]; |
| 46 | + } |
| 47 | + return $obj->handle($request); |
| 48 | + } |
| 49 | + |
| 50 | + public function handle(Request $request): Response |
| 51 | + { |
| 52 | + $method = strtoupper($request->getMethod()); |
| 53 | + $path = explode('/', trim($request->getPath(0), '/')); |
| 54 | + array_unshift($path, $method); |
| 55 | + |
| 56 | + $functions = $this->matchPath($path, $this->routes); |
| 57 | + if (count($functions) == 0) { |
| 58 | + return $this->responder->error(ErrorCode::ROUTE_NOT_FOUND, $request->getPath()); |
| 59 | + } |
| 60 | + return call_user_func($functions[0], $request); |
| 61 | + } |
| 62 | + |
| 63 | + private function matchPath(array $path, PathTree $tree): array |
| 64 | + { |
| 65 | + $values = array(); |
| 66 | + while (count($path) > 0) { |
| 67 | + $key = array_shift($path); |
| 68 | + if ($tree->has($key)) { |
| 69 | + $tree = $tree->get($key); |
| 70 | + } else if ($tree->has('*')) { |
| 71 | + $tree = $tree->get('*'); |
| 72 | + } else { |
| 73 | + $tree = null; |
| 74 | + break; |
| 75 | + } |
| 76 | + } |
| 77 | + if ($tree !== null) { |
| 78 | + $values = $tree->getValues(); |
| 79 | + } |
| 80 | + return $values; |
| 81 | + } |
| 82 | +} |
0 commit comments