|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 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 | +/** |
| 15 | + * A clock that always returns the same date, suitable for testing time-sensitive logic. |
| 16 | + * |
| 17 | + * @author Nicolas Grekas <p@tchwork.com> |
| 18 | + */ |
| 19 | +final class MockClock implements TimeInterface |
| 20 | +{ |
| 21 | + private \DateTimeImmutable $now; |
| 22 | + |
| 23 | + public function __construct(\DateTimeImmutable|\DateTimeZone|string $now = null) |
| 24 | + { |
| 25 | + if (\is_string($now ??= 'UTC')) { |
| 26 | + try { |
| 27 | + $now = new \DateTimeZone($now); |
| 28 | + } catch (\Exception) { |
| 29 | + $now = new \DateTimeImmutable($now); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + $this->now = $now instanceof \DateTimeImmutable ? $now : new \DateTimeImmutable('now', $now); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * {@inheritdoc} |
| 38 | + */ |
| 39 | + public function now(): \DateTimeImmutable |
| 40 | + { |
| 41 | + return clone $this->now; |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * {@inheritdoc} |
| 46 | + */ |
| 47 | + public function timeArray(): array |
| 48 | + { |
| 49 | + $now = explode('.', $this->now->format('U.u')); |
| 50 | + |
| 51 | + return [(int) $now[0], (float) $now[1]]; |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * {@inheritdoc} |
| 56 | + */ |
| 57 | + public function timeFloat(): float |
| 58 | + { |
| 59 | + return (float) $this->now->format('U.u'); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * {@inheritdoc} |
| 64 | + */ |
| 65 | + public function timeInt(): int |
| 66 | + { |
| 67 | + return $this->now->getTimestamp(); |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * {@inheritdoc} |
| 72 | + */ |
| 73 | + public function sleep(float|int $seconds): void |
| 74 | + { |
| 75 | + $now = explode('.', $this->now->format('U.u')); |
| 76 | + |
| 77 | + if (0 < $s = (int) $seconds) { |
| 78 | + $now[0] += $s; |
| 79 | + } |
| 80 | + |
| 81 | + if (0 < ($us = $seconds - $s) && 1E6 <= $now[1] += $us * 1E6) { |
| 82 | + ++$now[0]; |
| 83 | + $now[1] -= 1E6; |
| 84 | + } |
| 85 | + |
| 86 | + $datetime = '@'.$now[0].'.'.str_pad($now[1], 6, 0, \STR_PAD_LEFT); |
| 87 | + $timezone = $this->now->getTimezone(); |
| 88 | + |
| 89 | + $this->now = (new \DateTimeImmutable($datetime, $timezone))->setTimezone($timezone); |
| 90 | + } |
| 91 | +} |
0 commit comments