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
|
|
|
|