InteractsWithTime.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Illuminate\Support;
  3. use Carbon\CarbonInterval;
  4. use DateInterval;
  5. use DateTimeInterface;
  6. trait InteractsWithTime
  7. {
  8. /**
  9. * Get the number of seconds until the given DateTime.
  10. *
  11. * @param \DateTimeInterface|\DateInterval|int $delay
  12. * @return int
  13. */
  14. protected function secondsUntil($delay)
  15. {
  16. $delay = $this->parseDateInterval($delay);
  17. return $delay instanceof DateTimeInterface
  18. ? max(0, $delay->getTimestamp() - $this->currentTime())
  19. : (int) $delay;
  20. }
  21. /**
  22. * Get the "available at" UNIX timestamp.
  23. *
  24. * @param \DateTimeInterface|\DateInterval|int $delay
  25. * @return int
  26. */
  27. protected function availableAt($delay = 0)
  28. {
  29. $delay = $this->parseDateInterval($delay);
  30. return $delay instanceof DateTimeInterface
  31. ? $delay->getTimestamp()
  32. : Carbon::now()->addSeconds($delay)->getTimestamp();
  33. }
  34. /**
  35. * If the given value is an interval, convert it to a DateTime instance.
  36. *
  37. * @param \DateTimeInterface|\DateInterval|int $delay
  38. * @return \DateTimeInterface|int
  39. */
  40. protected function parseDateInterval($delay)
  41. {
  42. if ($delay instanceof DateInterval) {
  43. $delay = Carbon::now()->add($delay);
  44. }
  45. return $delay;
  46. }
  47. /**
  48. * Get the current system time as a UNIX timestamp.
  49. *
  50. * @return int
  51. */
  52. protected function currentTime()
  53. {
  54. return Carbon::now()->getTimestamp();
  55. }
  56. /**
  57. * Given a start time, format the total run time for human readability.
  58. *
  59. * @param float $startTime
  60. * @param float|null $endTime
  61. * @return string
  62. */
  63. protected function runTimeForHumans($startTime, $endTime = null)
  64. {
  65. $endTime ??= microtime(true);
  66. $runTime = ($endTime - $startTime) * 1000;
  67. return $runTime > 1000
  68. ? CarbonInterval::milliseconds($runTime)->cascade()->forHumans(short: true)
  69. : number_format($runTime, 2).'ms';
  70. }
  71. }