Skip to content

Commit 917a3fe

Browse files
[11.x] Optimize PendingBatch@ensureJobIsBatchable (#54485)
* 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]>
1 parent d30565a commit 917a3fe

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

src/Illuminate/Bus/PendingBatch.php

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,13 @@ class PendingBatch
4747
*/
4848
public $options = [];
4949

50+
/**
51+
* Jobs that have been verified to contain the Batchable trait.
52+
*
53+
* @var array<class-string, bool>
54+
*/
55+
protected static $batchableClasses = [];
56+
5057
/**
5158
* Create a new pending batch instance.
5259
*
@@ -92,14 +99,16 @@ protected function ensureJobIsBatchable(object|array $job): void
9299
{
93100
foreach (Arr::wrap($job) as $job) {
94101
if ($job instanceof PendingBatch) {
95-
$this->ensureJobIsBatchable($job->jobs->all());
96-
97102
return;
98103
}
99104

100-
if (! in_array(Batchable::class, class_uses_recursive($job))) {
105+
if (! (static::$batchableClasses[$job::class] ?? false) && ! in_array(Batchable::class, class_uses_recursive($job))) {
106+
static::$batchableClasses[$job::class] = false;
107+
101108
throw new RuntimeException(sprintf('Attempted to batch job [%s], but it does not use the Batchable trait.', $job::class));
102109
}
110+
111+
static::$batchableClasses[$job::class] = true;
103112
}
104113
}
105114

tests/Bus/BusPendingBatchTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,4 +231,22 @@ public function test_it_throws_exception_if_batched_job_is_not_batchable(): void
231231

232232
new PendingBatch(new Container, new Collection([$nonBatchableJob]));
233233
}
234+
235+
public function test_it_throws_an_exception_if_batched_job_contains_batch_with_nonbatchable_job(): void
236+
{
237+
$this->expectException(RuntimeException::class);
238+
239+
$container = new Container;
240+
new PendingBatch(
241+
$container,
242+
new Collection(
243+
[new PendingBatch($container, new Collection([new BatchableJob, new class {}]))]
244+
)
245+
);
246+
}
247+
}
248+
249+
class BatchableJob
250+
{
251+
use Batchable;
234252
}

0 commit comments

Comments
 (0)