PendingBatch.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. <?php
  2. namespace Illuminate\Bus;
  3. use Closure;
  4. use Illuminate\Bus\Events\BatchDispatched;
  5. use Illuminate\Contracts\Container\Container;
  6. use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;
  7. use Illuminate\Support\Arr;
  8. use Illuminate\Support\Collection;
  9. use Illuminate\Support\Traits\Conditionable;
  10. use Laravel\SerializableClosure\SerializableClosure;
  11. use RuntimeException;
  12. use Throwable;
  13. use function Illuminate\Support\enum_value;
  14. class PendingBatch
  15. {
  16. use Conditionable;
  17. /**
  18. * The IoC container instance.
  19. *
  20. * @var \Illuminate\Contracts\Container\Container
  21. */
  22. protected $container;
  23. /**
  24. * The batch name.
  25. *
  26. * @var string
  27. */
  28. public $name = '';
  29. /**
  30. * The jobs that belong to the batch.
  31. *
  32. * @var \Illuminate\Support\Collection
  33. */
  34. public $jobs;
  35. /**
  36. * The batch options.
  37. *
  38. * @var array
  39. */
  40. public $options = [];
  41. /**
  42. * Jobs that have been verified to contain the Batchable trait.
  43. *
  44. * @var array<class-string, bool>
  45. */
  46. protected static $batchableClasses = [];
  47. /**
  48. * Create a new pending batch instance.
  49. *
  50. * @param \Illuminate\Contracts\Container\Container $container
  51. * @param \Illuminate\Support\Collection $jobs
  52. */
  53. public function __construct(Container $container, Collection $jobs)
  54. {
  55. $this->container = $container;
  56. $this->jobs = $jobs->each(function (object|array $job) {
  57. $this->ensureJobIsBatchable($job);
  58. });
  59. }
  60. /**
  61. * Add jobs to the batch.
  62. *
  63. * @param iterable|object|array $jobs
  64. * @return $this
  65. */
  66. public function add($jobs)
  67. {
  68. $jobs = is_iterable($jobs) ? $jobs : Arr::wrap($jobs);
  69. foreach ($jobs as $job) {
  70. $this->ensureJobIsBatchable($job);
  71. $this->jobs->push($job);
  72. }
  73. return $this;
  74. }
  75. /**
  76. * Ensure the given job is batchable.
  77. *
  78. * @param object|array $job
  79. * @return void
  80. */
  81. protected function ensureJobIsBatchable(object|array $job): void
  82. {
  83. foreach (Arr::wrap($job) as $job) {
  84. if ($job instanceof PendingBatch || $job instanceof Closure) {
  85. return;
  86. }
  87. if (! (static::$batchableClasses[$job::class] ?? false) && ! in_array(Batchable::class, class_uses_recursive($job))) {
  88. static::$batchableClasses[$job::class] = false;
  89. throw new RuntimeException(sprintf('Attempted to batch job [%s], but it does not use the Batchable trait.', $job::class));
  90. }
  91. static::$batchableClasses[$job::class] = true;
  92. }
  93. }
  94. /**
  95. * Add a callback to be executed when the batch is stored.
  96. *
  97. * @param callable $callback
  98. * @return $this
  99. */
  100. public function before($callback)
  101. {
  102. $this->registerCallback('before', $callback);
  103. return $this;
  104. }
  105. /**
  106. * Get the "before" callbacks that have been registered with the pending batch.
  107. *
  108. * @return array
  109. */
  110. public function beforeCallbacks()
  111. {
  112. return $this->options['before'] ?? [];
  113. }
  114. /**
  115. * Add a callback to be executed after a job in the batch have executed successfully.
  116. *
  117. * @param callable $callback
  118. * @return $this
  119. */
  120. public function progress($callback)
  121. {
  122. $this->registerCallback('progress', $callback);
  123. return $this;
  124. }
  125. /**
  126. * Get the "progress" callbacks that have been registered with the pending batch.
  127. *
  128. * @return array
  129. */
  130. public function progressCallbacks()
  131. {
  132. return $this->options['progress'] ?? [];
  133. }
  134. /**
  135. * Add a callback to be executed after all jobs in the batch have executed successfully.
  136. *
  137. * @param callable $callback
  138. * @return $this
  139. */
  140. public function then($callback)
  141. {
  142. $this->registerCallback('then', $callback);
  143. return $this;
  144. }
  145. /**
  146. * Get the "then" callbacks that have been registered with the pending batch.
  147. *
  148. * @return array
  149. */
  150. public function thenCallbacks()
  151. {
  152. return $this->options['then'] ?? [];
  153. }
  154. /**
  155. * Add a callback to be executed after the first failing job in the batch.
  156. *
  157. * @param callable $callback
  158. * @return $this
  159. */
  160. public function catch($callback)
  161. {
  162. $this->registerCallback('catch', $callback);
  163. return $this;
  164. }
  165. /**
  166. * Get the "catch" callbacks that have been registered with the pending batch.
  167. *
  168. * @return array
  169. */
  170. public function catchCallbacks()
  171. {
  172. return $this->options['catch'] ?? [];
  173. }
  174. /**
  175. * Add a callback to be executed after the batch has finished executing.
  176. *
  177. * @param callable $callback
  178. * @return $this
  179. */
  180. public function finally($callback)
  181. {
  182. $this->registerCallback('finally', $callback);
  183. return $this;
  184. }
  185. /**
  186. * Get the "finally" callbacks that have been registered with the pending batch.
  187. *
  188. * @return array
  189. */
  190. public function finallyCallbacks()
  191. {
  192. return $this->options['finally'] ?? [];
  193. }
  194. /**
  195. * Indicate that the batch should not be canceled when a job within the batch fails.
  196. *
  197. * Optionally, add callbacks to be executed upon each job failure.
  198. *
  199. * @template TParam of (Closure(\Illuminate\Bus\Batch, \Throwable|null): mixed)|(callable(\Illuminate\Bus\Batch, \Throwable|null): mixed)
  200. *
  201. * @param bool|TParam|array<array-key, TParam> $param
  202. * @return $this
  203. */
  204. public function allowFailures($param = true)
  205. {
  206. if (! is_bool($param)) {
  207. $param = Arr::wrap($param);
  208. foreach ($param as $callback) {
  209. if (is_callable($callback)) {
  210. $this->registerCallback('failure', $callback);
  211. }
  212. }
  213. }
  214. $this->options['allowFailures'] = ! ($param === false);
  215. return $this;
  216. }
  217. /**
  218. * Determine if the pending batch allows jobs to fail without cancelling the batch.
  219. *
  220. * @return bool
  221. */
  222. public function allowsFailures()
  223. {
  224. return Arr::get($this->options, 'allowFailures', false) === true;
  225. }
  226. /**
  227. * Get the "failure" callbacks that have been registered with the pending batch.
  228. *
  229. * @return array<array-key, Closure|callable>
  230. */
  231. public function failureCallbacks(): array
  232. {
  233. return $this->options['failure'] ?? [];
  234. }
  235. /**
  236. * Register a callback with proper serialization.
  237. */
  238. private function registerCallback(string $type, Closure|callable $callback): void
  239. {
  240. $this->options[$type][] = $callback instanceof Closure
  241. ? new SerializableClosure($callback)
  242. : $callback;
  243. }
  244. /**
  245. * Set the name for the batch.
  246. *
  247. * @param string $name
  248. * @return $this
  249. */
  250. public function name(string $name)
  251. {
  252. $this->name = $name;
  253. return $this;
  254. }
  255. /**
  256. * Specify the queue connection that the batched jobs should run on.
  257. *
  258. * @param string $connection
  259. * @return $this
  260. */
  261. public function onConnection(string $connection)
  262. {
  263. $this->options['connection'] = $connection;
  264. return $this;
  265. }
  266. /**
  267. * Get the connection used by the pending batch.
  268. *
  269. * @return string|null
  270. */
  271. public function connection()
  272. {
  273. return $this->options['connection'] ?? null;
  274. }
  275. /**
  276. * Specify the queue that the batched jobs should run on.
  277. *
  278. * @param \UnitEnum|string|null $queue
  279. * @return $this
  280. */
  281. public function onQueue($queue)
  282. {
  283. $this->options['queue'] = enum_value($queue);
  284. return $this;
  285. }
  286. /**
  287. * Get the queue used by the pending batch.
  288. *
  289. * @return string|null
  290. */
  291. public function queue()
  292. {
  293. return $this->options['queue'] ?? null;
  294. }
  295. /**
  296. * Add additional data into the batch's options array.
  297. *
  298. * @param string $key
  299. * @param mixed $value
  300. * @return $this
  301. */
  302. public function withOption(string $key, $value)
  303. {
  304. $this->options[$key] = $value;
  305. return $this;
  306. }
  307. /**
  308. * Dispatch the batch.
  309. *
  310. * @return \Illuminate\Bus\Batch
  311. *
  312. * @throws \Throwable
  313. */
  314. public function dispatch()
  315. {
  316. $repository = $this->container->make(BatchRepository::class);
  317. try {
  318. $batch = $this->store($repository);
  319. $batch = $batch->add($this->jobs);
  320. } catch (Throwable $e) {
  321. if (isset($batch)) {
  322. $repository->delete($batch->id);
  323. }
  324. throw $e;
  325. }
  326. $this->container->make(EventDispatcher::class)->dispatch(
  327. new BatchDispatched($batch)
  328. );
  329. return $batch;
  330. }
  331. /**
  332. * Dispatch the batch after the response is sent to the browser.
  333. *
  334. * @return \Illuminate\Bus\Batch
  335. */
  336. public function dispatchAfterResponse()
  337. {
  338. $repository = $this->container->make(BatchRepository::class);
  339. $batch = $this->store($repository);
  340. if ($batch) {
  341. $this->container->terminating(function () use ($batch) {
  342. $this->dispatchExistingBatch($batch);
  343. });
  344. }
  345. return $batch;
  346. }
  347. /**
  348. * Dispatch an existing batch.
  349. *
  350. * @param \Illuminate\Bus\Batch $batch
  351. * @return void
  352. *
  353. * @throws \Throwable
  354. */
  355. protected function dispatchExistingBatch($batch)
  356. {
  357. try {
  358. $batch = $batch->add($this->jobs);
  359. } catch (Throwable $e) {
  360. $batch->delete();
  361. throw $e;
  362. }
  363. $this->container->make(EventDispatcher::class)->dispatch(
  364. new BatchDispatched($batch)
  365. );
  366. }
  367. /**
  368. * Dispatch the batch if the given truth test passes.
  369. *
  370. * @param bool|\Closure $boolean
  371. * @return \Illuminate\Bus\Batch|null
  372. */
  373. public function dispatchIf($boolean)
  374. {
  375. return value($boolean) ? $this->dispatch() : null;
  376. }
  377. /**
  378. * Dispatch the batch unless the given truth test passes.
  379. *
  380. * @param bool|\Closure $boolean
  381. * @return \Illuminate\Bus\Batch|null
  382. */
  383. public function dispatchUnless($boolean)
  384. {
  385. return ! value($boolean) ? $this->dispatch() : null;
  386. }
  387. /**
  388. * Store the batch using the given repository.
  389. *
  390. * @param \Illuminate\Bus\BatchRepository $repository
  391. * @return \Illuminate\Bus\Batch
  392. */
  393. protected function store($repository)
  394. {
  395. $batch = $repository->store($this);
  396. (new Collection($this->beforeCallbacks()))->each(function ($handler) use ($batch) {
  397. try {
  398. return $handler($batch);
  399. } catch (Throwable $e) {
  400. if (function_exists('report')) {
  401. report($e);
  402. }
  403. }
  404. });
  405. return $batch;
  406. }
  407. }