InteractsWithTime.php 1.5KB

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