Skip to content

[11.x] Ensure batched jobs are actually batchable #54442

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Feb 5, 2025
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
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]));
}
}
Loading