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

RouteLocator::generateName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
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