| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508 |
- <?php
- namespace Illuminate\Bus;
- use Carbon\CarbonImmutable;
- use Closure;
- use Illuminate\Contracts\Queue\Factory as QueueFactory;
- use Illuminate\Contracts\Support\Arrayable;
- use Illuminate\Queue\CallQueuedClosure;
- use Illuminate\Support\Arr;
- use Illuminate\Support\Collection;
- use JsonSerializable;
- use Throwable;
- class Batch implements Arrayable, JsonSerializable
- {
- /**
- * The queue factory implementation.
- *
- * @var \Illuminate\Contracts\Queue\Factory
- */
- protected $queue;
- /**
- * The repository implementation.
- *
- * @var \Illuminate\Bus\BatchRepository
- */
- protected $repository;
- /**
- * The batch ID.
- *
- * @var string
- */
- public $id;
- /**
- * The batch name.
- *
- * @var string
- */
- public $name;
- /**
- * The total number of jobs that belong to the batch.
- *
- * @var int
- */
- public $totalJobs;
- /**
- * The total number of jobs that are still pending.
- *
- * @var int
- */
- public $pendingJobs;
- /**
- * The total number of jobs that have failed.
- *
- * @var int
- */
- public $failedJobs;
- /**
- * The IDs of the jobs that have failed.
- *
- * @var array
- */
- public $failedJobIds;
- /**
- * The batch options.
- *
- * @var array
- */
- public $options;
- /**
- * The date indicating when the batch was created.
- *
- * @var \Carbon\CarbonImmutable
- */
- public $createdAt;
- /**
- * The date indicating when the batch was cancelled.
- *
- * @var \Carbon\CarbonImmutable|null
- */
- public $cancelledAt;
- /**
- * The date indicating when the batch was finished.
- *
- * @var \Carbon\CarbonImmutable|null
- */
- public $finishedAt;
- /**
- * Create a new batch instance.
- *
- * @param \Illuminate\Contracts\Queue\Factory $queue
- * @param \Illuminate\Bus\BatchRepository $repository
- * @param string $id
- * @param string $name
- * @param int $totalJobs
- * @param int $pendingJobs
- * @param int $failedJobs
- * @param array $failedJobIds
- * @param array $options
- * @param \Carbon\CarbonImmutable $createdAt
- * @param \Carbon\CarbonImmutable|null $cancelledAt
- * @param \Carbon\CarbonImmutable|null $finishedAt
- */
- public function __construct(
- QueueFactory $queue,
- BatchRepository $repository,
- string $id,
- string $name,
- int $totalJobs,
- int $pendingJobs,
- int $failedJobs,
- array $failedJobIds,
- array $options,
- CarbonImmutable $createdAt,
- ?CarbonImmutable $cancelledAt = null,
- ?CarbonImmutable $finishedAt = null,
- ) {
- $this->queue = $queue;
- $this->repository = $repository;
- $this->id = $id;
- $this->name = $name;
- $this->totalJobs = $totalJobs;
- $this->pendingJobs = $pendingJobs;
- $this->failedJobs = $failedJobs;
- $this->failedJobIds = $failedJobIds;
- $this->options = $options;
- $this->createdAt = $createdAt;
- $this->cancelledAt = $cancelledAt;
- $this->finishedAt = $finishedAt;
- }
- /**
- * Get a fresh instance of the batch represented by this ID.
- *
- * @return self
- */
- public function fresh()
- {
- return $this->repository->find($this->id);
- }
- /**
- * Add additional jobs to the batch.
- *
- * @param \Illuminate\Support\Enumerable|object|array $jobs
- * @return self
- */
- public function add($jobs)
- {
- $count = 0;
- $jobs = Collection::wrap($jobs)->map(function ($job) use (&$count) {
- $job = $job instanceof Closure ? CallQueuedClosure::create($job) : $job;
- if (is_array($job)) {
- $count += count($job);
- $chain = $this->prepareBatchedChain($job);
- return $chain->first()
- ->allOnQueue($this->options['queue'] ?? null)
- ->allOnConnection($this->options['connection'] ?? null)
- ->chain($chain->slice(1)->values()->all());
- } else {
- $job->withBatchId($this->id);
- $count++;
- }
- return $job;
- });
- $this->repository->transaction(function () use ($jobs, $count) {
- $this->repository->incrementTotalJobs($this->id, $count);
- $this->queue->connection($this->options['connection'] ?? null)->bulk(
- $jobs->all(),
- $data = '',
- $this->options['queue'] ?? null
- );
- });
- return $this->fresh();
- }
- /**
- * Prepare a chain that exists within the jobs being added.
- *
- * @param array $chain
- * @return \Illuminate\Support\Collection
- */
- protected function prepareBatchedChain(array $chain)
- {
- return (new Collection($chain))->map(function ($job) {
- $job = $job instanceof Closure ? CallQueuedClosure::create($job) : $job;
- return $job->withBatchId($this->id);
- });
- }
- /**
- * Get the total number of jobs that have been processed by the batch thus far.
- *
- * @return int
- */
- public function processedJobs()
- {
- return $this->totalJobs - $this->pendingJobs;
- }
- /**
- * Get the percentage of jobs that have been processed (between 0-100).
- *
- * @return int
- */
- public function progress()
- {
- return $this->totalJobs > 0 ? round(($this->processedJobs() / $this->totalJobs) * 100) : 0;
- }
- /**
- * Record that a job within the batch finished successfully, executing any callbacks if necessary.
- *
- * @param string $jobId
- * @return void
- */
- public function recordSuccessfulJob(string $jobId)
- {
- $counts = $this->decrementPendingJobs($jobId);
- if ($this->hasProgressCallbacks()) {
- $this->invokeCallbacks('progress');
- }
- if ($counts->pendingJobs === 0) {
- $this->repository->markAsFinished($this->id);
- }
- if ($counts->pendingJobs === 0 && $this->hasThenCallbacks()) {
- $this->invokeCallbacks('then');
- }
- if ($counts->allJobsHaveRanExactlyOnce() && $this->hasFinallyCallbacks()) {
- $this->invokeCallbacks('finally');
- }
- }
- /**
- * Decrement the pending jobs for the batch.
- *
- * @param string $jobId
- * @return \Illuminate\Bus\UpdatedBatchJobCounts
- */
- public function decrementPendingJobs(string $jobId)
- {
- return $this->repository->decrementPendingJobs($this->id, $jobId);
- }
- /**
- * Invoke the callbacks of the given type.
- */
- protected function invokeCallbacks(string $type, ?Throwable $e = null): void
- {
- $batch = $this->fresh();
- foreach ($this->options[$type] ?? [] as $handler) {
- $this->invokeHandlerCallback($handler, $batch, $e);
- }
- }
- /**
- * Determine if the batch has finished executing.
- *
- * @return bool
- */
- public function finished()
- {
- return ! is_null($this->finishedAt);
- }
- /**
- * Determine if the batch has "progress" callbacks.
- *
- * @return bool
- */
- public function hasProgressCallbacks()
- {
- return isset($this->options['progress']) && ! empty($this->options['progress']);
- }
- /**
- * Determine if the batch has "success" callbacks.
- *
- * @return bool
- */
- public function hasThenCallbacks()
- {
- return isset($this->options['then']) && ! empty($this->options['then']);
- }
- /**
- * Determine if the batch allows jobs to fail without cancelling the batch.
- *
- * @return bool
- */
- public function allowsFailures()
- {
- return Arr::get($this->options, 'allowFailures', false) === true;
- }
- /**
- * Determine if the batch has job failures.
- *
- * @return bool
- */
- public function hasFailures()
- {
- return $this->failedJobs > 0;
- }
- /**
- * Record that a job within the batch failed to finish successfully, executing any callbacks if necessary.
- *
- * @param string $jobId
- * @param \Throwable $e
- * @return void
- */
- public function recordFailedJob(string $jobId, $e)
- {
- $counts = $this->incrementFailedJobs($jobId);
- if ($counts->failedJobs === 1 && ! $this->allowsFailures()) {
- $this->cancel();
- }
- if ($this->allowsFailures()) {
- if ($this->hasProgressCallbacks()) {
- $this->invokeCallbacks('progress', $e);
- }
- if ($this->hasFailureCallbacks()) {
- $this->invokeCallbacks('failure', $e);
- }
- }
- if ($counts->failedJobs === 1 && $this->hasCatchCallbacks()) {
- $this->invokeCallbacks('catch', $e);
- }
- if ($counts->allJobsHaveRanExactlyOnce() && $this->hasFinallyCallbacks()) {
- $this->invokeCallbacks('finally');
- }
- }
- /**
- * Increment the failed jobs for the batch.
- *
- * @param string $jobId
- * @return \Illuminate\Bus\UpdatedBatchJobCounts
- */
- public function incrementFailedJobs(string $jobId)
- {
- return $this->repository->incrementFailedJobs($this->id, $jobId);
- }
- /**
- * Determine if the batch has "catch" callbacks.
- *
- * @return bool
- */
- public function hasCatchCallbacks()
- {
- return isset($this->options['catch']) && ! empty($this->options['catch']);
- }
- /**
- * Determine if the batch has "failure" callbacks.
- */
- public function hasFailureCallbacks(): bool
- {
- return isset($this->options['failure']) && ! empty($this->options['failure']);
- }
- /**
- * Determine if the batch has "finally" callbacks.
- *
- * @return bool
- */
- public function hasFinallyCallbacks()
- {
- return isset($this->options['finally']) && ! empty($this->options['finally']);
- }
- /**
- * Cancel the batch.
- *
- * @return void
- */
- public function cancel()
- {
- $this->repository->cancel($this->id);
- }
- /**
- * Determine if the batch has been cancelled.
- *
- * @return bool
- */
- public function canceled()
- {
- return $this->cancelled();
- }
- /**
- * Determine if the batch has been cancelled.
- *
- * @return bool
- */
- public function cancelled()
- {
- return ! is_null($this->cancelledAt);
- }
- /**
- * Delete the batch from storage.
- *
- * @return void
- */
- public function delete()
- {
- $this->repository->delete($this->id);
- }
- /**
- * Invoke a batch callback handler.
- *
- * @param callable $handler
- * @param \Illuminate\Bus\Batch $batch
- * @param \Throwable|null $e
- * @return void
- */
- protected function invokeHandlerCallback($handler, Batch $batch, ?Throwable $e = null)
- {
- try {
- $handler($batch, $e);
- } catch (Throwable $e) {
- if (function_exists('report')) {
- report($e);
- }
- }
- }
- /**
- * Convert the batch to an array.
- *
- * @return array
- */
- public function toArray()
- {
- return [
- 'id' => $this->id,
- 'name' => $this->name,
- 'totalJobs' => $this->totalJobs,
- 'pendingJobs' => $this->pendingJobs,
- 'processedJobs' => $this->processedJobs(),
- 'progress' => $this->progress(),
- 'failedJobs' => $this->failedJobs,
- 'options' => $this->options,
- 'createdAt' => $this->createdAt,
- 'cancelledAt' => $this->cancelledAt,
- 'finishedAt' => $this->finishedAt,
- ];
- }
- /**
- * Get the JSON serializable representation of the object.
- *
- * @return array
- */
- public function jsonSerialize(): array
- {
- return $this->toArray();
- }
- /**
- * Dynamically access the batch's "options" via properties.
- *
- * @param string $key
- * @return mixed
- */
- public function __get($key)
- {
- return $this->options[$key] ?? null;
- }
- }
|