Skip to content

Commit

Permalink
Add broadcastAs method to Broadcasting Notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
antonkomarev committed Feb 21, 2018
1 parent e0571ca commit 6f28b66
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,20 @@ public function broadcastOn()
return [new PrivateChannel($this->channelName())];
}

/**
* Get the type of the broadcasted event.
*
* @return string
*/
public function broadcastAs()
{
if (method_exists($this->notification, 'broadcastAs')) {
return $this->notification->broadcastAs();
}

return get_class($this->notification);
}

/**
* Get the data that should be sent with the broadcasted event.
*
Expand All @@ -72,7 +86,7 @@ public function broadcastWith()
{
return array_merge($this->data, [
'id' => $this->notification->id,
'type' => get_class($this->notification),
'type' => $this->broadcastAs(),
]);
}

Expand Down
43 changes: 43 additions & 0 deletions tests/Notifications/NotificationBroadcastChannelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,36 @@ public function testNotificationIsBroadcastedOnCustomChannels()
$this->assertEquals(new PrivateChannel('custom-channel'), $channels[0]);
}

public function testNotificationIsBroadcastedWithCustomEventName()
{
$notification = new CustomEventNameTestNotification;
$notification->id = 1;
$notifiable = Mockery::mock();

$event = new \Illuminate\Notifications\Events\BroadcastNotificationCreated(
$notifiable, $notification, $notification->toArray($notifiable)
);

$eventName = $event->broadcastAs();

$this->assertSame('custom.type', $eventName);
}

public function testNotificationIsBroadcastedWithCustomDataType()
{
$notification = new CustomEventNameTestNotification;
$notification->id = 1;
$notifiable = Mockery::mock();

$event = new \Illuminate\Notifications\Events\BroadcastNotificationCreated(
$notifiable, $notification, $notification->toArray($notifiable)
);

$data = $event->broadcastWith();

$this->assertSame('custom.type', $data['type']);
}

public function testNotificationIsBroadcastedNow()
{
$notification = new TestNotificationBroadCastedNow;
Expand Down Expand Up @@ -78,6 +108,19 @@ public function broadcastOn()
}
}

class CustomEventNameTestNotification extends Notification
{
public function toArray($notifiable)
{
return ['invoice_id' => 1];
}

public function broadcastAs()
{
return 'custom.type';
}
}

class TestNotificationBroadCastedNow extends Notification
{
public function toArray($notifiable)
Expand Down

0 comments on commit 6f28b66

Please sign in to comment.