File tree Expand file tree Collapse file tree 3 files changed +81
-0
lines changed
src/Symfony/Component/Clock Expand file tree Collapse file tree 3 files changed +81
-0
lines changed Original file line number Diff line number Diff line change 1
1
CHANGELOG
2
2
=========
3
3
4
+ 6.3
5
+ ---
6
+
7
+ * Add ` ClockAwareTrait ` to help write time-sensitive classes
8
+
4
9
6.2
5
10
---
6
11
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
+ use Psr \Clock \ClockInterface ;
15
+ use Symfony \Contracts \Service \Attribute \Required ;
16
+
17
+ /**
18
+ * A trait to help write time-sensitive classes.
19
+ *
20
+ * @author Nicolas Grekas <p@tchwork.com>
21
+ */
22
+ trait ClockAwareTrait
23
+ {
24
+ private readonly ClockInterface $ clock ;
25
+
26
+ #[Required]
27
+ public function setClock (ClockInterface $ clock ): void
28
+ {
29
+ $ this ->clock = $ clock ;
30
+ }
31
+
32
+ protected function now (): \DateTimeImmutable
33
+ {
34
+ return ($ this ->clock ??= new NativeClock ())->now ();
35
+ }
36
+ }
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 \ClockAwareTrait ;
16
+ use Symfony \Component \Clock \MockClock ;
17
+
18
+ class ClockAwareTraitTest extends TestCase
19
+ {
20
+ public function testTrait ()
21
+ {
22
+ $ sut = new class () {
23
+ use ClockAwareTrait {
24
+ now as public ;
25
+ }
26
+ };
27
+
28
+ $ this ->assertInstanceOf (\DateTimeImmutable::class, $ sut ->now ());
29
+
30
+ $ clock = new MockClock ();
31
+ $ sut = new $ sut ;
32
+ $ sut ->setClock ($ clock );
33
+
34
+ $ ts = $ sut ->now ()->getTimestamp ();
35
+ $ this ->assertEquals ($ clock ->now (), $ sut ->now ());
36
+ $ clock ->sleep (1 );
37
+ $ this ->assertEquals ($ clock ->now (), $ sut ->now ());
38
+ $ this ->assertSame (1.0 , round ($ sut ->now ()->getTimestamp () - $ ts , 1 ));
39
+ }
40
+ }
You can’t perform that action at this time.
0 commit comments