-
Notifications
You must be signed in to change notification settings - Fork 4
/
Clock.php
100 lines (88 loc) · 2.9 KB
/
Clock.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
/**
* @author: Julien Mercier-Rojas <julien@jeckel-lab.fr>
* Created at: 25/03/2021
*/
declare(strict_types=1);
namespace JeckelLab\Clock\CodeceptionHelper;
use Codeception\Configuration;
use Codeception\Module;
use Codeception\TestInterface;
use Codeception\Util\Fixtures;
use DateTimeImmutable;
use DateTimeInterface;
use InvalidArgumentException;
use RuntimeException;
/**
* Class Clock
* @package JeckelLab\Clock\CodeceptionHelper
*/
class Clock extends Module
{
public const FIXTURE_CURRENT_DATETIME = '_clock_current_datetime';
/**
* @var string[]
* @psalm-suppress NonInvariantDocblockPropertyType
*/
protected $config = [
'date_format' => 'Y/m/d',
'time_format' => 'H:i:s'
];
/**
* @var array
* @psalm-suppress NonInvariantDocblockPropertyType
*/
protected $requiredFields = ['fake_time_path', 'date_format', 'time_format'];
// @codingStandardsIgnoreStart
/**
* HOOK: before test
* @param TestInterface $test
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function _before(TestInterface $test): void
{
$this->haveCurrentDateTime(new DateTimeImmutable());
Fixtures::cleanup(self::FIXTURE_CURRENT_DATETIME);
}
// @codingStandardsIgnoreEnd
/**
* @Given current date is :currentDate and time is :currentTime
* @param string $date
* @param string $time
*/
public function haveCurrentDateAndTime(string $date, string $time): void
{
$format = sprintf('%s %s', $this->config['date_format'], $this->config['time_format']);
$currentDate = DateTimeImmutable::createFromFormat($format, sprintf('%s %s', $date, $time));
if (false === $currentDate) {
throw new InvalidArgumentException('Invalid date / time format');
}
$this->haveCurrentDateTime($currentDate);
}
/**
* @param DateTimeImmutable $dateTime
*/
public function haveCurrentDateTime(DateTimeImmutable $dateTime): void
{
$fullPath = Configuration::projectDir() . $this->config['fake_time_path'];
$dir = dirname($fullPath);
if (!is_dir($dir) && !mkdir($dir) && !is_dir($dir)) {
throw new RuntimeException(sprintf('Directory "%s" was not created', $dir));
}
file_put_contents($fullPath, $dateTime->format('Y-m-d H:i:s'));
$this->debug(sprintf('[Date] Set fake time %s in file %s', $dateTime->format('Y-m-d H:i:s'), $fullPath));
Fixtures::add(self::FIXTURE_CURRENT_DATETIME, $dateTime);
}
/**
* @return DateTimeImmutable|null
*/
public function getDefinedCurrentDateTime(): ?DateTimeImmutable
{
if (Fixtures::exists(self::FIXTURE_CURRENT_DATETIME)) {
/** @var DateTimeImmutable $dateTime */
$dateTime = Fixtures::get(self::FIXTURE_CURRENT_DATETIME);
return $dateTime;
}
return null;
}
}