Timebox.php 1.3 KB

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