|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the aether/aether. |
| 5 | + * |
| 6 | + * Copyright (C) 2024 Dominik Szamburski |
| 7 | + * |
| 8 | + * This software may be modified and distributed under the terms |
| 9 | + * of the MIT license. See the LICENSE file for details. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Aether\Clock; |
| 13 | + |
| 14 | +class FrozenClock implements Clock |
| 15 | +{ |
| 16 | + private \DateTimeImmutable $datetime; |
| 17 | + |
| 18 | + /** |
| 19 | + * @param \DateTimeImmutable|non-empty-string $datetime |
| 20 | + * @param \DateTimeZone|string $timezone |
| 21 | + * |
| 22 | + * @throws \DateInvalidTimeZoneException When $timezone is invalid. |
| 23 | + * @throws \DateMalformedStringException When $datetime is invalid. |
| 24 | + */ |
| 25 | + public function __construct( |
| 26 | + \DateTimeImmutable|string $datetime = 'now', |
| 27 | + \DateTimeZone|string $timezone = Clock::DEFAULT_TIMEZONE |
| 28 | + ) { |
| 29 | + if (\is_string($timezone)) { |
| 30 | + $timezone = new \DateTimeZone($timezone); |
| 31 | + } |
| 32 | + |
| 33 | + if (\is_string($datetime)) { |
| 34 | + $datetime = new \DateTimeImmutable($datetime); |
| 35 | + } |
| 36 | + |
| 37 | + $this->datetime = $datetime->setTimezone($timezone); |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * {@inheritDoc} |
| 42 | + */ |
| 43 | + public function __toString(): string |
| 44 | + { |
| 45 | + return \sprintf( |
| 46 | + '%s (%s)', |
| 47 | + $this->now()->format(\DateTimeInterface::ISO8601_EXPANDED), |
| 48 | + $this->now()->getTimezone()->getName() |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * {@inheritDoc} |
| 54 | + */ |
| 55 | + #[\Override] |
| 56 | + public function now(): \DateTimeImmutable |
| 57 | + { |
| 58 | + return $this->datetime; |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * {@inheritDoc} |
| 63 | + */ |
| 64 | + public function withTimezone(\DateTimeZone|string $timezone): static |
| 65 | + { |
| 66 | + if (\is_string($timezone)) { |
| 67 | + $timezone = new \DateTimeZone($timezone); |
| 68 | + } |
| 69 | + |
| 70 | + $self = clone $this; |
| 71 | + $self->datetime = $self->datetime->setTimezone($timezone); |
| 72 | + |
| 73 | + return $self; |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * {@inheritDoc} |
| 78 | + */ |
| 79 | + public function sleep(float|int $seconds): void |
| 80 | + { |
| 81 | + $wholeSeconds = \floor($seconds); |
| 82 | + $microSeconds = \round(($seconds - $wholeSeconds) * 1E6); |
| 83 | + |
| 84 | + if ($seconds > 0) { |
| 85 | + if (($dt = $this->datetime->modify("$wholeSeconds second")) !== false) { |
| 86 | + $this->datetime = $dt; |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + if ($microSeconds > 0) { |
| 91 | + if (($dt = $this->datetime->modify("$microSeconds microsecond")) !== false) { |
| 92 | + $this->datetime = $dt; |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | +} |
0 commit comments