Passed
Pull Request — master (#196)
by Rustam
02:41
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 1
                [$groupAttribute] = $groupAttributes;
33
                /** @var Group $group */
34 1
                $group = $groupAttribute->newInstance();
35 1
                $this->routeCollector->addRoute($group->routes(...iterator_to_array($routes)));
36
            } else {
37 1
                $this->routeCollector->addRoute(...iterator_to_array($routes));
38
            }
39
        }
40
    }
41
42
    /**
43
     * @return \Generator<Route>
44
     */
45 1
    private function lookupRoutes(\ReflectionClass $reflectionClass): \Generator
46
    {
47 1
        foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
48
            foreach (
49 1
                $reflectionMethod->getAttributes(
50 1
                    Route::class,
51 1
                    \ReflectionAttribute::IS_INSTANCEOF
52 1
                ) as $reflectionAttribute
53
            ) {
54
                /** @var Route $route */
55 1
                $route = $reflectionAttribute->newInstance();
56
57 1
                yield $route->action([$reflectionClass->getName(), $reflectionMethod->getName()]);
58
            }
59
        }
60
    }
61
}
62