Completed
Push — master ( eeebc2...21cf4a )
by Matze
03:31
created

EventCompilerPass::handleEvent()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 26
ccs 7
cts 7
cp 1
rs 8.439
cc 5
eloc 16
nc 5
nop 3
crap 5
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
 * @todo add event annotation
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
15
 * @CompilerPass
16
 */
17
class EventCompilerPass implements CompilerPassInterface
18
{
19
    use FileCacheTrait;
20
21
    /**
22
     * {@inheritdoc}
23 2
     */
24
    public function process(ContainerBuilder $container)
25 2
    {
26
        $this->dumpVariableToCache('events', $this->getEvents());
27
    }
28
29 2
    /**
30 2
     * @return array
31 2
     * @throws Exception
32
     */
33 2
    private function getEvents()
34 2
    {
35
        $events = [];
36
        foreach (get_declared_classes() as $class) {
37 2
            $reflection = new ReflectionClass($class);
38 2
39 2
            if ($reflection->isSubclassOf(AbstractEvent::class)) {
40
                $this->handleEvent($reflection, $events, $class);
41 2
            }
42
        }
43
44
        return $events;
45
    }
46
47
    /**
48
     * @param ReflectionClass $reflection
49
     * @param $events
50
     * @param string $class
51
     * @throws Exception
52 2
     */
53 2
    private function handleEvent(ReflectionClass $reflection, array &$events, string $class)
54 2
    {
55
        foreach (array_values($reflection->getConstants()) as $constant) {
56
            if (strlen($constant) < 2) {
57 2
                continue;
58 2
            }
59 2
            if (isset($events[$constant])) {
60
                throw new Exception(sprintf(
61
                    'Event "%s" was already defined in "%s". (%s)',
62
                    $constant,
63
                    $events[$constant],
64 2
                    $class
65 2
                ));
66
            }
67
68
            $parameters = [];
69
            foreach ($reflection->getConstructor()->getParameters() as $parameter) {
70
                $parameters[] = $parameter->getName();
71
            }
72
73
            $events[$constant] = [
74
                'class'      => $class,
75
                'parameters' => $parameters
76
            ];
77
        }
78
    }
79
}
80