8000 Fix `sleep()` in `MockClock` · symfony/symfony@5f9ce0f · GitHub
[go: up one dir, main page]

Skip to content

Commit 5f9ce0f

Browse files
committed
Fix sleep() in MockClock
1 parent f951250 commit 5f9ce0f

File tree

2 files changed

+17
-16
lines changed

2 files changed

+17
-16
lines changed

src/Symfony/Component/Clock/MockClock.php

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -40,21 +40,10 @@ public function now(): \DateTimeImmutable
4040

4141
public function sleep(float|int $seconds): void
4242
{
43-
$now = explode('.', $this->now->format('U.u'));
44-
45-
if (0 < $s = (int) $seconds) {
46-
$now[0] += $s;
47-
}
48-
49-
if (0 < ($us = $seconds - $s) && 1E6 <= $now[1] += $us * 1E6) {
50-
++$now[0];
51-
$now[1] -= 1E6;
52-
}
53-
54-
$datetime = '@'.$now[0].'.'.str_pad($now[1], 6, '0', \STR_PAD_LEFT);
43+
$datetime = ((float) $this->now->format('Uu') + $seconds * 1e6) / 1e6;
5544
$timezone = $this->now->getTimezone();
5645

57-
$this->now = (new \DateTimeImmutable($datetime, $timezone))->setTimezone($timezone);
46+
$this->now = (new \DateTimeImmutable(sprintf('@%.6F', $datetime), $timezone))->setTimezone($timezone);
5847
}
5948

6049
public function withTimeZone(\DateTimeZone|string $timezone): static

src/Symfony/Component/Clock/Tests/MockClockTest.php

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,26 @@ public function testNow()
5555

5656
public function testSleep()
5757
{
58-
$clock = new MockClock((new \DateTimeImmutable('@123.456'))->setTimezone(new \DateTimeZone('UTC')));
58+
// The maximum value without losing precision is 2112-09-17 23:53:47.370496
59+
$clock = new MockClock((new \DateTimeImmutable('2112-09-17 23:53:00.999Z'))->setTimezone(new \DateTimeZone('UTC')));
5960
$tz = $clock->now()->getTimezone()->getName();
6061

61-
$clock->sleep(4.999);
62-
$this->assertSame('128.455000', $clock->now()->format('U.u'));
62+
$clock->sleep(2.002001);
63+
$this->assertSame('2112-09-17 23:53:03.001001', $clock->now()->format('Y-m-d H:i:s.u'));
6364
$this->assertSame($tz, $clock->now()->getTimezone()->getName());
6465
}
6566

67+
public function testPrecisionSleep()
68+
{
69+
$precision = \ini_get('precision');
70+
ini_set('precision', -1);
71+
try {
72+
$this->testSleep();
73+
} finally {
74+
ini_set('precision', $precision);
75+
}
76+
}
77+
6678
public function testWithTimeZone()
6779
{
6880
$clock = new MockClock();

0 commit comments

Comments
 (0)
0