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

GenericRouter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 47
rs 10
c 0
b 0
f 0
ccs 13
cts 13
cp 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A route() 0 5 1
A executeEndpoint() 0 8 2
A mapEndpointMethod() 0 4 2
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