class MercureBroadcaster extends Broadcaster

Traits

Constants

DEFAULT_TOPIC_PREFIX

Properties

protected Container $container

The container instance.

from  Broadcaster
protected Closure|null $authenticatedUserCallback

The callback to resolve the authenticated user information.

from  Broadcaster
static protected array $channels

The registered channel authenticators.

from  Broadcaster
static protected array $channelOptions

The registered channel options.

from  Broadcaster
static protected Closure|null $channelFormatter

The callback used to format outgoing channel values.

from  Broadcaster
static protected null|Request, string): ?string $channelAuthorizer

The callback used to authorize incoming channel names.

from  Broadcaster
protected BindingRegistrar|null $bindingRegistrar

The binding registrar instance.

from  Broadcaster

Methods

array|null
resolveAuthenticatedUser(Request $request)

Resolve the authenticated user payload for the incoming connection request.

void
resolveAuthenticatedUserUsing(Closure|null $callback)

Register the user retrieval callback used to authenticate connections.

channel(HasBroadcastChannel|string $channel, callable|string $callback, array $options = [])

Register a channel authenticator.

static void
formatChannelsUsing(Closure|null $callback)

Register the outgoing channel formatter.

static Closure|null
channelFormatter()

Get the registered outgoing channel formatter.

static void
authorizeChannelsUsing(Closure|null $callback)

Register the incoming channel authorizer.

mixed
verifyUserCanAccessChannel(Request $request, string $channel, bool $guarded = false)

Authenticate the incoming request for a given channel.

mixed
validAuthenticationResponseForChannel(Request $request, mixed $result, string $channel)

Return the authorized channel's response and user without retaining request state.

array
extractAuthParameters(string $pattern, string $channel, callable|string $callback)

Extract the parameters from the given pattern and channel.

array
extractParameters(callable|string $callback)

Extract the parameters out of what the user passed to handle the channel authentication.

array
extractParametersFromClass(string $callback)

Extract the parameters out of a class channel's "join" method.

array
extractChannelKeys(string $pattern, string $channel)

Extract the channel keys from the incoming channel name.

mixed
resolveBinding(string $key, string $value, array $callbackParameters)

Resolve the given parameter binding.

mixed
resolveExplicitBindingIfPossible(string $key, mixed $value)

Resolve an explicit parameter binding if applicable.

mixed
resolveImplicitBindingIfPossible(string $key, string $value, array $callbackParameters)

Resolve an implicit parameter binding if applicable.

bool
isImplicitlyBindable(string $key, ReflectionParameter $parameter)

Determine if a given key and parameter is implicitly bindable.

array
formatChannels(array $channels)

Format the channel array into an array of strings.

binder()

Get the model binding registrar instance.

callable
normalizeChannelHandlerToCallable(callable|string $callback)

Normalize the given callback into a callable.

mixed
retrieveUser(Request $request, string $channel)

Retrieve the authenticated user using the configured guard (if any).

array
retrieveChannelOptions(string $channel)

Retrieve options for a certain channel.

bool
channelNameMatchesPattern(string $channel, string $pattern)

Check if the channel name from the request matches a pattern from registered channels.

getChannels()

Get all of the registered channels.

static void
flushState()

Flush all static state.

bool
isGuardedChannel(string $channel)

Return true if the channel is protected by authentication.

string
normalizeChannelName(string $channel)

Remove prefix from channel name.

__construct(Container $container, HubInterface $hub, int $expiration = 300, ChannelEncrypter|null $encrypter = null, string $topicPrefix = self::DEFAULT_TOPIC_PREFIX, bool $clientEvents = true)

Create a new broadcaster instance.

mixed
auth(Request $request)

Authenticate the incoming request for a given channel.

mixed
validAuthenticationResponse(Request $request, mixed $result)

Return the valid authentication response.

void
broadcast(array $channels, string $event, array $payload = [])

Broadcast the given event.

HubInterface
getHub()

Get the Mercure hub instance.

