1
|
|
|
<?php |
2
|
|
|
namespace LunixREST\Server; |
3
|
|
|
|
4
|
|
|
use LunixREST\Endpoint\Endpoint; |
5
|
|
|
use LunixREST\Endpoint\EndpointFactory; |
6
|
|
|
use LunixREST\Endpoint\Exceptions\UnknownEndpointException; |
7
|
|
|
use LunixREST\Exceptions\MethodNotFoundException; |
8
|
|
|
use LunixREST\Request\Request; |
9
|
|
|
use LunixREST\Response\ResponseData; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class Router |
13
|
|
|
* @package LunixREST\Router |
14
|
|
|
*/ |
15
|
|
|
class Router { |
16
|
|
|
/** |
17
|
|
|
* @var EndpointFactory |
18
|
|
|
*/ |
19
|
|
|
private $endpointFactory; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param EndpointFactory $endpointFactory |
23
|
|
|
*/ |
24
|
|
|
public function __construct(EndpointFactory $endpointFactory){ |
25
|
|
|
$this->endpointFactory = $endpointFactory; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param Request $request |
30
|
|
|
* @return ResponseData |
31
|
|
|
* @throws UnknownEndpointException |
32
|
|
|
* @throws MethodNotFoundException |
33
|
|
|
*/ |
34
|
|
|
public function route(Request $request): ResponseData{ |
35
|
|
|
$endpoint = $this->endpointFactory->getEndpoint($request->getEndpoint(), $request->getVersion()); |
36
|
|
|
return $this->executeEndpoint($endpoint, $request); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param Endpoint $endpoint |
41
|
|
|
* @param Request $request |
42
|
|
|
* @return ResponseData |
43
|
|
|
* @throws MethodNotFoundException |
44
|
|
|
*/ |
45
|
|
|
protected function executeEndpoint(Endpoint $endpoint, Request $request): ResponseData { |
46
|
|
|
if(!method_exists($endpoint, $request->getMethod())){ |
47
|
|
|
throw new MethodNotFoundException("The endpoint method " . $request->getMethod() . " was not found"); |
48
|
|
|
} |
49
|
|
|
return call_user_func([$endpoint, $request->getMethod()], $request); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|