Completed
Push — master ( 5e1cd2...38f1ea )
by Matze
03:32
created

EventCompilerPass::process()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 6
Bugs 1 Features 0
Metric Value
c 6
b 1
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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 = [];
68 2
            foreach ($reflection->getConstructor()->getParameters() as $parameter) {
69 2
                $parameters[] = $parameter->getName();
70
            }
71
72 2
            $events[$constant] = [
73 2
                'class'      => $class,
74 2
                'parameters' => $parameters
75
            ];
76
        }
77 2
    }
78
}
79