Controller::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
namespace Phprest\Util;
4
5
use Doctrine\Common\Annotations\AnnotationReader;
6
use League\Container\ContainerInterface;
7
use League\Route\RouteCollection;
8
use Phprest\Annotation\Route;
9
use Phprest\Application;
10
use ReflectionClass;
11
use ReflectionMethod;
12
13
abstract class Controller
14
{
15
    protected ContainerInterface $container;
16
17
    /**
18
     * @param ContainerInterface $container
19
     * @param bool $registerRoutes
20
     */
21 1
    public function __construct(ContainerInterface $container, $registerRoutes = true)
22
    {
23 1
        $this->container = $container;
24
25 1
        if ($registerRoutes) {
26 1
            $this->registerRoutes();
27
        }
28 1
    }
29
30 1
    protected function registerRoutes(): void
31
    {
32 1
        $reader = new AnnotationReader();
33 1
        $class  = new ReflectionClass($this);
34
        /** @var RouteCollection $router */
35 1
        $router = $this->getContainer()->get(Application::CONTAINER_ID_ROUTER);
36
37 1
        foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
38 1
            $this->registerRoute(
39 1
                $router,
40
                $class,
41
                $method,
42 1
                $reader->getMethodAnnotation($method, Route::class)
43
            );
44
        }
45 1
    }
46
47
    /**
48
     * @param mixed $docblock
49
     */
50 1
    protected function registerRoute(
51
        RouteCollection $router,
52
        ReflectionClass $class,
53
        ReflectionMethod $method,
54
        $docblock
55
    ): void {
56 1
        if ($docblock instanceof Route) {
57 1
            $this->addVersionToRoute($docblock);
58
59 1
            $router->addRoute(
60 1
                $docblock->method,
61 1
                $docblock->path,
62 1
                '\\' . $class->getName() . '::' . $method->getName()
63
            );
64
        }
65 1
    }
66
67 1
    protected function addVersionToRoute(Route $docblock): void
68
    {
69 1
        if (! is_null($docblock->version) && $docblock->path[0] === '/') {
70 1
            $docblock->path = '/' . $docblock->version . $docblock->path;
71 1
        } elseif (! is_null($docblock->version) && $docblock->path[0] !== '/') {
72 1
            $docblock->path = '/' . $docblock->version . '/' . $docblock->path;
73
        }
74 1
    }
75
76
    /**
77
     * @return ContainerInterface
78
     */
79 1
    protected function getContainer()
80
    {
81 1
        return $this->container;
82
    }
83
}
84