Skip to content

Commit be99e56

Browse files
[Clock] Add Clock::now()
1 parent bd6219d commit be99e56

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-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()` and `Clock::clock()`
89

910
6.2
1011
---

src/Symfony/Component/Clock/Clock.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
/**
27+
* Returns the current clock, or the previous one when passing a new clock as argument.
28+
*/
29+
public static function get(ClockInterface $newClock = null): ClockInterface
30+
{
31+
static $clock;
32+
33+
if (null === $newClock) {
34+
return $clock ??= new NativeClock();
35+
}
36+
37+
$previousClock = $clock ?? new NativeClock();
38+
$clock = $newClock;
39+
40+
return $previousClock;
41+
}
42+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
25+
$previousClock = Clock::get();
26+
$this->assertInstanceOf(NativeClock::class, $previousClock);
27+
28+
$newClock = new MockClock();
29+
$this->assertSame($previousClock, Clock::get($newClock));
30+
$this->assertSame($newClock, Clock::get());
31+
}
32+
}

0 commit comments

Comments
 (0)