Batchable.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace Illuminate\Bus;
  3. use Carbon\CarbonImmutable;
  4. use Illuminate\Container\Container;
  5. use Illuminate\Support\Str;
  6. use Illuminate\Support\Testing\Fakes\BatchFake;
  7. trait Batchable
  8. {
  9. /**
  10. * The batch ID (if applicable).
  11. *
  12. * @var string
  13. */
  14. public $batchId;
  15. /**
  16. * The fake batch, if applicable.
  17. *
  18. * @var \Illuminate\Support\Testing\Fakes\BatchFake
  19. */
  20. private $fakeBatch;
  21. /**
  22. * Get the batch instance for the job, if applicable.
  23. *
  24. * @return \Illuminate\Bus\Batch|null
  25. */
  26. public function batch()
  27. {
  28. if ($this->fakeBatch) {
  29. return $this->fakeBatch;
  30. }
  31. if ($this->batchId) {
  32. return Container::getInstance()->make(BatchRepository::class)?->find($this->batchId);
  33. }
  34. }
  35. /**
  36. * Determine if the batch is still active and processing.
  37. *
  38. * @return bool
  39. */
  40. public function batching()
  41. {
  42. $batch = $this->batch();
  43. return $batch && ! $batch->cancelled();
  44. }
  45. /**
  46. * Set the batch ID on the job.
  47. *
  48. * @param string $batchId
  49. * @return $this
  50. */
  51. public function withBatchId(string $batchId)
  52. {
  53. $this->batchId = $batchId;
  54. return $this;
  55. }
  56. /**
  57. * Indicate that the job should use a fake batch.
  58. *
  59. * @param string $id
  60. * @param string $name
  61. * @param int $totalJobs
  62. * @param int $pendingJobs
  63. * @param int $failedJobs
  64. * @param array $failedJobIds
  65. * @param array $options
  66. * @param \Carbon\CarbonImmutable|null $createdAt
  67. * @param \Carbon\CarbonImmutable|null $cancelledAt
  68. * @param \Carbon\CarbonImmutable|null $finishedAt
  69. * @return array{0: $this, 1: \Illuminate\Support\Testing\Fakes\BatchFake}
  70. */
  71. public function withFakeBatch(string $id = '',
  72. string $name = '',
  73. int $totalJobs = 0,
  74. int $pendingJobs = 0,
  75. int $failedJobs = 0,
  76. array $failedJobIds = [],
  77. array $options = [],
  78. ?CarbonImmutable $createdAt = null,
  79. ?CarbonImmutable $cancelledAt = null,
  80. ?CarbonImmutable $finishedAt = null)
  81. {
  82. $this->fakeBatch = new BatchFake(
  83. empty($id) ? (string) Str::uuid() : $id,
  84. $name,
  85. $totalJobs,
  86. $pendingJobs,
  87. $failedJobs,
  88. $failedJobIds,
  89. $options,
  90. $createdAt ?? CarbonImmutable::now(),
  91. $cancelledAt,
  92. $finishedAt,
  93. );
  94. return [$this, $this->fakeBatch];
  95. }
  96. }