1
|
<?php
|
2
|
|
3
|
namespace Illuminate\Broadcasting;
|
4
|
|
5
|
use ReflectionClass;
|
6
|
use ReflectionProperty;
|
7
|
use Illuminate\Contracts\Queue\Job;
|
8
|
use Illuminate\Contracts\Support\Arrayable;
|
9
|
use Illuminate\Contracts\Broadcasting\Broadcaster;
|
10
|
|
11
|
class BroadcastEvent
|
12
|
{
|
13
|
/**
|
14
|
* The broadcaster implementation.
|
15
|
*
|
16
|
* @var \Illuminate\Contracts\Broadcasting\Broadcaster
|
17
|
*/
|
18
|
protected $broadcaster;
|
19
|
|
20
|
/**
|
21
|
* Create a new job handler instance.
|
22
|
*
|
23
|
* @param \Illuminate\Contracts\Broadcasting\Broadcaster $broadcaster
|
24
|
* @return void
|
25
|
*/
|
26
|
public function __construct(Broadcaster $broadcaster)
|
27
|
{
|
28
|
$this->broadcaster = $broadcaster;
|
29
|
}
|
30
|
|
31
|
/**
|
32
|
* Handle the queued job.
|
33
|
*
|
34
|
* @param \Illuminate\Contracts\Queue\Job $job
|
35
|
* @param array $data
|
36
|
* @return void
|
37
|
*/
|
38
|
public function fire(Job $job, array $data)
|
39
|
{
|
40
|
$event = unserialize($data['event']);
|
41
|
|
42
|
$name = method_exists($event, 'broadcastAs')
|
43
|
? $event->broadcastAs() : get_class($event);
|
44
|
|
45
|
$this->broadcaster->broadcast(
|
46
|
$event->broadcastOn(), $name, $this->getPayloadFromEvent($event)
|
47
|
);
|
48
|
|
49
|
$job->delete();
|
50
|
}
|
51
|
|
52
|
/**
|
53
|
* Get the payload for the given event.
|
54
|
*
|
55
|
* @param mixed $event
|
56
|
* @return array
|
57
|
*/
|
58
|
protected function getPayloadFromEvent($event)
|
59
|
{
|
60
|
if (method_exists($event, 'broadcastWith')) {
|
61
|
return $event->broadcastWith();
|
62
|
}
|
63
|
|
64
|
$payload = [];
|
65
|
|
66
|
foreach ((new ReflectionClass($event))->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
|
67
|
$payload[$property->getName()] = $this->formatProperty($property->getValue($event));
|
68
|
}
|
69
|
|
70
|
return $payload;
|
71
|
}
|
72
|
|
73
|
/**
|
74
|
* Format the given value for a property.
|
75
|
*
|
76
|
* @param mixed $value
|
77
|
* @return mixed
|
78
|
*/
|
79
|
protected function formatProperty($value)
|
80
|
{
|
81
|
if ($value instanceof Arrayable) {
|
82
|
return $value->toArray();
|
83
|
}
|
84
|
|
85
|
return $value;
|
86
|
}
|
87
|
}
|