NativeClock.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Clock;
  11. /**
  12. * A clock that relies the system time.
  13. *
  14. * @author Nicolas Grekas <p@tchwork.com>
  15. */
  16. final class NativeClock implements ClockInterface
  17. {
  18. private \DateTimeZone $timezone;
  19. /**
  20. * @throws \DateInvalidTimeZoneException When $timezone is invalid
  21. */
  22. public function __construct(\DateTimeZone|string|null $timezone = null)
  23. {
  24. $this->timezone = \is_string($timezone ??= date_default_timezone_get()) ? $this->withTimeZone($timezone)->timezone : $timezone;
  25. }
  26. public function now(): DatePoint
  27. {
  28. return DatePoint::createFromInterface(new \DateTimeImmutable('now', $this->timezone));
  29. }
  30. public function sleep(float|int $seconds): void
  31. {
  32. if (0 < $s = (int) $seconds) {
  33. sleep($s);
  34. }
  35. if (0 < $us = $seconds - $s) {
  36. usleep((int) ($us * 1E6));
  37. }
  38. }
  39. /**
  40. * @throws \DateInvalidTimeZoneException When $timezone is invalid
  41. */
  42. public function withTimeZone(\DateTimeZone|string $timezone): static
  43. {
  44. if (\PHP_VERSION_ID >= 80300 && \is_string($timezone)) {
  45. $timezone = new \DateTimeZone($timezone);
  46. } elseif (\is_string($timezone)) {
  47. try {
  48. $timezone = new \DateTimeZone($timezone);
  49. } catch (\Exception $e) {
  50. throw new \DateInvalidTimeZoneException($e->getMessage(), $e->getCode(), $e);
  51. }
  52. }
  53. $clone = clone $this;
  54. $clone->timezone = $timezone;
  55. return $clone;
  56. }
  57. }