void
setHub(HubInterface $hub)

Set the Mercure hub instance.

void
exemptCookieFromEncryption()

Exempt the hub's authorization cookie from cookie encryption.

string
updateData(array|null $channels, string $event, array $payload, string|null $socket)

Encode the data of an update targeting the given channels.

Cookie
makeAuthorizationCookie(Request $request, array $grants, mixed $user = null)

Build the subscriber authorization cookie carrying the given grants.

string
broadcastingIdentifier(mixed $user)

Get the broadcasting identifier of the given user.

string
channelTopic(string $channelName)

Build the hub topic of the given channel.

string
whisperTopic(string $channelName)

Build the whisper topic of the given channel: the only topic its subscribers may publish to, keeping the channel topic server-only.

string
subscriptionPattern(string $channelName)

Build the subscription-API topic matcher for the given presence channel, matching both the snapshot listing used to seed the member list (.../subscriptions/{match_type}/{match}) and the per-subscriber active:true/false events (.../{match_type}/{match}/{subscriber}).

Details

in Broadcaster at line 69
array|null resolveAuthenticatedUser(Request $request)

Resolve the authenticated user payload for the incoming connection request.

See: https://pusher.com/docs/channels/library_auth_reference/auth-signatures/#user-authentication.

Parameters

Request $request

Return Value

array|null

in Broadcaster at line 86
void resolveAuthenticatedUserUsing(Closure|null $callback)

Register the user retrieval callback used to authenticate connections.

The callback persists in instance state on the cached broadcaster for the worker lifetime; per-request use races across coroutines.

See: https://pusher.com/docs/channels/library_auth_reference/auth-signatures/#user-authentication.

Parameters

Closure|null $callback

Return Value

void

in Broadcaster at line 101
Broadcaster channel(HasBroadcastChannel|string $channel, callable|string $callback, array $options = [])

Register a channel authenticator.

The channel authorizer and options persist in shared static state on the Broadcaster class for the worker lifetime and apply to every subsequent connection authentication.

Parameters

HasBroadcastChannel|string $channel
callable|string $callback
array $options

Return Value

Broadcaster

in Broadcaster at line 123
static void formatChannelsUsing(Closure|null $callback)

Register the outgoing channel formatter.

The callback persists in shared static state for the worker lifetime and applies to every broadcaster across all coroutines.

Parameters

Closure|null $callback

Return Value

void

in Broadcaster at line 132
static Closure|null channelFormatter()

Get the registered outgoing channel formatter.

Return Value

Closure|null

in Broadcaster at line 143
static void authorizeChannelsUsing(Closure|null $callback)

Register the incoming channel authorizer.

The callback persists in shared static state for the worker lifetime and applies to every broadcaster across all coroutines.

Parameters

Closure|null $callback

Return Value

void

in Broadcaster at line 154
protected mixed verifyUserCanAccessChannel(Request $request, string $channel, bool $guarded = false)

Authenticate the incoming request for a given channel.

Parameters

Request $request
string $channel
bool $guarded

Return Value

mixed

Exceptions

AccessDeniedHttpException

at line 184
protected mixed validAuthenticationResponseForChannel(Request $request, mixed $result, string $channel)

Return the authorized channel's response and user without retaining request state.

Parameters

Request $request
mixed $result
string $channel

Return Value

mixed

in Broadcaster at line 204
protected array extractAuthParameters(string $pattern, string $channel, callable|string $callback)

Extract the parameters from the given pattern and channel.

Parameters

string $pattern
string $channel
callable|string $callback

Return Value

array

in Broadcaster at line 222
protected array extractParameters(callable|string $callback)

Extract the parameters out of what the user passed to handle the channel authentication.

Parameters

callable|string $callback

Return Value

array

Exceptions

Exception

in Broadcaster at line 238
protected array extractParametersFromClass(string $callback)

Extract the parameters out of a class channel's "join" method.

Parameters

string $callback

Return Value

array

Exceptions

Exception

