Skip to content

Commit

Permalink
[11.x] Ensure batched jobs are actually batchable (#54442)
Browse files Browse the repository at this point in the history
* fix: Ensure batched jobs are actually batchable

* fix: Handle deeply nested PendingBatch instances

* style: Fix

* style: Fix

* revert: dock block changes.

* revert: dock block changes.

* formatting

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
josepostiga and taylorotwell authored Feb 5, 2025
1 parent 9f07081 commit 928a709
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/Illuminate/Bus/PendingBatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Illuminate\Support\Collection;
use Illuminate\Support\Traits\Conditionable;
use Laravel\SerializableClosure\SerializableClosure;
use RuntimeException;
use Throwable;

use function Illuminate\Support\enum_value;
Expand Down Expand Up @@ -56,7 +57,10 @@ class PendingBatch
public function __construct(Container $container, Collection $jobs)
{
$this->container = $container;
$this->jobs = $jobs;

$this->jobs = $jobs->each(function (object|array $job) {
$this->ensureJobIsBatchable($job);
});
}

/**
Expand All @@ -70,12 +74,35 @@ public function add($jobs)
$jobs = is_iterable($jobs) ? $jobs : Arr::wrap($jobs);

foreach ($jobs as $job) {
$this->ensureJobIsBatchable($job);

$this->jobs->push($job);
}

return $this;
}

/**
* Ensure the given job is batchable.
*
* @param object|array $job
* @return void
*/
protected function ensureJobIsBatchable(object|array $job): void
{
foreach (Arr::wrap($job) as $job) {
if ($job instanceof PendingBatch) {
$this->ensureJobIsBatchable($job->jobs->all());

return;
}

if (! in_array(Batchable::class, class_uses_recursive($job))) {
throw new RuntimeException(sprintf('Attempted to batch job [%s], but it does not use the Batchable trait.', $job::class));
}
}
}

/**
* Add a callback to be executed when the batch is stored.
*
Expand Down
9 changes: 9 additions & 0 deletions tests/Bus/BusPendingBatchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,13 @@ public function test_batch_before_event_is_called()

$this->assertTrue($beforeCalled);
}

public function test_it_throws_exception_if_batched_job_is_not_batchable(): void
{
$nonBatchableJob = new class {};

$this->expectException(RuntimeException::class);

new PendingBatch(new Container, new Collection([$nonBatchableJob]));
}
}

0 comments on commit 928a709

Please sign in to comment.