1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mpociot\CaptainHook; |
4
|
|
|
|
5
|
|
|
use Illuminate\Events\Dispatcher; |
6
|
|
|
|
7
|
|
|
class EventDispatcher extends Dispatcher |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* The event firing stack. |
11
|
|
|
* |
12
|
|
|
* @var array |
13
|
|
|
*/ |
14
|
|
|
protected $firing = []; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Get the event that is currently firing. |
18
|
|
|
* |
19
|
|
|
* @return string |
20
|
|
|
*/ |
21
|
|
|
public function firing() |
22
|
|
|
{ |
23
|
|
|
return last($this->firing); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Fire an event and call the listeners. |
28
|
|
|
* |
29
|
|
|
* @param string|object $event |
30
|
|
|
* @param mixed $payload |
31
|
|
|
* @param bool $halt |
32
|
|
|
* @return array|null |
33
|
|
|
*/ |
34
|
|
|
public function dispatch($event, $payload = [], $halt = false) |
35
|
|
|
{ |
36
|
|
|
// When the given "event" is actually an object we will assume it is an event |
37
|
|
|
// object and use the class as the event name and this event itself as the |
38
|
|
|
// payload to the handler, which makes object based events quite simple. |
39
|
|
|
list($event, $payload) = $this->parseEventAndPayload( |
40
|
|
|
$event, $payload |
41
|
|
|
); |
42
|
|
|
|
43
|
|
|
$this->firing[] = $event; |
44
|
|
|
|
45
|
|
|
if ($this->shouldBroadcast($payload)) { |
46
|
|
|
$this->broadcastEvent($payload[0]); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$responses = []; |
50
|
|
|
|
51
|
|
|
foreach ($this->getListeners($event) as $listener) { |
52
|
|
|
$response = $listener($event, $payload); |
53
|
|
|
|
54
|
|
|
// If a response is returned from the listener and event halting is enabled |
55
|
|
|
// we will just return this response, and not call the rest of the event |
56
|
|
|
// listeners. Otherwise we will add the response on the response list. |
57
|
|
|
if (! is_null($response) && $halt) { |
58
|
|
|
array_pop($this->firing); |
59
|
|
|
|
60
|
|
|
return $response; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
// If a boolean false is returned from a listener, we will stop propagating |
64
|
|
|
// the event to any further listeners down in the chain, else we keep on |
65
|
|
|
// looping through the listeners and firing every one in our sequence. |
66
|
|
|
if ($response === false) { |
67
|
|
|
break; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
$responses[] = $response; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
array_pop($this->firing); |
74
|
|
|
|
75
|
|
|
return $halt ? null : $responses; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|