Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/Illuminate/Events/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,9 @@ protected function parseEventAndPayload($event, $payload)
*/
protected function shouldBroadcast(array $payload)
{
return isset($payload[0]) && $payload[0] instanceof ShouldBroadcast;
return isset($payload[0]) &&
$payload[0] instanceof ShouldBroadcast &&
$this->checkBroadcastCondition($payload[0]);
}

/**
Expand Down Expand Up @@ -546,4 +548,20 @@ public function setQueueResolver(callable $resolver)

return $this;
}

/**
* Check if event should be broadcasted by condition.
*
* @param $event
*
* @return bool
*/
protected function checkBroadcastCondition($event)
{
if (method_exists($event, 'broadcastWhen')) {
return $event->broadcastWhen();
}

return true;
}
}
44 changes: 44 additions & 0 deletions tests/Events/EventsDispatcherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Illuminate\Events\Dispatcher;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class EventsDispatcherTest extends TestCase
{
Expand Down Expand Up @@ -239,6 +240,28 @@ public function testBothClassesAndInterfacesWork()
$this->assertSame('fooo', $_SERVER['__event.test1']);
$this->assertSame('baar', $_SERVER['__event.test2']);
}

public function testShouldBroadcastSuccess()
{
$d = m::mock(Dispatcher::class);

$d->makePartial()->shouldAllowMockingProtectedMethods();

$event = new BroadcastEvent();

$this->assertTrue($d->shouldBroadcast([$event]));
}

public function testShouldBroadcastFail()
{
$d = m::mock(Dispatcher::class);

$d->makePartial()->shouldAllowMockingProtectedMethods();

$event = new BroadcastFalseCondition();

$this->assertFalse($d->shouldBroadcast([$event]));
}
}

class TestDispatcherQueuedHandler implements \Illuminate\Contracts\Queue\ShouldQueue
Expand Down Expand Up @@ -274,3 +297,24 @@ class AnotherEvent implements SomeEventInterface
{
//
}

class BroadcastEvent implements ShouldBroadcast
{
public function broadcastOn()
{
return ['test-channel'];
}

public function broadcastWhen()
{
return true;
}
}

class BroadcastFalseCondition extends BroadcastEvent
{
public function broadcastWhen()
{
return false;
}
}