1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BrainExe\Core\DependencyInjection\CompilerPass; |
4
|
|
|
|
5
|
|
|
use BrainExe\Core\Annotations\CompilerPass; |
6
|
|
|
use BrainExe\Core\EventDispatcher\AbstractEvent; |
7
|
|
|
use BrainExe\Core\Traits\FileCacheTrait; |
8
|
|
|
use Exception; |
9
|
|
|
use ReflectionClass; |
10
|
|
|
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; |
11
|
|
|
use Symfony\Component\DependencyInjection\ContainerBuilder; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @CompilerPass |
15
|
|
|
*/ |
16
|
|
|
class EventCompilerPass implements CompilerPassInterface |
17
|
|
|
{ |
18
|
|
|
use FileCacheTrait; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* {@inheritdoc} |
22
|
|
|
*/ |
23
|
2 |
|
public function process(ContainerBuilder $container) |
24
|
|
|
{ |
25
|
2 |
|
$this->dumpVariableToCache('events', $this->getEvents()); |
26
|
2 |
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @return array |
30
|
|
|
* @throws Exception |
31
|
|
|
*/ |
32
|
2 |
|
private function getEvents() |
33
|
|
|
{ |
34
|
2 |
|
$events = []; |
35
|
2 |
|
foreach (get_declared_classes() as $class) { |
36
|
2 |
|
$reflection = new ReflectionClass($class); |
37
|
|
|
|
38
|
2 |
|
if ($reflection->isSubclassOf(AbstractEvent::class)) { |
39
|
2 |
|
$this->handleEvent($reflection, $events, $class); |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
2 |
|
return $events; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param ReflectionClass $reflection |
48
|
|
|
* @param $events |
49
|
|
|
* @param string $class |
50
|
|
|
* @throws Exception |
51
|
|
|
*/ |
52
|
2 |
|
private function handleEvent(ReflectionClass $reflection, array &$events, string $class) |
53
|
|
|
{ |
54
|
2 |
|
foreach (array_values($reflection->getConstants()) as $constant) { |
55
|
2 |
|
if (strlen($constant) < 2) { |
56
|
|
|
continue; |
57
|
|
|
} |
58
|
2 |
|
if (isset($events[$constant])) { |
59
|
|
|
throw new Exception(sprintf( |
60
|
|
|
'Event "%s" was already defined in "%s". (%s)', |
61
|
|
|
$constant, |
62
|
|
|
$events[$constant], |
63
|
|
|
$class |
64
|
|
|
)); |
65
|
|
|
} |
66
|
|
|
|
67
|
2 |
|
$parameters = $this->getParameters($reflection); |
68
|
|
|
|
69
|
2 |
|
$events[$constant] = [ |
70
|
2 |
|
'class' => $class, |
71
|
2 |
|
'parameters' => $parameters |
72
|
|
|
]; |
73
|
|
|
} |
74
|
2 |
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @param ReflectionClass $reflection |
78
|
|
|
* @return array |
79
|
|
|
*/ |
80
|
2 |
|
private function getParameters(ReflectionClass $reflection) |
81
|
|
|
{ |
82
|
2 |
|
$parameters = []; |
83
|
2 |
|
foreach ($reflection->getConstructor()->getParameters() as $parameter) { |
84
|
2 |
|
$parameters[] = $parameter->getName(); |
85
|
|
|
} |
86
|
|
|
|
87
|
2 |
|
return $parameters; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|