Skip to content

Commit 4795584

Browse files
[Clock] Add Clock::now(), get() and with()
1 parent bd6219d commit 4795584

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

src/Symfony/Component/Clock/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ CHANGELOG
55
---
66

77
* Add `ClockAwareTrait` to help write time-sensitive classes
8+
* Add `Clock::now()`, `Clock::get()` and `Clock::with()`
89

910
6.2
1011
---

src/Symfony/Component/Clock/Clock.php

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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 global clock.
16+
*
17+
* Defined as enum to be final and non-instantiable.
18+
*/
19+
enum Clock
20+
{
21+
public static function now(): \DateTimeImmutable
22+
{
23+
return self::get()->now();
24+
}
25+
26+
public static function with(ClockInterface $clock, callable $callback, mixed ...$arguments): mixed
27+
{
28+
$prevClock = self::get($clock);
29+
30+
try {
31+
return $callback(...$arguments);
32+
} finally {
33+
self::get($prevClock);
34+
}
35+
}
36+
37+
/**
38+
* Returns the current clock, or the previous one if a new clock is passed as argument.
39+
*/
40+
public static function get(ClockInterface $newClock = null): ClockInterface
41+
{
42+
static $clock;
43+
44+
if (!$newClock) {
45+
return $clock ??= new NativeClock();
46+
}
47+
48+
$prevClock = $clock ?? new NativeClock();
49+
$clock = $newClock;
50+
51+
return $prevClock;
52+
}
53+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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\Tests;
13+
14+
use PHPUnit\Framework\TestCase;
15+
use Symfony\Component\Clock\Clock;
16+
use Symfony\Component\Clock\MockClock;
17+
use Symfony\Component\Clock\NativeClock;
18+
19+
class ClockTest extends TestCase
20+
{
21+
public function testClock()
22+
{
23+
$this->assertInstanceOf(\DateTimeImmutable::class, Clock::now());
24+
$this->assertInstanceOf(NativeClock::class, Clock::get());
25+
26+
$clock = new MockClock();
27+
28+
$this->assertSame([123, $clock], Clock::with($clock, fn ($arg) => [$arg, Clock::get()], 123));
29+
$this->assertInstanceOf(NativeClock::class, Clock::get());
30+
}
31+
}

0 commit comments

Comments
 (0)