| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Clock; |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
final class MonotonicClock implements ClockInterface |
| 20 |
{ |
| 21 |
private int $sOffset; |
| 22 |
private int $usOffset; |
| 23 |
private \DateTimeZone $timezone; |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
public function __construct(\DateTimeZone|string|null $timezone = null) |
| 29 |
{ |
| 30 |
if (false === $offset = hrtime()) { |
| 31 |
throw new \RuntimeException('hrtime() returned false: the runtime environment does not provide access to a monotonic timer.'); |
| 32 |
} |
| 33 |
|
| 34 |
$time = explode(' ', microtime(), 2); |
| 35 |
$this->sOffset = $time[1] - $offset[0]; |
| 36 |
$this->usOffset = (int) ($time[0] * 1000000) - (int) ($offset[1] / 1000); |
| 37 |
|
| 38 |
$this->timezone = \is_string($timezone ??= date_default_timezone_get()) ? $this->withTimeZone($timezone)->timezone : $timezone; |
| 39 |
} |
| 40 |
|
| 41 |
public function now(): DatePoint |
| 42 |
{ |
| 43 |
[$s, $us] = hrtime(); |
| 44 |
|
| 45 |
if (1000000 <= $us = (int) ($us / 1000) + $this->usOffset) { |
| 46 |
++$s; |
| 47 |
$us -= 1000000; |
| 48 |
} elseif (0 > $us) { |
| 49 |
--$s; |
| 50 |
$us += 1000000; |
| 51 |
} |
| 52 |
|
| 53 |
if (6 !== \strlen($now = (string) $us)) { |
| 54 |
$now = str_pad($now, 6, '0', \STR_PAD_LEFT); |
| 55 |
} |
| 56 |
|
| 57 |
$now = '@'.($s + $this->sOffset).'.'.$now; |
| 58 |
|
| 59 |
return DatePoint::createFromInterface(new \DateTimeImmutable($now, $this->timezone))->setTimezone($this->timezone); |
| 60 |
} |
| 61 |
|
| 62 |
public function sleep(float|int $seconds): void |
| 63 |
{ |
| 64 |
if (0 < $s = (int) $seconds) { |
| 65 |
sleep($s); |
| 66 |
} |
| 67 |
|
| 68 |
if (0 < $us = $seconds - $s) { |
| 69 |
usleep((int) ($us * 1E6)); |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
public function withTimeZone(\DateTimeZone|string $timezone): static |
| 77 |
{ |
| 78 |
if (\PHP_VERSION_ID >= 80300 && \is_string($timezone)) { |
| 79 |
$timezone = new \DateTimeZone($timezone); |
| 80 |
} elseif (\is_string($timezone)) { |
| 81 |
try { |
| 82 |
$timezone = new \DateTimeZone($timezone); |
| 83 |
} catch (\Exception $e) { |
| 84 |
throw new \DateInvalidTimeZoneException($e->getMessage(), $e->getCode(), $e); |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
$clone = clone $this; |
| 89 |
$clone->timezone = $timezone; |
| 90 |
|
| 91 |
return $clone; |
| 92 |
} |
| 93 |
} |