Skip to content

Commit

Permalink
[11.x] Optimize PendingBatch@ensureJobIsBatchable (#54485)
Browse files Browse the repository at this point in the history
* simplify PendingBatch@ensureJobIsBatchable; memoize the classes which are batchable

* no need to recheck the batch jobs

* Update PendingBatch.php

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
cosmastech and taylorotwell authored Feb 6, 2025
1 parent d30565a commit 917a3fe
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/Illuminate/Bus/PendingBatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ class PendingBatch
*/
public $options = [];

/**
* Jobs that have been verified to contain the Batchable trait.
*
* @var array<class-string, bool>
*/
protected static $batchableClasses = [];

/**
* Create a new pending batch instance.
*
Expand Down Expand Up @@ -92,14 +99,16 @@ 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))) {
if (! (static::$batchableClasses[$job::class] ?? false) && ! in_array(Batchable::class, class_uses_recursive($job))) {
static::$batchableClasses[$job::class] = false;

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

static::$batchableClasses[$job::class] = true;
}
}

Expand Down
18 changes: 18 additions & 0 deletions tests/Bus/BusPendingBatchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -231,4 +231,22 @@ public function test_it_throws_exception_if_batched_job_is_not_batchable(): void

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

public function test_it_throws_an_exception_if_batched_job_contains_batch_with_nonbatchable_job(): void
{
$this->expectException(RuntimeException::class);

$container = new Container;
new PendingBatch(
$container,
new Collection(
[new PendingBatch($container, new Collection([new BatchableJob, new class {}]))]
)
);
}
}

class BatchableJob
{
use Batchable;
}

0 comments on commit 917a3fe

Please sign in to comment.