Completed
Push — master ( 86cfb6...ebc154 )
by Dmitry
03:36
created

Event::getSubscription()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 18
ccs 10
cts 11
cp 0.9091
rs 8.8571
cc 5
eloc 11
nc 3
nop 0
crap 5.0187
1
<?php
2
3
namespace Basis;
4
5
use Tarantool\Mapper\Plugins\Spy;
6
use ReflectionClass;
7
8
class Event
9
{
10
    private $dispatcher;
11
    private $filesystem;
12
    private $service;
13
    private $spy;
14
15 1
    public function __construct(Dispatcher $dispatcher, Service $service, Spy $spy, Filesystem $filesystem)
16
    {
17 1
        $this->dispatcher = $dispatcher;
18 1
        $this->filesystem = $filesystem;
19 1
        $this->service = $service;
20 1
        $this->spy = $spy;
21 1
    }
22
23 1
    public function getSubscription()
24
    {
25 1
        $subscription = [];
26 1
        foreach ($this->filesystem->listClasses('Listeners') as $class) {
27 1
            $reflection = new ReflectionClass($class);
28 1
            if ($reflection->isAbstract()) {
29
                continue;
30
            }
31 1
            foreach ($reflection->getStaticPropertyValue('events') as $event) {
32 1
                if (!array_key_exists($event, $subscription)) {
33 1
                    $subscription[$event] = [];
34
                }
35 1
                $subscription[$event][] = substr($class, strlen('Listeners\\'));
36
            }
37
        }
38
39 1
        return $subscription;
40
    }
41
42
    public function fireChanges()
43
    {
44
        if ($this->spy->hasChanges()) {
45
            // reduce changes list
46
            $changes = $this->spy->getChanges();
47
            foreach ($changes as $action => $collection) {
48
                foreach ($collection as $space => $entities) {
49
                    $event = $this->service->getName().'.'.$space.'.'.$action;
50
51
                    if (!$this->service->eventExists($event)) {
52
                        unset($collection[$space]);
53
                    }
54
                }
55
                if (!count($collection)) {
56
                    unset($changes->$action);
57
                }
58
            }
59
60
            if (count($changes)) {
61
                $this->dispatcher->dispatch('event.changes', [
62
                    'changes' => $changes,
63
                    'service' => $this->service->getName(),
64
                ]);
65
            }
66
67
            $this->spy->reset();
68
        }
69
    }
70
}
71