in Broadcaster at line 252
protected array extractChannelKeys(string $pattern, string $channel)

Extract the channel keys from the incoming channel name.

Parameters

string $pattern
string $channel

Return Value

array

in Broadcaster at line 262
protected mixed resolveBinding(string $key, string $value, array $callbackParameters)

Resolve the given parameter binding.

Parameters

string $key
string $value
array $callbackParameters

Return Value

mixed

in Broadcaster at line 276
protected mixed resolveExplicitBindingIfPossible(string $key, mixed $value)

Resolve an explicit parameter binding if applicable.

Parameters

string $key
mixed $value

Return Value

mixed

in Broadcaster at line 292
protected mixed resolveImplicitBindingIfPossible(string $key, string $value, array $callbackParameters)

Resolve an implicit parameter binding if applicable.

Parameters

string $key
string $value
array $callbackParameters

Return Value

mixed

Exceptions

AccessDeniedHttpException

in Broadcaster at line 314
protected bool isImplicitlyBindable(string $key, ReflectionParameter $parameter)

Determine if a given key and parameter is implicitly bindable.

Parameters

string $key
ReflectionParameter $parameter

Return Value

bool

in Broadcaster at line 323
protected array formatChannels(array $channels)

Format the channel array into an array of strings.

Parameters

array $channels

Return Value

array

in Broadcaster at line 338
protected BindingRegistrar|null binder()

Get the model binding registrar instance.

Return Value

BindingRegistrar|null

in Broadcaster at line 352
protected callable normalizeChannelHandlerToCallable(callable|string $callback)

Normalize the given callback into a callable.

Parameters

callable|string $callback

Return Value

callable

in Broadcaster at line 362
protected mixed retrieveUser(Request $request, string $channel)

Retrieve the authenticated user using the configured guard (if any).

Parameters

Request $request
string $channel

Return Value

mixed

in Broadcaster at line 384
protected array retrieveChannelOptions(string $channel)

Retrieve options for a certain channel.

Parameters

string $channel

Return Value

array

in Broadcaster at line 400
protected bool channelNameMatchesPattern(string $channel, string $pattern)

Check if the channel name from the request matches a pattern from registered channels.

Parameters

string $channel
string $pattern

Return Value

bool

in Broadcaster at line 410
Collection getChannels()

Get all of the registered channels.

Return Value

Collection

in Broadcaster at line 418
static void flushState()

Flush all static state.

Return Value

void

bool isGuardedChannel(string $channel)

Return true if the channel is protected by authentication.

Parameters

string $channel

Return Value

bool

string normalizeChannelName(string $channel)

Remove prefix from channel name.

Parameters

string $channel

Return Value

string

at line 53
__construct(Container $container, HubInterface $hub, int $expiration = 300, ChannelEncrypter|null $encrypter = null, string $topicPrefix = self::DEFAULT_TOPIC_PREFIX, bool $clientEvents = true)

Create a new broadcaster instance.

The hub's token factory mints the subscriber cookie token and must be non-null, already carrying the static RFC 9068 claims; the hub's token provider mints the (longer-lived) publish token. The encrypter enables end-to-end encrypted channels: without one, using such a channel throws. Presence channels are never encrypted, as their member payloads flow through the hub's subscription API.

The topic prefix namespaces every hub topic: it keeps Hypervel topics from colliding with other publishers sharing the hub, and lets two applications sharing one hub (and one JWT secret) stay apart. The default is a "laravel.alt" URL: ".alt" is reserved outside the DNS (RFC 9476), so the IRI is guaranteed non-resolvable and unsquattable.

Parameters

Container $container
HubInterface $hub
int $expiration
ChannelEncrypter|null $encrypter
string $topicPrefix
bool $clientEvents

at line 87
mixed auth(Request $request)

Authenticate the incoming request for a given channel.

