-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathFrozenClock.php
More file actions
84 lines (71 loc) · 2.23 KB
/
FrozenClock.php
File metadata and controls
84 lines (71 loc) · 2.23 KB
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
76
77
78
79
80
81
82
83
84
<?php
/**
* @author: Julien Mercier-Rojas <julien@jeckel-lab.fr>
* Created at: 19/04/2019
*/
declare(strict_types=1);
namespace JeckelLab\Clock\Clock;
use DateTimeImmutable;
use DateTimeZone;
use JeckelLab\Clock\Exception\InvalidFakeClockInitialValueException;
use JeckelLab\Clock\Exception\RuntimeException;
use JeckelLab\Contract\Infrastructure\System\Clock as ClockInterface;
/**
* Class FakeClock
* @package Jeckel\Clock
*/
class FrozenClock implements ClockInterface
{
protected DateTimeImmutable $now;
private DateTimeZone $timezone;
/**
* FakeClock constructor.
* @param DateTimeImmutable $initialDatetime
* @param DateTimeZone|null $timezone
*/
public function __construct(DateTimeImmutable $initialDatetime, ?DateTimeZone $timezone = null)
{
$this->timezone = $timezone ?: $initialDatetime->getTimezone();
if ($initialDatetime->getTimezone()->getName() !== $this->timezone->getName()) {
$fixedDateTime = $initialDatetime->setTimezone($this->timezone);
// @codeCoverageIgnoreStart
if (! $fixedDateTime instanceof DateTimeImmutable) {
throw new RuntimeException('Error setting timezone');
}
// @codeCoverageIgnoreEnd
$initialDatetime = $fixedDateTime;
}
$this->now = $initialDatetime;
}
/**
* @param DateTimeImmutable $now
*/
public function setClock(DateTimeImmutable $now): void
{
$newNow = DateTimeImmutable::createFromFormat('U', $now->format('U'));
// @codeCoverageIgnoreStart
if (! $newNow instanceof DateTimeImmutable) {
throw new RuntimeException('Error creating new date');
}
// @codeCoverageIgnoreEnd
$this->now = $newNow->setTimezone($this->timezone);
}
/**
* @param DateTimeZone|null $timezone
* @return DateTimeImmutable
*/
public function now(?DateTimeZone $timezone = null): DateTimeImmutable
{
if (null !== $timezone) {
return $this->now->setTimezone($timezone);
}
return $this->now;
}
/**
* @return DateTimeZone
*/
public function getTimeZone(): DateTimeZone
{
return $this->timezone;
}
}