8000 [Clock] Add ClockAwareTrait to help write time-sensitive classes · symfony/symfony@b1a36b0 · GitHub
[go: up one dir, main page]

Skip to content

Commit b1a36b0

Browse files
[Clock] Add ClockAwareTrait to help write time-sensitive classes
1 parent a97d79a commit b1a36b0

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
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 <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 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 ($this->clock ??= new NativeClock())->now();
34+
}
35+
36+
protected function sleep(float|int $seconds): void
37+
{
38+
($this->clock ??= new NativeClock())->sleep($seconds);
39+
}
40+
}
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 <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+
}

0 commit comments

Comments
 (0)
0