Sleep.php 12 KB

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