-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFixedClock.php
75 lines (64 loc) · 1.74 KB
/
FixedClock.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\Clock;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
use Psr\Clock\ClockInterface;
use SonsOfPHP\Component\Clock\Exception\ClockException;
use Stringable;
/**
* Fixed Clock.
*
* The test clock is used for testing purposes. It freezes time in place and has the ability
* to update or set the time to whatever you want.
*
* @author Joshua Estes <[email protected]>
*/
final class FixedClock implements ClockInterface, Stringable
{
private DateTimeInterface $time;
public function __construct(
private readonly DateTimeZone $zone = new DateTimeZone('UTC'),
) {
$this->tick();
}
public function __toString(): string
{
return 'FixedClock[' . $this->zone->getName() . ']';
}
public function now(): DateTimeImmutable
{
return $this->time;
}
public function getZone(): DateTimeZone
{
return $this->zone;
}
/**
* Updates the current clock time to be when the tick happened.
*/
public function tick(): void
{
$this->time = new DateTimeImmutable('now', $this->zone);
}
/**
* Updates the clock to a specific date and time that can be in the past or
* in the future.
*
* Input should match the format: YYYY-MM-DD HH:MM:SS
*
* Example:
* $clock->tickTo('2022-04-20 04:20:00');
*
* @throws ClockException
*/
public function tickTo(string $input): void
{
$time = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $input, $this->zone);
if (false === $time) {
throw new ClockException(sprintf('The input "%s" is invalid', $input));
}
$this->time = $time;
}
}