Skip to content

Commit dc8a762

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

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
}
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy