Passed
Push — main ( 1e579d...c0f50c )
by
unknown
08:04 queued 03:57
created

DefinedRouteCollector   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 90%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 32
c 1
b 0
f 0
dl 0
loc 62
ccs 9
cts 10
cp 0.9
rs 10
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B collect() 0 45 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
    private RouteCollection $routeCollection;
22
23
    /**
24
     * Routes deja collectees (pour eviter de faire la meme chose plusieurs fois)
25
     */
26
    private array $cachedRoutes = [];
27
28
    public function __construct(RouteCollection $routes)
29
    {
30 2
        $this->routeCollection = $routes;
31
    }
32
33
    /**
34
     * Collecte les routes enregistrees
35
     */
36
    public function collect(bool $reset = true): array
37
    {
38
        if (! $reset && $this->cachedRoutes !== []) {
39
            return $this->cachedRoutes;
40
        }
41
42
        $methods = [
43
            'get',
44
            'head',
45
            'post',
46
            'patch',
47
            'put',
48
            'delete',
49
            'options',
50
            'trace',
51
            'connect',
52
            'cli',
53 2
        ];
54
55 2
        $definedRoutes = [];
56
57
        foreach ($methods as $method) {
58 2
            $routes = $this->routeCollection->getRoutes($method);
59
60
            foreach ($routes as $route => $handler) {
61
                if (is_string($handler) || $handler instanceof Closure) {
62
                    if ($handler instanceof Closure) {
63 2
                        $view = $this->routeCollection->getRoutesOptions($route, $method)['view'] ?? false;
64
65 2
                        $handler = $view ? '(View) ' . $view : '(Closure)';
66
                    }
67
68 2
                    $routeName = $this->routeCollection->getRoutesOptions($route, $method)['as'] ?? $route;
69
70
                    $definedRoutes[] = [
71
                        'method'  => $method,
72
                        'route'   => $route,
73
                        'name'    => $routeName,
74
                        'handler' => $handler,
75 2
                    ];
76
                }
77
            }
78
        }
79
80 2
        return $this->cachedRoutes = $definedRoutes;
81
    }
82
}
83