Router::getRoute()   B
last analyzed

Complexity

Conditions 7
Paths 12

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 11
c 0
b 0
f 0
nc 12
nop 1
dl 0
loc 17
rs 8.8333
1
<?php
2
3
namespace pjpawel\LightApi\Route;
4
5
use Exception;
6
use pjpawel\LightApi\Http\Exception\HttpException;
7
use pjpawel\LightApi\Http\Exception\MethodNotAllowedHttpException;
8
use pjpawel\LightApi\Http\Exception\NotFoundHttpException;
9
use pjpawel\LightApi\Http\Request;
10
use pjpawel\LightApi\Http\Response;
11
use pjpawel\LightApi\Http\ResponseStatus;
12
13
class Router
14
{
15
16
    /**
17
     * @var Route[]
18
     */
19
    public array $routes = [];
20
21
    /**
22
     * Register new route
23
     *
24
     * @param string $className
25
     * @param string $methodName
26
     * @param string $path
27
     * @param array $httpMethods
28
     * @return void
29
     * @throws \ReflectionException
30
     */
31
    public function registerRoute(string $className, string $methodName, string $path, array $httpMethods): void
32
    {
33
        $route = new Route($className, $methodName, $path, $httpMethods);
34
        $route->makeRegexPath();
35
        $this->routes[] = $route;
36
    }
37
38
    /**
39
     * @param Request $request
40
     * @return Route
41
     * @throws NotFoundHttpException
42
     * @throws MethodNotAllowedHttpException
43
     */
44
    public function getRoute(Request $request): Route
45
    {
46
        $methodNotAllowed = false;
47
        foreach ($this->routes as $route) {
48
            if (preg_match($route->regexPath, $request->path) === 1) {
49
                if (!empty($route->httpMethods) && !in_array($request->method, $route->httpMethods)) {
50
                    $methodNotAllowed = true;
51
                } else {
52
                    $matchedRoute = $route;
53
                }
54
                break;
55
            }
56
        }
57
        if (!isset($matchedRoute)) {
58
            throw $methodNotAllowed ? new MethodNotAllowedHttpException() : new NotFoundHttpException();
59
        }
60
        return $matchedRoute;
61
    }
62
63
    public function getErrorResponse(Exception|HttpException $exception): Response
64
    {
65
        if ($exception instanceof HttpException) {
66
            return new Response($exception->getMessage(), ResponseStatus::from($exception->getCode()));
67
        } else {
68
            return new Response('Internal server error occurred', ResponseStatus::INTERNAL_SERVER_ERROR);
69
        }
70
    }
71
}