| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Clock; |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
final class MockClock implements ClockInterface |
| 22 |
{ |
| 23 |
private DatePoint $now; |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
public function __construct(\DateTimeImmutable|string $now = 'now', \DateTimeZone|string|null $timezone = null) |
| 30 |
{ |
| 31 |
if (\PHP_VERSION_ID >= 80300 && \is_string($timezone)) { |
| 32 |
$timezone = new \DateTimeZone($timezone); |
| 33 |
} elseif (\is_string($timezone)) { |
| 34 |
try { |
| 35 |
$timezone = new \DateTimeZone($timezone); |
| 36 |
} catch (\Exception $e) { |
| 37 |
throw new \DateInvalidTimeZoneException($e->getMessage(), $e->getCode(), $e); |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
if (\is_string($now)) { |
| 42 |
$now = new DatePoint($now, $timezone ?? new \DateTimeZone('UTC')); |
| 43 |
} elseif (!$now instanceof DatePoint) { |
| 44 |
$now = DatePoint::createFromInterface($now); |
| 45 |
} |
| 46 |
|
| 47 |
$this->now = null !== $timezone ? $now->setTimezone($timezone) : $now; |
| 48 |
} |
| 49 |
|
| 50 |
public function now(): DatePoint |
| 51 |
{ |
| 52 |
return clone $this->now; |
| 53 |
} |
| 54 |
|
| 55 |
public function sleep(float|int $seconds): void |
| 56 |
{ |
| 57 |
if (0 >= $seconds) { |
| 58 |
return; |
| 59 |
} |
| 60 |
|
| 61 |
$now = (float) $this->now->format('Uu') + $seconds * 1e6; |
| 62 |
$now = substr_replace(\sprintf('@%07.0F', $now), '.', -6, 0); |
| 63 |
$timezone = $this->now->getTimezone(); |
| 64 |
|
| 65 |
$this->now = DatePoint::createFromInterface(new \DateTimeImmutable($now, $timezone))->setTimezone($timezone); |
| 66 |
} |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
public function modify(string $modifier): void |
| 72 |
{ |
| 73 |
if (\PHP_VERSION_ID < 80300) { |
| 74 |
$this->now = @$this->now->modify($modifier) ?: throw new \DateMalformedStringException(error_get_last()['message'] ?? \sprintf('Invalid modifier: "%s". Could not modify MockClock.', $modifier)); |
| 75 |
|
| 76 |
return; |
| 77 |
} |
| 78 |
|
| 79 |
$this->now = $this->now->modify($modifier); |
| 80 |
} |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
public function withTimeZone(\DateTimeZone|string $timezone): static |
| 86 |
{ |
| 87 |
if (\PHP_VERSION_ID >= 80300 && \is_string($timezone)) { |
| 88 |
$timezone = new \DateTimeZone($timezone); |
| 89 |
} elseif (\is_string($timezone)) { |
| 90 |
try { |
| 91 |
$timezone = new \DateTimeZone($timezone); |
| 92 |
} catch (\Exception $e) { |
| 93 |
throw new \DateInvalidTimeZoneException($e->getMessage(), $e->getCode(), $e); |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
$clone = clone $this; |
| 98 |
$clone->now = $clone->now->setTimezone($timezone); |
| 99 |
|
| 100 |
return $clone; |
| 101 |
} |
| 102 |
} |