File tree Expand file tree Collapse file tree 3 files changed +75
-0
lines changed
src/Symfony/Component/Clock Expand file tree Collapse file tree 3 files changed +75
-0
lines changed Original file line number Diff line number Diff 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
9106.2
1011---
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments