1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Basis; |
4
|
|
|
|
5
|
|
|
use Tarantool\Mapper\Plugin\Spy; |
6
|
|
|
use ReflectionClass; |
7
|
|
|
|
8
|
|
|
class Event |
9
|
|
|
{ |
10
|
|
|
private $dispatcher; |
11
|
|
|
private $filesystem; |
12
|
|
|
private $service; |
13
|
|
|
private $spy; |
14
|
|
|
|
15
|
|
|
public function __construct(Dispatcher $dispatcher, Service $service, Spy $spy, Filesystem $filesystem) |
16
|
|
|
{ |
17
|
|
|
$this->dispatcher = $dispatcher; |
18
|
|
|
$this->filesystem = $filesystem; |
19
|
|
|
$this->service = $service; |
20
|
|
|
$this->spy = $spy; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function getSubscription() |
24
|
|
|
{ |
25
|
|
|
$subscription = []; |
26
|
|
|
foreach ($this->filesystem->listClasses('Listener') as $class) { |
27
|
|
|
$reflection = new ReflectionClass($class); |
28
|
|
|
if ($reflection->isAbstract()) { |
29
|
|
|
continue; |
30
|
|
|
} |
31
|
|
|
foreach ($reflection->getStaticPropertyValue('events') as $event) { |
32
|
|
|
if (!array_key_exists($event, $subscription)) { |
33
|
|
|
$subscription[$event] = []; |
34
|
|
|
} |
35
|
|
|
$subscription[$event][] = substr($class, strlen('Listener\\')); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
return $subscription; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function fire(string $event, $context) |
43
|
|
|
{ |
44
|
|
|
$this->dispatcher->dispatch('event.fire', [ |
45
|
|
|
'event' => $this->service->getName().'.'.$event, |
46
|
|
|
'context' => $context, |
47
|
|
|
]); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function fireChanges(string $producer) |
51
|
|
|
{ |
52
|
|
|
if ($this->spy->hasChanges()) { |
53
|
|
|
// reduce changes list |
54
|
|
|
$changes = $this->spy->getChanges(); |
55
|
|
|
foreach ($changes as $action => $collection) { |
56
|
|
|
foreach ($collection as $space => $entities) { |
57
|
|
|
$event = $this->service->getName().'.'.$space.'.'.$action; |
58
|
|
|
|
59
|
|
|
if (!$this->service->eventExists($event)) { |
60
|
|
|
unset($collection[$space]); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
if (!count($collection)) { |
64
|
|
|
unset($changes->$action); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
if (count($changes)) { |
69
|
|
|
$this->dispatcher->dispatch('event.changes', [ |
70
|
|
|
'producer' => $producer, |
71
|
|
|
'changes' => $changes, |
72
|
|
|
'service' => $this->service->getName(), |
73
|
|
|
]); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
$this->spy->reset(); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|