Completed
Push — master ( f9ded0...b13d5b )
by John
02:58 queued 01:00
created

GenericRouter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
cc 1
eloc 2
nc 1
nop 1
crap 1
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