Test Failed
Pull Request — main (#59)
by Dimitri
06:14
created

DefinedRouteCollector   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 51
ccs 0
cts 10
cp 0
rs 10
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
B collect() 0 37 9
1
<?php
2
3
/**
4
 * This file is part of Blitz PHP framework.
5
 *
6
 * (c) 2022 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace BlitzPHP\Router;
13
14
use Closure;
15
16
/**
17
 * Collecter tous les itinéraires définis pour affichage.
18
 */
19
final class DefinedRouteCollector
20
{
21
    /**
22
     * Routes deja collectees (pour eviter de faire la meme chose plusieurs fois)
23
     */
24
    private array $cachedRoutes = [];
25
26
    public function __construct(private readonly RouteCollection $routeCollection)
27
    {
28
    }
29
30
    /**
31
     * Collecte les routes enregistrees
32
     */
33
    public function collect(bool $reset = true): array
34
    {
35
        if (! $reset && $this->cachedRoutes !== []) {
36
            return $this->cachedRoutes;
37
        }
38
39
        $methods = Router::HTTP_METHODS;
40
41
        $definedRoutes = [];
42
43
        foreach ($methods as $method) {
44
            $routes = $this->routeCollection->getRoutes($method);
45
46
            foreach ($routes as $route => $handler) {
47
                // La clé de la route devrait être une chaîne de caractères, mais elle est stockée sous la forme d'une clé de tableau, qui peut être un entier.
48
                $route = (string) $route;
49
50
                if (is_string($handler) || $handler instanceof Closure) {
51
                    if ($handler instanceof Closure) {
52
                        $view = $this->routeCollection->getRoutesOptions($route, $method)['view'] ?? false;
53
54
                        $handler = $view ? '(View) ' . $view : '(Closure)';
55
                    }
56
57
                    $routeName = $this->routeCollection->getRoutesOptions($route, $method)['as'] ?? $route;
58
59
                    $definedRoutes[] = [
60
                        'method'  => $method,
61
                        'route'   => $route,
62
                        'name'    => $routeName,
63
                        'handler' => $handler,
64
                    ];
65
                }
66
            }
67
        }
68
69
        return $this->cachedRoutes = $definedRoutes;
70
    }
71
}
72