Debian Codegraph @

lib/3rdParty/composer/illuminate/support/Testing/Fakes/QueueFake.php

raw symbols SCIP
1 <?php
2
3 namespace Illuminate\Support\Testing\Fakes;
4
5 use BadMethodCallException;
6 use Closure;
7 use Illuminate\Bus\UniqueLock;
8 use Illuminate\Contracts\Cache\Repository as Cache;
9 use Illuminate\Contracts\Queue\Queue;
10 use Illuminate\Contracts\Queue\ShouldBeUnique;
11 use Illuminate\Events\CallQueuedListener;
12 use Illuminate\Queue\CallQueuedClosure;
13 use Illuminate\Queue\QueueManager;
14 use Illuminate\Support\Collection;
15 use Illuminate\Support\Str;
16 use Illuminate\Support\Traits\ReflectsClosures;
17 use PHPUnit\Framework\Assert as PHPUnit;
18
19 /**
20 * @phpstan-type RawPushType array{"payload": string, "queue": string|null, "options": array<array-key, mixed>}
21 */
22 class QueueFake extends QueueManager implements Fake, Queue
23 {
24 use ReflectsClosures;
25
26 /**
27 * The original queue manager.
28 *
29 * @var \Illuminate\Contracts\Queue\Queue
30 */
31 public $queue;
32
33 /**
34 * The job types that should be intercepted instead of pushed to the queue.
35 *
36 * @var \Illuminate\Support\Collection
37 */
38 protected $jobsToFake;
39
40 /**
41 * The job types that should be pushed to the queue and not intercepted.
42 *
43 * @var \Illuminate\Support\Collection
44 */
45 protected $jobsToBeQueued;
46
47 /**
48 * All of the jobs that have been pushed.
49 *
50 * @var array
51 */
52 protected $jobs = [];
53
54 /**
55 * All of the payloads that have been raw pushed.
56 *
57 * @var list<RawPushType>
58 */
59 protected $rawPushes = [];
60
61 /**
62 * All of the unique jobs that were pushed.
63 *
64 * @var array
65 */
66 private $uniqueJobs = [];
67
68 /**
69 * Indicates if items should be serialized and restored when pushed to the queue.
70 *
71 * @var bool
72 */
73 protected bool $serializeAndRestore = false;
74
75 /**
76 * Create a new fake queue instance.
77 *
78 * @param \Illuminate\Contracts\Foundation\Application $app
79 * @param array $jobsToFake
80 * @param \Illuminate\Queue\QueueManager|null $queue
81 */
82 public function __construct($app, $jobsToFake = [], $queue = null)
83 {
84 parent::__construct($app);
85
86 $this->jobsToFake = Collection::wrap($jobsToFake);
87 $this->jobsToBeQueued = new Collection;
88 $this->queue = $queue;
89 }
90
91 /**
92 * Specify the jobs that should be queued instead of faked.
93 *
94 * @param array|string $jobsToBeQueued
95 * @return $this
96 */
97 public function except($jobsToBeQueued)
98 {
99 $this->jobsToBeQueued = Collection::wrap($jobsToBeQueued)->merge($this->jobsToBeQueued);
100
101 return $this;
102 }
103
104 /**
105 * Assert if a job was pushed based on a truth-test callback.
106 *
107 * @param string|\Closure $job
108 * @param callable|int|null $callback
109 * @return void
110 */
111 public function assertPushed($job, $callback = null)
112 {
113 if ($job instanceof Closure) {
114 [$job, $callback] = [$this->firstClosureParameterType($job), $job];
115 }
116
117 if (is_numeric($callback)) {
118 return $this->assertPushedTimes($job, $callback);
119 }
120
121 PHPUnit::assertTrue(
122 $this->pushed($job, $callback)->count() > 0,
123 "The expected [{$job}] job was not pushed."
124 );
125 }
126
127 /**
128 * Assert if a job was pushed a number of times.
129 *
130 * @param string $job
131 * @param int $times
132 * @return void
133 */
134 public function assertPushedTimes($job, $times = 1)
135 {
136 $count = $this->pushed($job)->count();
137
138 PHPUnit::assertSame(
139 $times, $count,
140 sprintf(
141 "The expected [{$job}] job was pushed {$count} %s instead of {$times} %s.",
142 Str::plural('time', $count),
143 Str::plural('time', $times)
144 )
145 );
146 }
147
148 /**
149 * Assert if a job was pushed based on a truth-test callback.
150 *
151 * @param string $queue
152 * @param string|\Closure $job
153 * @param callable|null $callback
154 * @return void
155 */
156 public function assertPushedOn($queue, $job, $callback = null)
157 {
158 if ($job instanceof Closure) {
159 [$job, $callback] = [$this->firstClosureParameterType($job), $job];
160 }
161
162 $this->assertPushed($job, function ($job, $pushedQueue) use ($callback, $queue) {
163 if ($pushedQueue !== $queue) {
164 return false;
165 }
166
167 return $callback ? $callback(...func_get_args()) : true;
168 });
169 }
170
171 /**
172 * Assert if a job was pushed with chained jobs based on a truth-test callback.
173 *
174 * @param string $job
175 * @param array $expectedChain
176 * @param callable|null $callback
177 * @return void
178 */
179 public function assertPushedWithChain($job, $expectedChain = [], $callback = null)
180 {
181 PHPUnit::assertTrue(
182 $this->pushed($job, $callback)->isNotEmpty(),
183 "The expected [{$job}] job was not pushed."
184 );
185
186 PHPUnit::assertTrue(
187 (new Collection($expectedChain))->isNotEmpty(),
188 'The expected chain can not be empty.'
189 );
190
191 $this->isChainOfObjects($expectedChain)
192 ? $this->assertPushedWithChainOfObjects($job, $expectedChain, $callback)
193 : $this->assertPushedWithChainOfClasses($job, $expectedChain, $callback);
194 }
195
196 /**
197 * Assert if a job was pushed with an empty chain based on a truth-test callback.
198 *
199 * @param string $job
200 * @param callable|null $callback
201 * @return void
202 */
203 public function assertPushedWithoutChain($job, $callback = null)
204 {
205 PHPUnit::assertTrue(
206 $this->pushed($job, $callback)->isNotEmpty(),
207 "The expected [{$job}] job was not pushed."
208 );
209
210 $this->assertPushedWithChainOfClasses($job, [], $callback);
211 }
212
213 /**
214 * Assert if a job was pushed with chained jobs based on a truth-test callback.
215 *
216 * @param string $job
217 * @param array $expectedChain
218 * @param callable|null $callback
219 * @return void
220 */
221 protected function assertPushedWithChainOfObjects($job, $expectedChain, $callback)
222 {
223 $chain = (new Collection($expectedChain))->map(fn ($job) => serialize($job))->all();
224
225 PHPUnit::assertTrue(
226 $this->pushed($job, $callback)->filter(fn ($job) => $job->chained == $chain)->isNotEmpty(),
227 'The expected chain was not pushed.'
228 );
229 }
230
231 /**
232 * Assert if a job was pushed with chained jobs based on a truth-test callback.
233 *
234 * @param string $job
235 * @param array $expectedChain
236 * @param callable|null $callback
237 * @return void
238 */
239 protected function assertPushedWithChainOfClasses($job, $expectedChain, $callback)
240 {
241 $matching = $this->pushed($job, $callback)->map->chained->map(function ($chain) {
242 return (new Collection($chain))->map(function ($job) {
243 return get_class(unserialize($job));
244 });
245 })->filter(function ($chain) use ($expectedChain) {
246 return $chain->all() === $expectedChain;
247 });
248
249 PHPUnit::assertTrue(
250 $matching->isNotEmpty(), 'The expected chain was not pushed.'
251 );
252 }
253
254 /**
255 * Assert if a closure was pushed based on a truth-test callback.
256 *
257 * @param callable|int|null $callback
258 * @return void
259 */
260 public function assertClosurePushed($callback = null)
261 {
262 $this->assertPushed(CallQueuedClosure::class, $callback);
263 }
264
265 /**
266 * Assert that a closure was not pushed based on a truth-test callback.
267 *
268 * @param callable|null $callback
269 * @return void
270 */
271 public function assertClosureNotPushed($callback = null)
272 {
273 $this->assertNotPushed(CallQueuedClosure::class, $callback);
274 }
275
276 /**
277 * Determine if the given chain is entirely composed of objects.
278 *
279 * @param array $chain
280 * @return bool
281 */
282 protected function isChainOfObjects($chain)
283 {
284 return ! (new Collection($chain))->contains(fn ($job) => ! is_object($job));
285 }
286
287 /**
288 * Determine if a job was pushed based on a truth-test callback.
289 *
290 * @param string|\Closure $job
291 * @param callable|null $callback
292 * @return void
293 */
294 public function assertNotPushed($job, $callback = null)
295 {
296 if ($job instanceof Closure) {
297 [$job, $callback] = [$this->firstClosureParameterType($job), $job];
298 }
299
300 PHPUnit::assertCount(
301 0, $this->pushed($job, $callback),
302 "The unexpected [{$job}] job was pushed."
303 );
304 }
305
306 /**
307 * Assert the total count of jobs that were pushed.
308 *
309 * @param int $expectedCount
310 * @return void
311 */
312 public function assertCount($expectedCount)
313 {
314 $actualCount = (new Collection($this->jobs))->flatten(1)->count();
315
316 PHPUnit::assertSame(
317 $expectedCount, $actualCount,
318 "Expected {$expectedCount} jobs to be pushed, but found {$actualCount} instead."
319 );
320 }
321
322 /**
323 * Assert that no jobs were pushed.
324 *
325 * @return void
326 */
327 public function assertNothingPushed()
328 {
329 $pushedJobs = implode("\n- ", array_keys($this->jobs));
330
331 PHPUnit::assertEmpty($this->jobs, "The following jobs were pushed unexpectedly:\n\n- $pushedJobs\n");
332 }
333
334 /**
335 * Get all of the jobs matching a truth-test callback.
336 *
337 * @param string $job
338 * @param callable|null $callback
339 * @return \Illuminate\Support\Collection
340 */
341 public function pushed($job, $callback = null)
342 {
343 if (! $this->hasPushed($job)) {
344 return new Collection;
345 }
346
347 $callback = $callback ?: fn () => true;
348
349 return (new Collection($this->jobs[$job]))->filter(
350 fn ($data) => $callback($data['job'], $data['queue'], $data['data'])
351 )->pluck('job');
352 }
353
354 /**
355 * Get all of the raw pushes matching a truth-test callback.
356 *
357 * @param null|\Closure(string, ?string, array): bool $callback
358 * @return \Illuminate\Support\Collection<int, RawPushType>
359 */
360 public function pushedRaw($callback = null)
361 {
362 $callback ??= static fn () => true;
363
364 return (new Collection($this->rawPushes))->filter(fn ($data) => $callback($data['payload'], $data['queue'], $data['options']));
365 }
366
367 /**
368 * Get all of the jobs by listener class, passing an optional truth-test callback.
369 *
370 * @param class-string $listenerClass
371 * @param (\Closure(mixed, \Illuminate\Events\CallQueuedListener, string|null, mixed): bool)|null $callback
372 * @return \Illuminate\Support\Collection<int, \Illuminate\Events\CallQueuedListener>
373 */
374 public function listenersPushed($listenerClass, $callback = null)
375 {
376 if (! $this->hasPushed(CallQueuedListener::class)) {
377 return new Collection;
378 }
379
380 $collection = (new Collection($this->jobs[CallQueuedListener::class]))
381 ->filter(fn ($data) => $data['job']->class === $listenerClass);
382
383 if ($callback) {
384 $collection = $collection->filter(fn ($data) => $callback($data['job']->data[0] ?? null, $data['job'], $data['queue'], $data['data']));
385 }
386
387 return $collection->pluck('job');
388 }
389
390 /**
391 * Determine if there are any stored jobs for a given class.
392 *
393 * @param string $job
394 * @return bool
395 */
396 public function hasPushed($job)
397 {
398 return isset($this->jobs[$job]) && ! empty($this->jobs[$job]);
399 }
400
401 /**
402 * Resolve a queue connection instance.
403 *
404 * @param mixed $value
405 * @return \Illuminate\Contracts\Queue\Queue
406 */
407 public function connection($value = null)
408 {
409 return $this;
410 }
411
412 /**
413 * Get the size of the queue.
414 *
415 * @param string|null $queue
416 * @return int
417 */
418 public function size($queue = null)
419 {
420 return (new Collection($this->jobs))
421 ->flatten(1)
422 ->filter(fn ($job) => $job['queue'] === $queue)
423 ->count();
424 }
425
426 /**
427 * Get the number of pending jobs.
428 *
429 * @param string|null $queue
430 * @return int
431 */
432 public function pendingSize($queue = null)
433 {
434 return $this->size($queue);
435 }
436
437 /**
438 * Get the number of delayed jobs.
439 *
440 * @param string|null $queue
441 * @return int
442 */
443 public function delayedSize($queue = null)
444 {
445 return 0;
446 }
447
448 /**
449 * Get the number of reserved jobs.
450 *
451 * @param string|null $queue
452 * @return int
453 */
454 public function reservedSize($queue = null)
455 {
456 return 0;
457 }
458
459 /**
460 * Get the creation timestamp of the oldest pending job, excluding delayed jobs.
461 *
462 * @param string|null $queue
463 * @return int|null
464 */
465 public function creationTimeOfOldestPendingJob($queue = null)
466 {
467 return null;
468 }
469
470 /**
471 * Push a new job onto the queue.
472 *
473 * @param string|object $job
474 * @param mixed $data
475 * @param string|null $queue
476 * @return mixed
477 */
478 public function push($job, $data = '', $queue = null)
479 {
480 if ($this->shouldFakeJob($job)) {
481 if ($job instanceof Closure) {
482 $job = CallQueuedClosure::create($job);
483 }
484
485 $this->jobs[is_object($job) ? get_class($job) : $job][] = [
486 'job' => $this->serializeAndRestore ? $this->serializeAndRestoreJob($job) : $job,
487 'queue' => $queue,
488 'data' => $data,
489 ];
490
491 if ($job instanceof ShouldBeUnique) {
492 $this->uniqueJobs[] = $job;
493 }
494 } else {
495 is_object($job) && isset($job->connection)
496 ? $this->queue->connection($job->connection)->push($job, $data, $queue)
497 : $this->queue->push($job, $data, $queue);
498 }
499 }
500
501 /**
502 * Determine if a job should be faked or actually dispatched.
503 *
504 * @param object $job
505 * @return bool
506 */
507 public function shouldFakeJob($job)
508 {
509 if ($this->shouldDispatchJob($job)) {
510 return false;
511 }
512
513 if ($this->jobsToFake->isEmpty()) {
514 return true;
515 }
516
517 return $this->jobsToFake->contains(
518 fn ($jobToFake) => $job instanceof ((string) $jobToFake) || $job === (string) $jobToFake
519 );
520 }
521
522 /**
523 * Determine if a job should be pushed to the queue instead of faked.
524 *
525 * @param object $job
526 * @return bool
527 */
528 protected function shouldDispatchJob($job)
529 {
530 if ($this->jobsToBeQueued->isEmpty()) {
531 return false;
532 }
533
534 return $this->jobsToBeQueued->contains(
535 fn ($jobToQueue) => $job instanceof ((string) $jobToQueue)
536 );
537 }
538
539 /**
540 * Push a raw payload onto the queue.
541 *
542 * @param string $payload
543 * @param string|null $queue
544 * @param array $options
545 * @return mixed
546 */
547 public function pushRaw($payload, $queue = null, array $options = [])
548 {
549 $this->rawPushes[] = [
550 'payload' => $payload,
551 'queue' => $queue,
552 'options' => $options,
553 ];
554 }
555
556 /**
557 * Push a new job onto the queue after (n) seconds.
558 *
559 * @param \DateTimeInterface|\DateInterval|int $delay
560 * @param string|object $job
561 * @param mixed $data
562 * @param string|null $queue
563 * @return mixed
564 */
565 public function later($delay, $job, $data = '', $queue = null)
566 {
567 return $this->push($job, $data, $queue);
568 }
569
570 /**
571 * Push a new job onto the queue.
572 *
573 * @param string $queue
574 * @param string|object $job
575 * @param mixed $data
576 * @return mixed
577 */
578 public function pushOn($queue, $job, $data = '')
579 {
580 return $this->push($job, $data, $queue);
581 }
582
583 /**
584 * Push a new job onto a specific queue after (n) seconds.
585 *
586 * @param string $queue
587 * @param \DateTimeInterface|\DateInterval|int $delay
588 * @param string|object $job
589 * @param mixed $data
590 * @return mixed
591 */
592 public function laterOn($queue, $delay, $job, $data = '')
593 {
594 return $this->push($job, $data, $queue);
595 }
596
597 /**
598 * Pop the next job off of the queue.
599 *
600 * @param string|null $queue
601 * @return \Illuminate\Contracts\Queue\Job|null
602 */
603 public function pop($queue = null)
604 {
605 //
606 }
607
608 /**
609 * Push an array of jobs onto the queue.
610 *
611 * @param array $jobs
612 * @param mixed $data
613 * @param string|null $queue
614 * @return mixed
615 */
616 public function bulk($jobs, $data = '', $queue = null)
617 {
618 foreach ($jobs as $job) {
619 $this->push($job, $data, $queue);
620 }
621 }
622
623 /**
624 * Get the jobs that have been pushed.
625 *
626 * @return array
627 */
628 public function pushedJobs()
629 {
630 return $this->jobs;
631 }
632
633 /**
634 * Get the payloads that were pushed raw.
635 *
636 * @return list<RawPushType>
637 */
638 public function rawPushes()
639 {
640 return $this->rawPushes;
641 }
642
643 /**
644 * Specify if jobs should be serialized and restored when being "pushed" to the queue.
645 *
646 * @param bool $serializeAndRestore
647 * @return $this
648 */
649 public function serializeAndRestore(bool $serializeAndRestore = true)
650 {
651 $this->serializeAndRestore = $serializeAndRestore;
652
653 return $this;
654 }
655
656 /**
657 * Serialize and unserialize the job to simulate the queueing process.
658 *
659 * @param mixed $job
660 * @return mixed
661 */
662 protected function serializeAndRestoreJob($job)
663 {
664 return unserialize(serialize($job));
665 }
666
667 /**
668 * Release the locks for all unique jobs that were pushed.
669 *
670 * @return void
671 */
672 public function releaseUniqueJobLocks()
673 {
674 $lock = new UniqueLock($this->app->make(Cache::class));
675
676 foreach ($this->uniqueJobs as $job) {
677 $lock->release($job);
678 }
679
680 $this->uniqueJobs = [];
681 }
682
683 /**
684 * Get the connection name for the queue.
685 *
686 * @return string
687 */
688 public function getConnectionName()
689 {
690 //
691 }
692
693 /**
694 * Set the connection name for the queue.
695 *
696 * @param string $name
697 * @return $this
698 */
699 public function setConnectionName($name)
700 {
701 return $this;
702 }
703
704 /**
705 * Override the QueueManager to prevent circular dependency.
706 *
707 * @param string $method
708 * @param array $parameters
709 * @return mixed
710 *
711 * @throws \BadMethodCallException
712 */
713 public function __call($method, $parameters)
714 {
715 throw new BadMethodCallException(sprintf(
716 'Call to undefined method %s::%s()', static::class, $method
717 ));
718 }
719 }