Skip to content

Commit 3c4e92c

Browse files
[Clock] Add ClockAwareTrait to help write time-sensitive classes
1 parent 384840c commit 3c4e92c

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
6.3
5+
---
6+
7+
* Add `ClockAwareTrait` to help write time-sensitive classes
8+
49
6.2
510
---
611

ClockAwareTrait.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
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 <[email protected]>
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+
}

Tests/ClockAwareTraitTest.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
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+
}

0 commit comments

Comments
 (0)