RouteFactory::createRoutesFrom()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 17
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 32
rs 9.3888
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace inroutephp\inroute\Compiler\Doctrine;
6
7
use inroutephp\inroute\Compiler\RouteFactoryInterface;
8
use inroutephp\inroute\Compiler\RouteCollectionInterface;
9
use inroutephp\inroute\Compiler\RouteCollection;
10
use inroutephp\inroute\Runtime\Route as RouteObject;
11
use Doctrine\Common\Annotations\AnnotationReader;
12
13
final class RouteFactory implements RouteFactoryInterface
14
{
15
    /**
16
     * @var AnnotationReader
17
     */
18
    private $reader;
19
20
    public function __construct(AnnotationReader $reader = null)
21
    {
22
        $this->reader = $reader ?: new AnnotationReader;
23
    }
24
25
    public function createRoutesFrom(string $classname): RouteCollectionInterface
26
    {
27
        if (!class_exists($classname)) {
28
            return new RouteCollection([]);
29
        }
30
31
        $classReflector = new \ReflectionClass($classname);
32
33
        if (!$classReflector->isInstantiable()) {
34
            return new RouteCollection([]);
35
        }
36
37
        $classAnnotations = $this->reader->getClassAnnotations($classReflector);
38
39
        $routes = [];
40
41
        foreach ($classReflector->getMethods(\ReflectionMethod::IS_PUBLIC) as $methodReflector) {
42
            if ($methodReflector->isConstructor()) {
43
                continue;
44
            }
45
46
            $routes[] = new RouteObject(
47
                $classReflector->getName(),
48
                $methodReflector->getName(),
49
                array_merge(
50
                    $classAnnotations,
51
                    $this->reader->getMethodAnnotations($methodReflector)
52
                )
53
            );
54
        }
55
56
        return new RouteCollection($routes);
57
    }
58
}
59