Completed
Push — master ( 73f336...7e2fc0 )
by John
01:53
created

Router::route()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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