Sleep.php 11 KB

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