RedisBroadcaster.php 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace Illuminate\Broadcasting\Broadcasters;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Support\Str;
  5. use Illuminate\Contracts\Redis\Factory as Redis;
  6. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  7. class RedisBroadcaster extends Broadcaster
  8. {
  9. /**
  10. * The Redis instance.
  11. *
  12. * @var \Illuminate\Contracts\Redis\Factory
  13. */
  14. protected $redis;
  15. /**
  16. * The Redis connection to use for broadcasting.
  17. *
  18. * @var string
  19. */
  20. protected $connection;
  21. /**
  22. * Create a new broadcaster instance.
  23. *
  24. * @param \Illuminate\Contracts\Redis\Factory $redis
  25. * @param string|null $connection
  26. * @return void
  27. */
  28. public function __construct(Redis $redis, $connection = null)
  29. {
  30. $this->redis = $redis;
  31. $this->connection = $connection;
  32. }
  33. /**
  34. * Authenticate the incoming request for a given channel.
  35. *
  36. * @param \Illuminate\Http\Request $request
  37. * @return mixed
  38. * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
  39. */
  40. public function auth($request)
  41. {
  42. if (Str::startsWith($request->channel_name, ['private-', 'presence-']) &&
  43. ! $request->user()) {
  44. throw new AccessDeniedHttpException;
  45. }
  46. $channelName = Str::startsWith($request->channel_name, 'private-')
  47. ? Str::replaceFirst('private-', '', $request->channel_name)
  48. : Str::replaceFirst('presence-', '', $request->channel_name);
  49. return parent::verifyUserCanAccessChannel(
  50. $request, $channelName
  51. );
  52. }
  53. /**
  54. * Return the valid authentication response.
  55. *
  56. * @param \Illuminate\Http\Request $request
  57. * @param mixed $result
  58. * @return mixed
  59. */
  60. public function validAuthenticationResponse($request, $result)
  61. {
  62. if (is_bool($result)) {
  63. return json_encode($result);
  64. }
  65. return json_encode(['channel_data' => [
  66. 'user_id' => $request->user()->getAuthIdentifier(),
  67. 'user_info' => $result,
  68. ]]);
  69. }
  70. /**
  71. * Broadcast the given event.
  72. *
  73. * @param array $channels
  74. * @param string $event
  75. * @param array $payload
  76. * @return void
  77. */
  78. public function broadcast(array $channels, $event, array $payload = [])
  79. {
  80. $connection = $this->redis->connection($this->connection);
  81. $payload = json_encode([
  82. 'event' => $event,
  83. 'data' => $payload,
  84. 'socket' => Arr::pull($payload, 'socket'),
  85. ]);
  86. foreach ($this->formatChannels($channels) as $channel) {
  87. $connection->publish($channel, $payload);
  88. }
  89. }
  90. }