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

Event::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 6
cts 6
cp 1
rs 9.4285
cc 1
eloc 5
nc 1
nop 4
crap 1
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