1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace pjpawel\LightApi\Component; |
4
|
|
|
|
5
|
|
|
use pjpawel\LightApi\Command\AsCommand; |
6
|
|
|
use pjpawel\LightApi\Command\CommandsLoader; |
7
|
|
|
use pjpawel\LightApi\Container\ContainerLoader; |
8
|
|
|
use pjpawel\LightApi\Route\AsRoute; |
9
|
|
|
use pjpawel\LightApi\Route\Router; |
10
|
|
|
use pjpawel\LightApi\Exception\ProgrammerException; |
11
|
|
|
use ReflectionClass; |
12
|
|
|
|
13
|
|
|
class ClassWalker |
14
|
|
|
{ |
15
|
|
|
|
16
|
|
|
private string $servicePath; |
17
|
|
|
|
18
|
|
|
public function __construct(string $servicePath) |
19
|
|
|
{ |
20
|
|
|
$this->servicePath = $servicePath; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param ContainerLoader $containerLoader |
25
|
|
|
* @param Router $router |
26
|
|
|
* @param CommandsLoader $commandsLoader |
27
|
|
|
* @return void |
28
|
|
|
* @throws ProgrammerException |
29
|
|
|
* @throws \ReflectionException |
30
|
|
|
*/ |
31
|
|
|
public function register( |
32
|
|
|
ContainerLoader $containerLoader, |
33
|
|
|
Router $router, |
34
|
|
|
CommandsLoader $commandsLoader |
35
|
|
|
): void |
36
|
|
|
{ |
37
|
|
|
if (is_file($this->servicePath) || !is_dir($this->servicePath)) { |
38
|
|
|
//TODO: this will be covered soon |
39
|
|
|
throw new ProgrammerException('Cannot load path that is not directory'); |
40
|
|
|
} |
41
|
|
|
$classFinder = new ClassFinder(); |
42
|
|
|
foreach ($classFinder->getAllClassInDir($this->servicePath) as $className) { |
43
|
|
|
/* Add to container */ |
44
|
|
|
$containerLoader->add(['name' => $className]); |
45
|
|
|
/* Add routes or command if exists */ |
46
|
|
|
$reflectionClass = new ReflectionClass($className); |
47
|
|
|
$commandAttribute = $reflectionClass->getAttributes(AsCommand::class); |
48
|
|
|
if (!empty($commandAttribute)) { |
49
|
|
|
$commandsLoader->registerCommand($commandAttribute[0]->getArguments()[0], $className); |
50
|
|
|
} |
51
|
|
|
foreach ($reflectionClass->getMethods() as $method) { |
52
|
|
|
$attributes = $method->getAttributes(AsRoute::class); |
53
|
|
|
if (!empty($attributes)) { |
54
|
|
|
$attribute = $attributes[0]; |
55
|
|
|
$arguments = $attribute->getArguments(); |
56
|
|
|
$router->registerRoute( |
57
|
|
|
$className, |
58
|
|
|
$method->getName(), |
59
|
|
|
$arguments[0], |
60
|
|
|
$arguments[1] ?? []); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |