Timebox.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace Illuminate\Support;
  3. use Throwable;
  4. class Timebox
  5. {
  6. /**
  7. * Indicates if the timebox is allowed to return early.
  8. *
  9. * @var bool
  10. */
  11. public $earlyReturn = false;
  12. /**
  13. * Invoke the given callback within the specified timebox minimum.
  14. *
  15. * @template TCallReturnType
  16. *
  17. * @param (callable($this): TCallReturnType) $callback
  18. * @param int $microseconds
  19. * @return TCallReturnType
  20. *
  21. * @throws \Throwable
  22. */
  23. public function call(callable $callback, int $microseconds)
  24. {
  25. $exception = null;
  26. $start = microtime(true);
  27. try {
  28. $result = $callback($this);
  29. } catch (Throwable $caught) {
  30. $exception = $caught;
  31. }
  32. $remainder = intval($microseconds - ((microtime(true) - $start) * 1000000));
  33. if (! $this->earlyReturn && $remainder > 0) {
  34. $this->usleep($remainder);
  35. }
  36. if ($exception) {
  37. throw $exception;
  38. }
  39. return $result;
  40. }
  41. /**
  42. * Indicate that the timebox can return early.
  43. *
  44. * @return $this
  45. */
  46. public function returnEarly()
  47. {
  48. $this->earlyReturn = true;
  49. return $this;
  50. }
  51. /**
  52. * Indicate that the timebox cannot return early.
  53. *
  54. * @return $this
  55. */
  56. public function dontReturnEarly()
  57. {
  58. $this->earlyReturn = false;
  59. return $this;
  60. }
  61. /**
  62. * Sleep for the specified number of microseconds.
  63. *
  64. * @param int $microseconds
  65. * @return void
  66. */
  67. protected function usleep(int $microseconds)
  68. {
  69. Sleep::usleep($microseconds);
  70. }
  71. }