Passed
Pull Request — main (#6)
by Chema
02:20
created

Routing::findRedirectRoute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
nc 3
nop 2
dl 0
loc 8
rs 10
c 1
b 0
f 0
ccs 5
cts 5
cp 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Router;
6
7
/**
8
 * @method static get(string $path, object|string $controller, string $action = '__invoke')
9
 * @method static head(string $path, object|string $controller, string $action = '__invoke')
10
 * @method static connect(string $path, object|string $controller, string $action = '__invoke')
11
 * @method static post(string $path, object|string $controller, string $action = '__invoke')
12
 * @method static delete(string $path, object|string $controller, string $action = '__invoke')
13
 * @method static options(string $path, object|string $controller, string $action = '__invoke')
14
 * @method static patch(string $path, object|string $controller, string $action = '__invoke')
15
 * @method static put(string $path, object|string $controller, string $action = '__invoke')
16
 * @method static trace(string $path, object|string $controller, string $action = '__invoke')
17
 */
18
final class Routing
19
{
20
    /**
21
     * @param callable(RoutingConfigurator):void $fn
22
     */
23 65
    public static function configure(callable $fn): void
24
    {
25 65
        $routingConfigurator = new RoutingConfigurator();
26 65
        $fn($routingConfigurator);
27
28 64
        $route = self::findRoute($routingConfigurator);
29
30 64
        if ($route) {
0 ignored issues
show
introduced by
$route is of type Gacela\Router\Route, thus it always evaluated to true.
Loading history...
31 60
            echo $route->run($routingConfigurator);
32
        }
33
    }
34
35 64
    private static function findRoute(RoutingConfigurator $routingConfigurator): ?Route
36
    {
37 64
        foreach ($routingConfigurator->routes() as $route) {
38 64
            if ($route->methodMatches()) {
39 62
                $redirect = $routingConfigurator->redirects()[$route->path()] ?? null;
40 62
                if ($redirect !== null) {
41 11
                    return self::findRedirectRoute($redirect, $routingConfigurator);
42
                }
43
            }
44
45 61
            if ($route->requestMatches()) {
46 50
                return $route;
47
            }
48
        }
49
50 3
        return null;
51
    }
52
53 11
    private static function findRedirectRoute(Redirect $redirect, RoutingConfigurator $routingConfigurator): ?Route
54
    {
55 11
        foreach ($routingConfigurator->routes() as $route) {
56 11
            if ($route->isRedirected($redirect)) {
57 10
                return $route;
58
            }
59
        }
60 1
        return null;
61
    }
62
}
63