EventCompilerPass::handleEvent()   B
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.9256

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 10
cts 15
cp 0.6667
rs 8.5125
c 0
b 0
f 0
cc 5
eloc 14
nc 4
nop 3
crap 5.9256
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 1
    public function process(ContainerBuilder $container)
24
    {
25 1
        $this->dumpVariableToCache('events', $this->getEvents());
26 1
    }
27
28
    /**
29
     * @return array
30
     * @throws Exception
31
     */
32 1
    private function getEvents()
33
    {
34 1
        $events = [];
35 1
        foreach (get_declared_classes() as $class) {
36 1
            $reflection = new ReflectionClass($class);
37
38 1
            if ($reflection->isSubclassOf(AbstractEvent::class)) {
39 1
                $this->handleEvent($reflection, $events, $class);
40
            }
41
        }
42
43 1
        return $events;
44
    }
45
46
    /**
47
     * @param ReflectionClass $reflection
48
     * @param $events
49
     * @param string $class
50
     * @throws Exception
51
     */
52 1
    private function handleEvent(ReflectionClass $reflection, array &$events, string $class)
53
    {
54 1
        foreach (array_values($reflection->getConstants()) as $constant) {
55 1
            if (strlen($constant) < 3 || strpos($constant, '.') === false) {
56 1
                continue;
57
            }
58
59 1
            if (isset($events[$constant])) {
60
                throw new Exception(sprintf(
61
                    'Event "%s" was already defined in "%s". (%s)',
62
                    $constant,
63
                    $events[$constant],
64
                    $class
65
                ));
66
            }
67
68 1
            $parameters = $this->getParameters($reflection);
69
70 1
            $events[$constant] = [
71 1
                'class'      => $class,
72 1
                'parameters' => $parameters
73
            ];
74
        }
75 1
    }
76
77
    /**
78
     * @param ReflectionClass $reflection
79
     * @return array
80
     */
81 1
    private function getParameters(ReflectionClass $reflection)
82
    {
83 1
        $parameters = [];
84 1
        foreach ($reflection->getConstructor()->getParameters() as $parameter) {
85 1
            $parameters[] = $parameter->getName();
86
        }
87
88 1
        return $parameters;
89
    }
90
}
91