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