Completed
Push — master ( ba9072...49bd4f )
by Matze
06:56
created

EventCompilerPass::getEvents()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7.392

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 39
ccs 12
cts 15
cp 0.8
rs 6.7272
cc 7
eloc 23
nc 4
nop 0
crap 7.392
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
        if (!is_dir(ROOT . 'cache')) {
26
            return;
27
        }
28
29 2
        $this->dumpVariableToCache('events', $this->getEvents());
30 2
    }
31 2
32
    /**
33 2
     * @return array
34 2
     * @throws Exception
35
     */
36
    private function getEvents()
37 2
    {
38 2
        $events = [];
39 2
        foreach (get_declared_classes() as $class) {
40
            $reflection = new ReflectionClass($class);
41 2
42
            if (!$reflection->isSubclassOf(AbstractEvent::class)) {
43
                continue;
44
            }
45
46
            foreach (array_values($reflection->getConstants()) as $constant) {
47
                if (strlen($constant) < 2) {
48
                    continue;
49
                }
50
                if (isset($events[$constant])) {
51
                    throw new Exception(
52 2
                        sprintf(
53 2
                            'Event "%s" was already defined in "%s". (%s)',
54 2
                            $constant,
55
                            $events[$constant],
56
                            $class
57 2
                        )
58 2
                    );
59 2
                }
60
61
                $parameters = [];
62
                foreach ($reflection->getConstructor()->getParameters() as $parameter) {
63
                    $parameters[] = $parameter->getName();
64 2
                }
65 2
66
                $events[$constant] = [
67
                    'class'      => $class,
68
                    'parameters' => $parameters
69
                ];
70
            };
71
        }
72
73
        return $events;
74
    }
75
}
76