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

EventCompilerPass   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 84%

Importance

Changes 7
Bugs 1 Features 1
Metric Value
wmc 9
c 7
b 1
f 1
lcom 1
cbo 0
dl 0
loc 63
ccs 21
cts 25
cp 0.84
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getEvents() 0 13 3
A process() 0 4 1
B handleEvent() 0 26 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
 * @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