Completed
Push — master ( d4fad0...05c834 )
by Kirill
26s queued 18s
created

RouteLocator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 56
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A generateName() 0 7 2
A findDeclarations() 0 25 2
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Router;
13
14
use Spiral\Annotations\AnnotatedMethod;
15
use Spiral\Annotations\AnnotationLocator;
16
use Spiral\Router\Annotation\Route as RouteAnnotation;
17
18
final class RouteLocator
19
{
20
    /** @var AnnotationLocator */
21
    private $locator;
22
23
    /**
24
     * @param AnnotationLocator $locator
25
     */
26
    public function __construct(AnnotationLocator $locator)
27
    {
28
        $this->locator = $locator;
29
    }
30
31
    /**
32
     * @return array
33
     */
34
    public function findDeclarations(): array
35
    {
36
        $routes = iterator_to_array($this->locator->findMethods(RouteAnnotation::class));
37
        uasort($routes, static function (AnnotatedMethod $route1, AnnotatedMethod $route2) {
38
            return $route1->getAnnotation()->priority <=> $route2->getAnnotation()->priority;
39
        });
40
41
        $result = [];
42
        foreach ($routes as $match) {
43
            /** @var RouteAnnotation $route */
44
            $route = $match->getAnnotation();
45
            $routeName = $route->name ?? $this->generateName($route);
46
47
            $result[$routeName] = [
48
                'pattern'    => $route->route,
49
                'controller' => $match->getClass()->getName(),
50
                'action'     => $match->getMethod()->getName(),
51
                'group'      => $route->group,
52
                'verbs'      => (array) $route->methods,
53
                'defaults'   => $route->defaults,
54
                'middleware' => (array) $route->middleware,
55
            ];
56
        }
57
58
        return $result;
59
    }
60
61
    /**
62
     * Generates route name based on declared methods and route.
63
     *
64
     * @param RouteAnnotation $route
65
     * @return string
66
     */
67
    private function generateName(RouteAnnotation $route): string
68
    {
69
        $methods = is_array($route->methods)
70
            ? implode(',', $route->methods)
71
            : $route->methods;
72
73
        return mb_strtolower(sprintf('%s:%s', $methods, $route->route));
74
    }
75
}
76