diff --git a/src/Illuminate/Bus/PendingBatch.php b/src/Illuminate/Bus/PendingBatch.php index 56297bc80e0d..654c83ac334a 100644 --- a/src/Illuminate/Bus/PendingBatch.php +++ b/src/Illuminate/Bus/PendingBatch.php @@ -49,14 +49,14 @@ class PendingBatch /** * Create a new pending batch instance. * - * @param \Illuminate\Contracts\Container\Container $container - * @param \Illuminate\Support\Collection $jobs * @return void */ public function __construct(Container $container, Collection $jobs) { $this->container = $container; - $this->jobs = $jobs; + $this->jobs = $jobs->each(function (object|array $job) { + $this->checkJobIsBatchable($job); + }); } /** @@ -70,6 +70,7 @@ public function add($jobs) $jobs = is_iterable($jobs) ? $jobs : Arr::wrap($jobs); foreach ($jobs as $job) { + $this->checkJobIsBatchable($job); $this->jobs->push($job); } @@ -227,7 +228,6 @@ public function allowsFailures() /** * Set the name for the batch. * - * @param string $name * @return $this */ public function name(string $name) @@ -240,7 +240,6 @@ public function name(string $name) /** * Specify the queue connection that the batched jobs should run on. * - * @param string $connection * @return $this */ public function onConnection(string $connection) @@ -286,7 +285,6 @@ public function queue() /** * Add additional data into the batch's options array. * - * @param string $key * @param mixed $value * @return $this */ @@ -414,4 +412,19 @@ protected function store($repository) return $batch; } + + private function checkJobIsBatchable(object|array $job): void + { + foreach (Arr::wrap($job) as $job) { + if ($job instanceof PendingBatch) { + $this->checkJobIsBatchable($job->jobs->all()); + + return; + } + + if (! in_array(Batchable::class, class_uses_recursive($job))) { + throw new \RuntimeException(sprintf('Job %s must use Batchable trait', $job::class)); + } + } + } } diff --git a/tests/Bus/BusPendingBatchTest.php b/tests/Bus/BusPendingBatchTest.php index d5b9bd8d9ea7..d0398da85e69 100644 --- a/tests/Bus/BusPendingBatchTest.php +++ b/tests/Bus/BusPendingBatchTest.php @@ -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])); + } }