master

laravel/framework

Last updated at: 29/12/2023 09:24

BroadcastChannel.php

TLDR

The BroadcastChannel.php file in the Illuminate\Notifications\Channels namespace contains the BroadcastChannel class, which is responsible for sending notifications through a broadcast channel.

Methods

send

The send method sends the given notification to the specified notifiable entity. It receives the notifiable entity and the notification object as parameters. It returns an array containing the result of the event dispatching process.

getData

The getData method retrieves the data for the notification. It receives the notifiable entity and the notification object as parameters. It checks if the notification has a toBroadcast method and invokes it to retrieve the data. If the toBroadcast method is not available, it checks if the notification has an toArray method and invokes it to retrieve the data. If neither method is available, it throws a RuntimeException.

<?php

namespace Illuminate\Notifications\Channels;

use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Notifications\Events\BroadcastNotificationCreated;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Notification;
use RuntimeException;

class BroadcastChannel
{
    /**
     * The event dispatcher.
     *
     * @var \Illuminate\Contracts\Events\Dispatcher
     */
    protected $events;

    /**
     * Create a new broadcast channel.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
     * @return void
     */
    public function __construct(Dispatcher $events)
    {
        $this->events = $events;
    }

    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return array|null
     */
    public function send($notifiable, Notification $notification)
    {
        $message = $this->getData($notifiable, $notification);

        $event = new BroadcastNotificationCreated(
            $notifiable, $notification, is_array($message) ? $message : $message->data
        );

        if ($message instanceof BroadcastMessage) {
            $event->onConnection($message->connection)
                  ->onQueue($message->queue);
        }

        return $this->events->dispatch($event);
    }

    /**
     * Get the data for the notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return mixed
     *
     * @throws \RuntimeException
     */
    protected function getData($notifiable, Notification $notification)
    {
        if (method_exists($notification, 'toBroadcast')) {
            return $notification->toBroadcast($notifiable);
        }

        if (method_exists($notification, 'toArray')) {
            return $notification->toArray($notifiable);
        }

        throw new RuntimeException('Notification is missing toArray method.');
    }
}