Repository::findByName()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace MiladRahimi\PhpRouter\Routing;
4
5
use Closure;
6
7
/**
8
 * It is a repository for the defined routes
9
 */
10
class Repository
11
{
12
    /**
13
     * List of the defined routes
14
     *
15
     * @var Route[]
16
     */
17
    private array $routes = [];
18
19
    /**
20
     * Save a new route
21
     *
22
     * @param string $method
23
     * @param string $path
24
     * @param Closure|string|array $controller
25
     * @param string|null $name
26
     * @param array $middleware
27
     * @param string|null $domain
28
     */
29
    public function save(
30
        string  $method,
31
        string  $path,
32
                $controller,
33
        ?string $name,
34
        array   $middleware,
35
        ?string $domain
36
    ): void
37
    {
38
        $route = new Route($method, $path, $controller, $name, $middleware, $domain);
39
40
        $this->routes['method'][$method][] = $route;
41
42
        if ($name !== null) {
43
            $this->routes['name'][$name] = $route;
44
        }
45
    }
46
47
    /**
48
     * Find routes by method
49
     *
50
     * @param string $method
51
     * @return Route[]
52
     */
53
    public function findByMethod(string $method): array
54
    {
55
        $routes = array_merge(
56
            $this->routes['method']['*'] ?? [],
57
            $this->routes['method'][$method] ?? []
58
        );
59
60
        krsort($routes);
61
62
        return $routes;
63
    }
64
65
    /**
66
     * Find route by name
67
     *
68
     * @param string $name
69
     * @return Route|null
70
     */
71
    public function findByName(string $name): ?Route
72
    {
73
        return $this->routes['name'][$name] ?? null;
74
    }
75
76
    /**
77
     * Index all the defined routes
78
     *
79
     * @return Route[]
80
     */
81
    public function all(): array
82
    {
83
        $all = [];
84
        foreach ($this->routes['method'] as $group) {
85
            foreach ($group as $route) {
86
                $all[] = $route;
87
            }
88
        }
89
90
        return $all;
91
    }
92
}
93