AnnotationReader::getControllerAnnotation()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
cc 3
nc 2
nop 1
1
<?php
2
/**
3
 * This file is part of the silex-annotation-provider package.
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 *
7
 * @license       MIT License
8
 * @copyright (c) 2018, Dana Desrosiers <[email protected]>
9
 */
10
11
declare(strict_types=1);
12
13
namespace DDesrosiers\SilexAnnotations\AnnotationReader;
14
15
use DDesrosiers\SilexAnnotations\Annotations\Controller;
16
use DDesrosiers\SilexAnnotations\Annotations\Route;
17
18
/**
19
 * Class AnnotationReader parses doc block annotations and converts them to Annotation classes.
20
 *
21
 * @author Dana Desrosiers <[email protected]>
22
 */
23
class AnnotationReader
24
{
25
    /**
26
     * @param string $className
27
     * @return Controller|null
28
     * @throws \ReflectionException
29
     */
30
    public function getControllerAnnotation(string $className): ?Controller
31
    {
32
        $reflectionClass = new \ReflectionClass($className);
33
        $docBlock = new DocBlock($reflectionClass->getDocComment());
34
        $controllerDefinition = $docBlock->parseAnnotation("Controller");
35
        if ($controllerDefinition !== null) {
36
            $prefix = $controllerDefinition['prefix'][0][0] ?? key($controllerDefinition);
37
            array_shift($controllerDefinition);
38
            $controller = new Controller($prefix);
39
            $controller->setModifiers($controllerDefinition);
40
            foreach ($this->getRouteAnnotations($reflectionClass) as $route) {
41
                $controller->addRoute($route);
42
            }
43
        }
44
45
        return $controller ?? null;
46
    }
47
48
    /**
49
     * @param \ReflectionClass  $class
50
     * @return Route[]
51
     */
52
    private function getRouteAnnotations(\ReflectionClass $class): array
53
    {
54
        $routes = [];
55
        foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
56
            if (!$method->isStatic()) {
57
                $docBlock = new DocBlock($method->getDocComment());
58
                $routeDefinition = $docBlock->parseAnnotation("Route");
59
                if ($routeDefinition !== null) {
60
                    $uri = $routeDefinition['uri'][0][0] ?? key($routeDefinition);
61
                    array_shift($routeDefinition);
62
                    $route = new Route("$class->name:$method->name", $uri);
63
                    $route->setModifiers($routeDefinition);
64
                    $routes[] = $route;
65
                }
66
            }
67
        }
68
69
        return $routes;
70
    }
71
}