Debian Codegraph @

lib/3rdParty/composer/symfony/clock/Clock.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Clock;
13
14 use Psr\Clock\ClockInterface as PsrClockInterface;
15
16 /**
17 * A global clock.
18 *
19 * @author Nicolas Grekas <[email protected]>
20 */
21 final class Clock implements ClockInterface
22 {
23 private static ClockInterface $globalClock;
24
25 public function __construct(
26 private readonly ?PsrClockInterface $clock = null,
27 private ?\DateTimeZone $timezone = null,
28 ) {
29 }
30
31 /**
32 * Returns the current global clock.
33 *
34 * Note that you should prefer injecting a ClockInterface or using
35 * ClockAwareTrait when possible instead of using this method.
36 */
37 public static function get(): ClockInterface
38 {
39 return self::$globalClock ??= new NativeClock();
40 }
41
42 public static function set(PsrClockInterface $clock): void
43 {
44 self::$globalClock = $clock instanceof ClockInterface ? $clock : new self($clock);
45 }
46
47 public function now(): DatePoint
48 {
49 $now = ($this->clock ?? self::get())->now();
50
51 if (!$now instanceof DatePoint) {
52 $now = DatePoint::createFromInterface($now);
53 }
54
55 return isset($this->timezone) ? $now->setTimezone($this->timezone) : $now;
56 }
57
58 public function sleep(float|int $seconds): void
59 {
60 $clock = $this->clock ?? self::get();
61
62 if ($clock instanceof ClockInterface) {
63 $clock->sleep($seconds);
64 } else {
65 (new NativeClock())->sleep($seconds);
66 }
67 }
68
69 /**
70 * @throws \DateInvalidTimeZoneException When $timezone is invalid
71 */
72 public function withTimeZone(\DateTimeZone|string $timezone): static
73 {
74 if (\PHP_VERSION_ID >= 80300 && \is_string($timezone)) {
75 $timezone = new \DateTimeZone($timezone);
76 } elseif (\is_string($timezone)) {
77 try {
78 $timezone = new \DateTimeZone($timezone);
79 } catch (\Exception $e) {
80 throw new \DateInvalidTimeZoneException($e->getMessage(), $e->getCode(), $e);
81 }
82 }
83
84 $clone = clone $this;
85 $clone->timezone = $timezone;
86
87 return $clone;
88 }
89 }