-
Notifications
You must be signed in to change notification settings - Fork 1
/
ReceiveEvent.php
107 lines (90 loc) · 2.67 KB
/
ReceiveEvent.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
declare(strict_types=1);
namespace Spiral\Livewire\Component\Trait;
use Spiral\Livewire\Component\Event;
use Spiral\Livewire\Event\Component\ActionReturned;
use Spiral\Livewire\Exception\Component\BadMethodCallException;
// TODO refactor or remove this trait
trait ReceiveEvent
{
protected array $eventQueue = [];
protected array $dispatchQueue = [];
protected array $listeners = [];
protected function getListeners(): array
{
return $this->listeners;
}
/**
* @param non-empty-string $event
*/
public function emit(string $event, mixed ...$params): Event
{
return $this->eventQueue[] = new Event($event, $params);
}
/**
* @param non-empty-string $event
*/
public function emitUp(string $event, mixed ...$params): void
{
$this->emit($event, ...$params)->up();
}
/**
* @param non-empty-string $event
*/
public function emitSelf(string $event, mixed ...$params): void
{
$this->emit($event, ...$params)->self();
}
/**
* @param non-empty-string $name
* @param non-empty-string $event
*/
public function emitTo(string $name, string $event, mixed ...$params): void
{
$this->emit($event, ...$params)->component($name);
}
/**
* @param non-empty-string $event
*/
public function dispatchBrowserEvent(string $event, mixed $data = null): void
{
$this->dispatchQueue[] = [
'event' => $event,
'data' => $data,
];
}
public function getEventQueue(): array
{
return array_map(static fn (Event $event) => $event->serialize(), $this->eventQueue);
}
public function getDispatchQueue(): array
{
return $this->dispatchQueue;
}
protected function getEventsAndHandlers(): array
{
$handlers = [];
foreach ($this->getListeners() as $key => $listener) {
$handlers[is_numeric($key) ? $listener : $key] = $listener;
}
return $handlers;
}
public function getEventsBeingListenedFor(): array
{
return array_keys($this->getEventsAndHandlers());
}
/**
* @param non-empty-string $event
* @param non-empty-string $id
*
* @throws BadMethodCallException
*/
public function fireEvent(string $event, mixed $params, string $id): void
{
$method = $this->getEventsAndHandlers()[$event];
/** @psalm-suppress UndefinedMagicMethod */
$this->callMethod($method, $params, function (mixed $returned) use ($event, $id) {
$this->livewireDispatcher->dispatch(new ActionReturned($this, $event, $returned, $id));
});
}
}