| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Clock; |
| 13 |
|
| 14 |
use Psr\Clock\ClockInterface as PsrClockInterface; |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 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 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 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 |
|
| 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 |
} |