Completed
Push — master ( 3d05f5...78c728 )
by John
08:45 queued 06:38
created

GenericRouter::mapEndpointMethod()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
cc 2
eloc 2
nc 2
nop 1
crap 2
1
<?php
2
namespace LunixREST\Server;
3
4
use LunixREST\APIResponse\APIResponseData;
5
use LunixREST\Endpoint\Endpoint;
6
use LunixREST\APIRequest\APIRequest;
7
use LunixREST\Endpoint\EndpointFactory;
8
use LunixREST\Endpoint\Exceptions\ElementConflictException;
9
use LunixREST\Endpoint\Exceptions\ElementNotFoundException;
10
use LunixREST\Endpoint\Exceptions\InvalidRequestException;
11
use LunixREST\Server\Exceptions\MethodNotFoundException;
12
13
/**
14
 * An implementation of a Router that uses an EndpointFactory to find an Endpoint. Maps methods based on the get/getAll pattern.
15
 * Class GenericRouter
16
 * @package LunixREST\Server
17
 */
18
class GenericRouter implements Router
19
{
20
    /**
21
     * @var EndpointFactory
22
     */
23
    private $endpointFactory;
24
25
    /**
26
     * DefaultRouter constructor.
27
     * @param EndpointFactory $endpointFactory
28
     */
29 3
    public function __construct(EndpointFactory $endpointFactory)
30
    {
31 3
        $this->endpointFactory = $endpointFactory;
32 3
    }
33
34
    /**
35
     * @param APIRequest $request
36
     * @return APIResponseData
37
     * @throws MethodNotFoundException
38
     * @throws ElementNotFoundException
39
     * @throws InvalidRequestException
40
     * @throws ElementConflictException
41
     */
42 3
    public function route(APIRequest $request): APIResponseData
43
    {
44 3
        $endpoint = $this->endpointFactory->getEndpoint($request->getEndpoint(), $request->getVersion());
45 3
        return $this->executeEndpoint($endpoint, $request);
46
    }
47
48
    /**
49
     * @param Endpoint $endpoint
50
     * @param APIRequest $request
51
     * @return APIResponseData
52
     * @throws MethodNotFoundException
53
     * @throws ElementNotFoundException
54
     * @throws InvalidRequestException
55
     * @throws ElementConflictException
56
     */
57 3
    protected function executeEndpoint(Endpoint $endpoint, APIRequest $request): APIResponseData
58
    {
59 3
        $method = $this->mapEndpointMethod($request);
60 3
        if (!method_exists($endpoint, $method)) {
61 1
            throw new MethodNotFoundException("The endpoint method " . $method . " was not found");
62
        }
63 2
        return call_user_func([$endpoint, $method], $request);
64
    }
65
66
    /**
67
     * @param APIRequest $request
68
     * @return string
69
     */
70 3
    protected function mapEndpointMethod(APIRequest $request): string
71
    {
72 3
        return strtolower($request->getMethod()) . (!$request->getElement() ? 'All': '');
73
    }
74
}
75