Clock.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. use Psr\Clock\ClockInterface as PsrClockInterface;
  12. /**
  13. * A global clock.
  14. *
  15. * @author Nicolas Grekas <p@tchwork.com>
  16. */
  17. final class Clock implements ClockInterface
  18. {
  19. private static ClockInterface $globalClock;
  20. public function __construct(
  21. private readonly ?PsrClockInterface $clock = null,
  22. private ?\DateTimeZone $timezone = null,
  23. ) {
  24. }
  25. /**
  26. * Returns the current global clock.
  27. *
  28. * Note that you should prefer injecting a ClockInterface or using
  29. * ClockAwareTrait when possible instead of using this method.
  30. */
  31. public static function get(): ClockInterface
  32. {
  33. return self::$globalClock ??= new NativeClock();
  34. }
  35. public static function set(PsrClockInterface $clock): void
  36. {
  37. self::$globalClock = $clock instanceof ClockInterface ? $clock : new self($clock);
  38. }
  39. public function now(): DatePoint
  40. {
  41. $now = ($this->clock ?? self::get())->now();
  42. if (!$now instanceof DatePoint) {
  43. $now = DatePoint::createFromInterface($now);
  44. }
  45. return isset($this->timezone) ? $now->setTimezone($this->timezone) : $now;
  46. }
  47. public function sleep(float|int $seconds): void
  48. {
  49. $clock = $this->clock ?? self::get();
  50. if ($clock instanceof ClockInterface) {
  51. $clock->sleep($seconds);
  52. } else {
  53. (new NativeClock())->sleep($seconds);
  54. }
  55. }
  56. /**
  57. * @throws \DateInvalidTimeZoneException When $timezone is invalid
  58. */
  59. public function withTimeZone(\DateTimeZone|string $timezone): static
  60. {
  61. if (\PHP_VERSION_ID >= 80300 && \is_string($timezone)) {
  62. $timezone = new \DateTimeZone($timezone);
  63. } elseif (\is_string($timezone)) {
  64. try {
  65. $timezone = new \DateTimeZone($timezone);
  66. } catch (\Exception $e) {
  67. throw new \DateInvalidTimeZoneException($e->getMessage(), $e->getCode(), $e);
  68. }
  69. }
  70. $clone = clone $this;
  71. $clone->timezone = $timezone;
  72. return $clone;
  73. }
  74. }