Passed
Pull Request — master (#196)
by Rustam
02:30
created

RouteAttributesRegistrar::lookupRoutes()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 1
dl 0
loc 13
ccs 8
cts 8
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Router;
6
7
/**
8
 * Provides an implementation of {@see RouteAttributesRegistrarInterface} using {@see get_declared_classes()} function.
9
 */
10
final class RouteAttributesRegistrar implements RouteAttributesRegistrarInterface
11
{
12 1
    public function __construct(private RouteCollectorInterface $routeCollector)
13
    {
14 1
    }
15
16
    /**
17
     * @inheritDoc
18
     */
19 1
    public function register(): void
20
    {
21
        //TODO: caching?
22 1
        $classes = get_declared_classes();
23 1
        foreach ($classes as $class) {
24 1
            $reflectionClass = new \ReflectionClass($class);
25 1
            if (!$reflectionClass->isUserDefined()) {
26 1
                continue;
27
            }
28 1
            $routes = $this->lookupRoutes($reflectionClass);
29 1
            $groupAttributes = $reflectionClass->getAttributes(Group::class, \ReflectionAttribute::IS_INSTANCEOF);
30
31 1
            if (!empty($groupAttributes)) {
32
                [$groupAttribute] = $groupAttributes;
33
                /** @var Group $group */
34
                $group = $groupAttribute->newInstance();
35
                $this->routeCollector->addRoute($group->routes(...$routes));
36
            } else {
37 1
                $this->routeCollector->addRoute(...$routes);
38
            }
39
        }
40
    }
41
42 1
    private function lookupRoutes(\ReflectionClass $reflectionClass): iterable
43
    {
44 1
        foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
45
            foreach (
46 1
                $reflectionMethod->getAttributes(
47 1
                    Route::class,
48 1
                    \ReflectionAttribute::IS_INSTANCEOF
49 1
                ) as $reflectionAttribute
50
            ) {
51
                /** @var Route $route */
52 1
                $route = $reflectionAttribute->newInstance();
53
54 1
                yield $route->action([$reflectionClass->getName(), $reflectionMethod->getName()]);
55
            }
56
        }
57
    }
58
}
59