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

DefinedRouteCollector::collect()   B

Complexity

Conditions 9
Paths 7

Size

Total Lines 45
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 9.111

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 28
c 1
b 0
f 0
nc 7
nop 1
dl 0
loc 45
ccs 8
cts 9
cp 0.8889
crap 9.111
rs 8.0555
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