Skip to content

Commit 0f76617

Browse files
committed
work on event refactoring
1 parent 965afe0 commit 0f76617

2 files changed

Lines changed: 44 additions & 11 deletions

File tree

src/Illuminate/Events/Dispatcher.php

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -221,22 +221,15 @@ public function fire($event, $payload = [], $halt = false)
221221
// When the given "event" is actually an object we will assume it is an event
222222
// object and use the class as the event name and this event itself as the
223223
// payload to the handler, which makes object based events quite simple.
224-
if (is_object($event)) {
225-
list($payload, $event) = [[$event], get_class($event)];
226-
}
224+
list($event, $payload) = $this->parseEventAndPayload(
225+
$event, $payload
226+
);
227227

228228
$responses = [];
229229

230-
// If an array is not given to us as the payload, we will turn it into one so
231-
// we can easily use call_user_func_array on the listeners, passing in the
232-
// payload to each of them so that they receive each of these arguments.
233-
if (! is_array($payload)) {
234-
$payload = [$payload];
235-
}
236-
237230
$this->firing[] = $event;
238231

239-
if (isset($payload[0]) && $payload[0] instanceof ShouldBroadcast) {
232+
if ($this->shouldBroadcast($payload)) {
240233
$this->broadcastEvent($payload[0]);
241234
}
242235

@@ -267,6 +260,33 @@ public function fire($event, $payload = [], $halt = false)
267260
return $halt ? null : $responses;
268261
}
269262

263+
/**
264+
* Parse the given event and payload and prepare them for dispatching.
265+
*
266+
* @param mixed $event
267+
* @param mixed $payload
268+
* @return array
269+
*/
270+
protected function parseEventAndPayload($event, $payload)
271+
{
272+
if (is_object($event)) {
273+
list($payload, $event) = [[$event], get_class($event)];
274+
}
275+
276+
return [$event, array_wrap($payload)];
277+
}
278+
279+
/**
280+
* Determine if the payload has a broadcastable event.
281+
*
282+
* @param array $payload
283+
* @return bool
284+
*/
285+
protected function shouldBroadcast(array $payload)
286+
{
287+
return isset($payload[0]) && $payload[0] instanceof ShouldBroadcast;
288+
}
289+
270290
/**
271291
* Broadcast the given event class.
272292
*

src/Illuminate/Support/helpers.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,19 @@ function array_where($array, callable $callback)
302302
}
303303
}
304304

305+
if (! function_exists('array_wrap')) {
306+
/**
307+
* If the given value is not an array, wrap it in one.
308+
*
309+
* @param mixed $value
310+
* @return array
311+
*/
312+
function array_wrap($value)
313+
{
314+
return ! is_array($value) ? [$value] : $value;
315+
}
316+
}
317+
305318
if (! function_exists('camel_case')) {
306319
/**
307320
* Convert a value to camel case.

0 commit comments

Comments
 (0)