File tree Expand file tree Collapse file tree 2 files changed +84
-0
lines changed
src/Symfony/Component/Clock Expand file tree Collapse file tree 2 files changed +84
-0
lines changed 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 Symfony \Contracts \Service \Attribute \Required ;
15+
16+ /**
17+ * A trait to help write time-sensitive classes.
18+ *
19+ * @author Nicolas Grekas <p@tchwork.com>
20+ */
21+ trait ClockAwareTrait
22+ {
23+ protected readonly ClockInterface $ clock ;
24+
25+ #[Required]
26+ public function setClock (ClockInterface $ clock ): void
27+ {
28+ $ this ->clock = $ clock ;
29+ }
30+
31+ protected function now (): \DateTimeImmutable
32+ {
33+ return isset ($ this ->clock ) ? $ this ->clock ->now () : new \DateTimeImmutable ();
34+ }
35+
36+ protected function sleep (float |int $ seconds ): void
37+ {
38+ if (isset ($ this ->clock )) {
39+ $ this ->clock ->sleep ($ seconds );
40+ } else {
41+ usleep ($ seconds * 1E6 );
42+ }
43+ }
44+ }
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+ sleep as public ;
26+ }
27+ };
28+
29+ $ this ->assertInstanceOf (\DateTimeImmutable::class, $ sut ->now ());
30+
31+ $ clock = new MockClock ();
32+ $ sut ->setClock ($ clock );
33+
34+ $ ts = $ sut ->now ()->getTimestamp ();
35+ $ this ->assertEquals ($ clock ->now (), $ sut ->now ());
36+ $ sut ->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