InteractsWithTime.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Utils;
  12. use Carbon\Carbon;
  13. use DateInterval;
  14. use DateTimeInterface;
  15. trait InteractsWithTime
  16. {
  17. /**
  18. * Get the number of seconds until the given DateTime.
  19. *
  20. * @param \DateInterval|\DateTimeInterface|int $delay
  21. */
  22. protected function secondsUntil($delay): int
  23. {
  24. $delay = $this->parseDateInterval($delay);
  25. return $delay instanceof DateTimeInterface
  26. ? max(0, $delay->getTimestamp() - $this->currentTime())
  27. : (int) $delay;
  28. }
  29. /**
  30. * Get the "available at" UNIX timestamp.
  31. *
  32. * @param \DateInterval|\DateTimeInterface|int $delay
  33. */
  34. protected function availableAt($delay = 0): int
  35. {
  36. $delay = $this->parseDateInterval($delay);
  37. return $delay instanceof DateTimeInterface
  38. ? $delay->getTimestamp()
  39. : Carbon::now()->addSeconds($delay)->getTimestamp();
  40. }
  41. /**
  42. * If the given value is an interval, convert it to a DateTime instance.
  43. *
  44. * @param \DateInterval|\DateTimeInterface|int $delay
  45. * @return \DateTimeInterface|int
  46. */
  47. protected function parseDateInterval($delay)
  48. {
  49. if ($delay instanceof DateInterval) {
  50. $delay = Carbon::now()->add($delay);
  51. }
  52. return $delay;
  53. }
  54. /**
  55. * Get the current system time as a UNIX timestamp.
  56. */
  57. protected function currentTime(): int
  58. {
  59. return Carbon::now()->getTimestamp();
  60. }
  61. }