Skip to content

Commit 0d67d50

Browse files
[Clock] A new component to decouple applications from the system clock
1 parent 2894680 commit 0d67d50

15 files changed

+699
-0
lines changed

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
"symfony/asset": "self.version",
5858
"symfony/browser-kit": "self.version",
5959
"symfony/cache": "self.version",
60+
"symfony/clock": "self.version",
6061
"symfony/config": "self.version",
6162
"symfony/console": "self.version",
6263
"symfony/css-selector": "self.version",
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/Tests export-ignore
2+
/phpunit.xml.dist export-ignore
3+
/.gitattributes export-ignore
4+
/.gitignore export-ignore
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
vendor/
2+
composer.lock
3+
phpunit.xml
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
CHANGELOG
2+
=========
3+
4+
6.2
5+
---
6+
7+
* Add the component
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
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 high-resolution monotonic clock, counting from an arbitrary point in time.
16+
*
17+
* @author Nicolas Grekas <[email protected]>
18+
*/
19+
final class HrClock implements TimeInterface
20+
{
21+
private \DateTimeZone $timezone;
22+
23+
public function __construct(\DateTimeZone|string $timezone = null)
24+
{
25+
if (false === hrtime()) {
26+
throw new \LogicException('hrtime() returned false: the runtime environment does not provide access to high-resolution time.');
27+
}
28+
29+
if (\is_string($timezone ??= date_default_timezone_get())) {
30+
$this->timezone = new \DateTimeZone($timezone);
31+
} else {
32+
$this->timezone = $timezone;
33+
}
34+
}
35+
36+
/**
37+
* {@inheritdoc}
38+
*/
39+
public function now(): \DateTimeImmutable
40+
{
41+
$hrtime = hrtime();
42+
$now = '@'.$hrtime[0].'.'.substr(str_pad($hrtime[1], 9, 0, \STR_PAD_LEFT), 0, -3);
43+
44+
return (new \DateTimeImmutable($now, $this->timezone))->setTimezone($this->timezone);
45+
}
46+
47+
/**
48+
* {@inheritdoc}
49+
*/
50+
public function timeArray(): array
51+
{
52+
$now = hrtime();
53+
54+
return [$now[0], (float) ($now[1] / 1E3)];
55+
}
56+
57+
/**
58+
* {@inheritdoc}
59+
*/
60+
public function timeFloat(): float
61+
{
62+
return hrtime(true) / 1E9;
63+
}
64+
65+
/**
66+
* {@inheritdoc}
67+
*/
68+
public function timeInt(): int
69+
{
70+
return hrtime()[0];
71+
}
72+
73+
public function sleep(float|int $seconds): void
74+
{
75+
if (0 < $s = (int) $seconds) {
76+
sleep($s);
77+
}
78+
79+
if (0 < $us = $seconds - $s) {
80+
usleep($us * 1E6);
81+
}
82+
}
83+
}

src/Symfony/Component/Clock/LICENSE

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Copyright (c) 2022 Fabien Potencier
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy
4+
of this software and associated documentation files (the "Software"), to deal
5+
in the Software without restriction, including without limitation the rights
6+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
copies of the Software, and to permit persons to whom the Software is furnished
8+
to do so, subject to the following conditions:
9+
10+
The above copyright notice and this permission notice shall be included in all
11+
copies or substantial portions of the Software.
12+
13+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19+
THE SOFTWARE.
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
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 <[email protected]>
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+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
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 returns the system time.
16+
*
17+
* @author Nicolas Grekas <[email protected]>
18+
*/
19+
final class NativeClock implements TimeInterface
20+
{
21+
private \DateTimeZone $timezone;
22+
23+
public function __construct(\DateTimeZone|string $timezone = null)
24+
{
25+
if (\is_string($timezone ??= date_default_timezone_get())) {
26+
$this->timezone = new \DateTimeZone($timezone);
27+
} else {
28+
$this->timezone = $timezone;
29+
}
30+
}
31+
32+
/**
33+
* {@inheritdoc}
34+
*/
35+
public function now(): \DateTimeImmutable
36+
{
37+
return new \DateTimeImmutable('now', $this->timezone);
38+
}
39+
40+
/**
41+
* {@inheritdoc}
42+
*/
43+
public function timeArray(): array
44+
{
45+
$now = gettimeofday();
46+
47+
return [$now['sec'], (float) $now['usec']];
48+
}
49+
50+
/**
51+
* {@inheritdoc}
52+
*/
53+
public function timeFloat(): float
54+
{
55+
return microtime(true);
56+
}
57+
58+
/**
59+
* {@inheritdoc}
60+
*/
61+
public function timeInt(): int
62+
{
63+
return time();
64+
}
65+
66+
public function sleep(float|int $seconds): void
67+
{
68+
if (0 < $s = (int) $seconds) {
69+
sleep($s);
70+
}
71+
72+
if (0 < $us = $seconds - $s) {
73+
usleep($us * 1E6);
74+
}
75+
}
76+
}

src/Symfony/Component/Clock/README.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
Clock Component
2+
===============
3+
4+
Symfony Clock enables decoupling applications from the system clock.
5+
6+
Getting Started
7+
---------------
8+
9+
```
10+
$ composer require symfony/clock
11+
```
12+
13+
```php
14+
use Symfony\Component\Clock\NativeClock;
15+
use Symfony\Component\Clock\TimeInterface;
16+
17+
class MyClockSensitiveClass
18+
{
19+
public function __construct(
20+
private TimeInterface $clock,
21+
) {
22+
}
23+
24+
public function doSomething()
25+
{
26+
$now = $this->clock->now();
27+
// [...] do something with $now, which is a \DateTimeImmutable object
28+
29+
$this->clock->sleep(1); // Pause execution for 1 second
30+
$this->clock->timeInt(); // Gets the current timestamp with second precision
31+
$this->clock->timeFloat(); // Gets the current timestamp with sub-second precision
32+
$this->clock->timeArray(); // Gets the current timestamp with sub-second precision and 32-bit portability
33+
}
34+
}
35+
36+
$clock = new NativeClock();
37+
$service = new MyClockSensitiveClass($clock);
38+
$service->doSomething();
39+
```
40+
41+
Resources
42+
---------
43+
44+
* [Documentation](https://symfony.com/doc/current/clock.html)
45+
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
46+
* [Report issues](https://github.com/symfony/symfony/issues) and
47+
[send Pull Requests](https://github.com/symfony/symfony/pulls)
48+
in the [main Symfony repository](https://github.com/symfony/symfony)

0 commit comments

Comments
 (0)