Passed
Pull Request — master (#196)
by Rustam
12:45
created

RouteAttributesRegistrar::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 1
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 1
ccs 0
cts 1
cp 0
crap 2
rs 10
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
    public function __construct(private RouteCollectorInterface $collector) {
13
    }
14
15
    /**
16
     * @inheritDoc
17
     */
18
    public function register(): void
19
    {
20
        //TODO: caching?
21
        $classes = get_declared_classes();
22
        foreach ($classes as $class) {
23
            $reflectionClass = new \ReflectionClass($class);
24
            if (!$reflectionClass->isUserDefined()) {
25
                continue;
26
            }
27
            $routes = $this->getRoutes($reflectionClass);
28
            $groupAttributes = $reflectionClass->getAttributes(Group::class, \ReflectionAttribute::IS_INSTANCEOF);
29
30
            if (!empty($groupAttributes)) {
31
                [$groupAttribute] = $groupAttributes;
32
                /** @var Group $group */
33
                $group = $groupAttribute->newInstance();
34
                $this->collector->addRoute($group->routes(...$routes));
35
            } else {
36
                $this->collector->addRoute(...$routes);
37
            }
38
        }
39
    }
40
41
    private function getRoutes(\ReflectionClass $reflectionClass): iterable
42
    {
43
        foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
44
            foreach (
45
                $reflectionMethod->getAttributes(
46
                    Route::class,
47
                    \ReflectionAttribute::IS_INSTANCEOF
48
                ) as $reflectionAttribute
49
            ) {
50
                /** @var Route $route */
51
                $route = $reflectionAttribute->newInstance();
52
53
                yield $route->action([$reflectionClass->getName(), $reflectionMethod->getName()]);
54
            }
55
        }
56
    }
57
}
58