BroadcastEvent.php 2.4KB

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