Mercure multiplexes every joined topic over one EventSource guarded by one authorization cookie, so this reads a "channel_names" array and mints a single token covering every currently-joined channel, public ones included (a hub without the "anonymous" directive rejects token-less subscribers). Authorization is per channel: a denied channel is flagged in the response and left out of the grants, so revoking one channel mid-session never takes down the others.

Each authorized end-to-end encrypted channel's response entry carries the JSON Web Key decrypting its updates, the out-of-band key exchange recommended by the Mercure specification: the hub never sees the keys.

Every guarded channel also gets a whisper topic the subscriber may publish to, so clients can exchange whispers directly through the hub. Confining client publish rights to those topics keeps the channel topics server-only: a whisper grant can never forge a server event.

Parameters

Request $request

Return Value

mixed

Exceptions

AccessDeniedHttpException
BroadcastException

at line 174
mixed validAuthenticationResponse(Request $request, mixed $result)

Return the valid authentication response.

Parameters

Request $request
mixed $result

Return Value

mixed

at line 204
void broadcast(array $channels, string $event, array $payload = [])

Broadcast the given event.

The hub delivers a private update to any subscriber authorized for one of its topics, so every guarded channel gets its own update: a shared one would leak the sibling channel names to every recipient. Encrypted channels additionally hide the event name, payload, and socket ID from the hub inside a JWE; the routing envelope stays plaintext so a multiplexing subscriber can select the decryption key.

Parameters

array $channels
string $event
array $payload

Return Value

void

Exceptions

BroadcastException

at line 274
HubInterface getHub()

Get the Mercure hub instance.

Return Value

HubInterface

at line 285
void setHub(HubInterface $hub)

Set the Mercure hub instance.

Replaces the hub on this worker-cached broadcaster and updates the worker-wide cookie encryption exemptions.

Parameters

HubInterface $hub

Return Value

void

at line 298
protected void exemptCookieFromEncryption()

Exempt the hub's authorization cookie from cookie encryption.

Encrypting the raw JWT would produce a value the hub can never verify.

Return Value

void

at line 313
protected string updateData(array|null $channels, string $event, array $payload, string|null $socket)

Encode the data of an update targeting the given channels.

Parameters

array|null $channels
string $event
array $payload
string|null $socket

Return Value

string

Exceptions

JsonException

at line 341
protected Cookie makeAuthorizationCookie(Request $request, array $grants, mixed $user = null)

Build the subscriber authorization cookie carrying the given grants.

The Authorization helper mints the token with the hub's factory, resolves the cookie domain so a hub on a sibling subdomain still receives the cookie, and injects an "exp" claim matching the cookie lifetime. Only the per-request "sub" claim is contributed here; the static RFC 9068 claims come from the hub's factory.

Browsers enforce prefixes case-insensitively, including path and domain requirements; Symfony checks only exact-case prefixes against the scheme.

Parameters

Request $request
array $grants
mixed $user

Return Value

Cookie

Exceptions

BroadcastException
InvalidArgumentException

at line 373
protected string broadcastingIdentifier(mixed $user)

Get the broadcasting identifier of the given user.

Parameters

mixed $user

Return Value

string

at line 388
protected string channelTopic(string $channelName)

Build the hub topic of the given channel.

Channel names are RFC 3986 encoded into a single path segment, so a name can never escape its namespace, whatever characters it contains.

Parameters

string $channelName

Return Value

string

at line 397
protected string whisperTopic(string $channelName)

Build the whisper topic of the given channel: the only topic its subscribers may publish to, keeping the channel topic server-only.

Parameters

string $channelName

Return Value

string

at line 412
protected string subscriptionPattern(string $channelName)

Build the subscription-API topic matcher for the given presence channel, matching both the snapshot listing used to seed the member list (.../subscriptions/{match_type}/{match}) and the per-subscriber active:true/false events (.../{match_type}/{match}/{subscriber}).

"{/:subscriber}?" is an optional URLPattern group covering the trailing segment and its slash.

Parameters

string $channelName

Return Value

string

See also

https://mercure.rocks/docs/hub/concepts/active-subscriptions