-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProgressingFixedClock.php
63 lines (52 loc) · 1.33 KB
/
ProgressingFixedClock.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
<?php
declare(strict_types=1);
namespace Bag2\Clock;
use DateInterval;
use DateTimeImmutable;
use Psr\Clock\ClockInterface;
use function time;
/**
* A clock class that returns the time progressed in real time from a fixed time for testing.
*
* @template T of DateTimeImmutable
*/
class ProgressingFixedClock implements ClockInterface
{
/**
* @var DateTimeImmutable
* @phpstan-var T
*/
private $datetime;
/** @var int */
private $origin_sec;
/**
* @phpstan-param T $datetime
* @param int $sec A return value of {@see time()} function.
*/
protected function __construct(DateTimeImmutable $datetime, int $sec)
{
$this->datetime = $datetime;
$this->origin_sec = $sec;
}
/**
* @phpstan-param T $datetime
* @param int $sec A return value of {@see time()} function.
* @return self<T>
*/
public static function fromTime(DateTimeImmutable $datetime, int $sec): self
{
return new self($datetime, $sec);
}
/**
* @phpstan-return T
*/
public function now(): DateTimeImmutable
{
$now_sec = time();
if ($this->origin_sec === $now_sec) {
return $this->datetime;
}
$diff = $now_sec - $this->origin_sec;
return $this->datetime->add(new DateInterval("PT{$diff}S"));
}
}