Debian Codegraph @

lib/3rdParty/composer/illuminate/support/Sleep.php

raw symbols SCIP
1 <?php
2
3 namespace Illuminate\Support;
4
5 use Carbon\CarbonInterval;
6 use Closure;
7 use DateInterval;
8 use Illuminate\Support\Traits\Macroable;
9 use PHPUnit\Framework\Assert as PHPUnit;
10 use RuntimeException;
11
12 class Sleep
13 {
14 use Macroable;
15
16 /**
17 * The fake sleep callbacks.
18 *
19 * @var array
20 */
21 public static $fakeSleepCallbacks = [];
22
23 /**
24 * Keep Carbon's "now" in sync when sleeping.
25 *
26 * @var bool
27 */
28 protected static $syncWithCarbon = false;
29
30 /**
31 * The total duration to sleep.
32 *
33 * @var \Carbon\CarbonInterval
34 */
35 public $duration;
36
37 /**
38 * The callback that determines if sleeping should continue.
39 *
40 * @var \Closure
41 */
42 public $while;
43
44 /**
45 * The pending duration to sleep.
46 *
47 * @var int|float|null
48 */
49 protected $pending = null;
50
51 /**
52 * Indicates that all sleeping should be faked.
53 *
54 * @var bool
55 */
56 protected static $fake = false;
57
58 /**
59 * The sequence of sleep durations encountered while faking.
60 *
61 * @var array<int, \Carbon\CarbonInterval>
62 */
63 protected static $sequence = [];
64
65 /**
66 * Indicates if the instance should sleep.
67 *
68 * @var bool
69 */
70 protected $shouldSleep = true;
71
72 /**
73 * Indicates if the instance already slept via `then()`.
74 *
75 * @var bool
76 */
77 protected $alreadySlept = false;
78
79 /**
80 * Create a new class instance.
81 *
82 * @param int|float|\DateInterval $duration
83 */
84 public function __construct($duration)
85 {
86 $this->duration($duration);
87 }
88
89 /**
90 * Sleep for the given duration.
91 *
92 * @param \DateInterval|int|float $duration
93 * @return static
94 */
95 public static function for($duration)
96 {
97 return new static($duration);
98 }
99
100 /**
101 * Sleep until the given timestamp.
102 *
103 * @param \DateTimeInterface|int|float|numeric-string $timestamp
104 * @return static
105 */
106 public static function until($timestamp)
107 {
108 if (is_numeric($timestamp)) {
109 $timestamp = Carbon::createFromTimestamp($timestamp, date_default_timezone_get());
110 }
111
112 return new static(Carbon::now()->diff($timestamp));
113 }
114
115 /**
116 * Sleep for the given number of microseconds.
117 *
118 * @param int $duration
119 * @return static
120 */
121 public static function usleep($duration)
122 {
123 return (new static($duration))->microseconds();
124 }
125
126 /**
127 * Sleep for the given number of seconds.
128 *
129 * @param int|float $duration
130 * @return static
131 */
132 public static function sleep($duration)
133 {
134 return (new static($duration))->seconds();
135 }
136
137 /**
138 * Sleep for the given duration. Replaces any previously defined duration.
139 *
140 * @param \DateInterval|int|float $duration
141 * @return $this
142 */
143 protected function duration($duration)
144 {
145 if (! $duration instanceof DateInterval) {
146 $this->duration = CarbonInterval::microsecond(0);
147
148 $this->pending = $duration;
149 } else {
150 $duration = CarbonInterval::instance($duration);
151
152 if ($duration->totalMicroseconds < 0) {
153 $duration = CarbonInterval::seconds(0);
154 }
155
156 $this->duration = $duration;
157 $this->pending = null;
158 }
159
160 return $this;
161 }
162
163 /**
164 * Sleep for the given number of minutes.
165 *
166 * @return $this
167 */
168 public function minutes()
169 {
170 $this->duration->add('minutes', $this->pullPending());
171
172 return $this;
173 }
174
175 /**
176 * Sleep for one minute.
177 *
178 * @return $this
179 */
180 public function minute()
181 {
182 return $this->minutes();
183 }
184
185 /**
186 * Sleep for the given number of seconds.
187 *
188 * @return $this
189 */
190 public function seconds()
191 {
192 $this->duration->add('seconds', $this->pullPending());
193
194 return $this;
195 }
196
197 /**
198 * Sleep for one second.
199 *
200 * @return $this
201 */
202 public function second()
203 {
204 return $this->seconds();
205 }
206
207 /**
208 * Sleep for the given number of milliseconds.
209 *
210 * @return $this
211 */
212 public function milliseconds()
213 {
214 $this->duration->add('milliseconds', $this->pullPending());
215
216 return $this;
217 }
218
219 /**
220 * Sleep for one millisecond.
221 *
222 * @return $this
223 */
224 public function millisecond()
225 {
226 return $this->milliseconds();
227 }
228
229 /**
230 * Sleep for the given number of microseconds.
231 *
232 * @return $this
233 */
234 public function microseconds()
235 {
236 $this->duration->add('microseconds', $this->pullPending());
237
238 return $this;
239 }
240
241 /**
242 * Sleep for on microsecond.
243 *
244 * @return $this
245 */
246 public function microsecond()
247 {
248 return $this->microseconds();
249 }
250
251 /**
252 * Add additional time to sleep for.
253 *
254 * @param int|float $duration
255 * @return $this
256 */
257 public function and($duration)
258 {
259 $this->pending = $duration;
260
261 return $this;
262 }
263
264 /**
265 * Sleep while a given callback returns "true".
266 *
267 * @param \Closure $callback
268 * @return $this
269 */
270 public function while(Closure $callback)
271 {
272 $this->while = $callback;
273
274 return $this;
275 }
276
277 /**
278 * Specify a callback that should be executed after sleeping.
279 *
280 * @param callable $then
281 * @return mixed
282 */
283 public function then(callable $then)
284 {
285 $this->goodnight();
286
287 $this->alreadySlept = true;
288
289 return $then();
290 }
291
292 /**
293 * Handle the object's destruction.
294 *
295 * @return void
296 */
297 public function __destruct()
298 {
299 $this->goodnight();
300 }
301
302 /**
303 * Handle the object's destruction.
304 *
305 * @return void
306 */
307 protected function goodnight()
308 {
309 if ($this->alreadySlept || ! $this->shouldSleep) {
310 return;
311 }
312
313 if ($this->pending !== null) {
314 throw new RuntimeException('Unknown duration unit.');
315 }
316
317 if (static::$fake) {
318 static::$sequence[] = $this->duration;
319
320 if (static::$syncWithCarbon) {
321 Carbon::setTestNow(Carbon::now()->add($this->duration));
322 }
323
324 foreach (static::$fakeSleepCallbacks as $callback) {
325 $callback($this->duration);
326 }
327
328 return;
329 }
330
331 $remaining = $this->duration->copy();
332
333 $seconds = (int) $remaining->totalSeconds;
334
335 $while = $this->while ?: function () {
336 static $return = [true, false];
337
338 return array_shift($return);
339 };
340
341 while ($while()) {
342 if ($seconds > 0) {
343 sleep($seconds);
344
345 $remaining = $remaining->subSeconds($seconds);
346 }
347
348 $microseconds = (int) $remaining->totalMicroseconds;
349
350 if ($microseconds > 0) {
351 usleep($microseconds);
352 }
353 }
354 }
355
356 /**
357 * Resolve the pending duration.
358 *
359 * @return int|float
360 */
361 protected function pullPending()
362 {
363 if ($this->pending === null) {
364 $this->shouldNotSleep();
365
366 throw new RuntimeException('No duration specified.');
367 }
368
369 if ($this->pending < 0) {
370 $this->pending = 0;
371 }
372
373 return tap($this->pending, function () {
374 $this->pending = null;
375 });
376 }
377
378 /**
379 * Stay awake and capture any attempts to sleep.
380 *
381 * @param bool $value
382 * @param bool $syncWithCarbon
383 * @return void
384 */
385 public static function fake($value = true, $syncWithCarbon = false)
386 {
387 static::$fake = $value;
388
389 static::$sequence = [];
390 static::$fakeSleepCallbacks = [];
391 static::$syncWithCarbon = $syncWithCarbon;
392 }
393
394 /**
395 * Assert a given amount of sleeping occurred a specific number of times.
396 *
397 * @param \Closure $expected
398 * @param int $times
399 * @return void
400 */
401 public static function assertSlept($expected, $times = 1)
402 {
403 $count = (new Collection(static::$sequence))->filter($expected)->count();
404
405 PHPUnit::assertSame(
406 $times,
407 $count,
408 "The expected sleep was found [{$count}] times instead of [{$times}]."
409 );
410 }
411
412 /**
413 * Assert sleeping occurred a given number of times.
414 *
415 * @param int $expected
416 * @return void
417 */
418 public static function assertSleptTimes($expected)
419 {
420 PHPUnit::assertSame($expected, $count = count(static::$sequence), "Expected [{$expected}] sleeps but found [{$count}].");
421 }
422
423 /**
424 * Assert the given sleep sequence was encountered.
425 *
426 * @param array $sequence
427 * @return void
428 */
429 public static function assertSequence($sequence)
430 {
431 try {
432 static::assertSleptTimes(count($sequence));
433
434 (new Collection($sequence))
435 ->zip(static::$sequence)
436 ->eachSpread(function (?Sleep $expected, CarbonInterval $actual) {
437 if ($expected === null) {
438 return;
439 }
440
441 PHPUnit::assertTrue(
442 $expected->shouldNotSleep()->duration->equalTo($actual),
443 vsprintf('Expected sleep duration of [%s] but actually slept for [%s].', [
444 $expected->duration->cascade()->forHumans([
445 'options' => 0,
446 'minimumUnit' => 'microsecond',
447 ]),
448 $actual->cascade()->forHumans([
449 'options' => 0,
450 'minimumUnit' => 'microsecond',
451 ]),
452 ])
453 );
454 });
455 } finally {
456 foreach ($sequence as $expected) {
457 if ($expected instanceof self) {
458 $expected->shouldNotSleep();
459 }
460 }
461 }
462 }
463
464 /**
465 * Assert that no sleeping occurred.
466 *
467 * @return void
468 */
469 public static function assertNeverSlept()
470 {
471 static::assertSleptTimes(0);
472 }
473
474 /**
475 * Assert that no sleeping occurred.
476 *
477 * @return void
478 */
479 public static function assertInsomniac()
480 {
481 if (static::$sequence === []) {
482 PHPUnit::assertTrue(true);
483 }
484
485 foreach (static::$sequence as $duration) {
486 PHPUnit::assertSame(0, (int) $duration->totalMicroseconds, vsprintf('Unexpected sleep duration of [%s] found.', [
487 $duration->cascade()->forHumans([
488 'options' => 0,
489 'minimumUnit' => 'microsecond',
490 ]),
491 ]));
492 }
493 }
494
495 /**
496 * Indicate that the instance should not sleep.
497 *
498 * @return $this
499 */
500 protected function shouldNotSleep()
501 {
502 $this->shouldSleep = false;
503
504 return $this;
505 }
506
507 /**
508 * Only sleep when the given condition is true.
509 *
510 * @param (\Closure($this): bool)|bool $condition
511 * @return $this
512 */
513 public function when($condition)
514 {
515 $this->shouldSleep = (bool) value($condition, $this);
516
517 return $this;
518 }
519
520 /**
521 * Don't sleep when the given condition is true.
522 *
523 * @param (\Closure($this): bool)|bool $condition
524 * @return $this
525 */
526 public function unless($condition)
527 {
528 return $this->when(! value($condition, $this));
529 }
530
531 /**
532 * Specify a callback that should be invoked when faking sleep within a test.
533 *
534 * @param callable $callback
535 * @return void
536 */
537 public static function whenFakingSleep($callback)
538 {
539 static::$fakeSleepCallbacks[] = $callback;
540 }
541
542 /**
543 * Indicate that Carbon's "now" should be kept in sync when sleeping.
544 *
545 * @return void
546 */
547 public static function syncWithCarbon($value = true)
548 {
549 static::$syncWithCarbon = $value;
550 }
551 }