Skip to content

Commit

Permalink
Can disable turbo stream broadcasts globally
Browse files Browse the repository at this point in the history
  • Loading branch information
tonysm committed Nov 5, 2023
1 parent a92a909 commit 4a3de10
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/Broadcasting/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,24 @@ class Factory
*/
protected $recordedStreams = [];

/**
* Whether the broadcasts should be sent or not (globally).
*/
protected bool $isBroadcasting = true;

public function withoutBroadcasts(callable $callback)
{
$original = $this->isBroadcasting;

$this->isBroadcasting = false;

try {
return $callback();
} finally {
$this->isBroadcasting = $original;
}
}

public function fake()
{
$this->recording = true;
Expand Down Expand Up @@ -95,7 +113,7 @@ public function broadcastAction(string $action, $content = null, Model|string $t
$broadcast->fake($this);
}

return $broadcast;
return $broadcast->cancelIf(! $this->isBroadcasting);
}

public function record(PendingBroadcast $broadcast)
Expand Down
1 change: 1 addition & 0 deletions src/Facades/TurboStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
* @method static \HotwiredLaravel\TurboLaravel\Broadcasting\Factory assertNothingWasBroadcasted()
* @method static \HotwiredLaravel\TurboLaravel\Broadcasting\Factory assertBroadcasted(callable $callback)
* @method static \HotwiredLaravel\TurboLaravel\Broadcasting\Factory clearRecordedBroadcasts()
* @method static mixed withoutBroadcasts(callable $callback)
*
* @mixin \HotwiredLaravel\TurboLaravel\Broadcasting\Factory
*/
Expand Down
36 changes: 36 additions & 0 deletions tests/TurboStreamsBroadcastingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -611,4 +611,40 @@ public function broadcast_passing_model_with_broadcasts_trait_to_channel()
return true;
});
}

/** @test */
public function can_disable_turbo_stream_broadcasts()
{
TurboStream::withoutBroadcasts(fn () => (
TurboStream::broadcastRemove('todo_123')
));

TurboStream::assertNothingWasBroadcasted();

TurboStream::broadcastRemove('todo_123');

TurboStream::assertBroadcasted(function (PendingBroadcast $broadcast) {
return
$broadcast->target === 'todo_123'
&& $broadcast->action === 'remove';
});
}

/** @test */
public function globally_disabling_turbo_stream_broadcasts_also_disable_models()
{
$article = ArticleFactory::new()->create()->fresh();

TurboStream::withoutBroadcasts(fn () => (
$article->broadcastAppend()
));

TurboStream::assertNothingWasBroadcasted();

$article->broadcastAppend();

TurboStream::assertBroadcasted(function (PendingBroadcast $broadcast) {
return $broadcast->target === 'articles' && $broadcast->action === 'append';
});
}
}

0 comments on commit 4a3de10

Please sign in to comment.