-
Notifications
You must be signed in to change notification settings - Fork 91
/
CronTimeResolver.php
80 lines (69 loc) · 2.31 KB
/
CronTimeResolver.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
<?php
declare(strict_types=1);
namespace Shopsys\FrameworkBundle\Component\Cron;
use DateTimeInterface;
use Shopsys\FrameworkBundle\Component\Cron\Config\Exception\InvalidTimeFormatException;
class CronTimeResolver
{
/**
* @param \Shopsys\FrameworkBundle\Component\Cron\CronTimeInterface $cronTime
* @param \DateTimeInterface $dateTime
* @return bool
*/
public function isValidAtTime(CronTimeInterface $cronTime, DateTimeInterface $dateTime): bool
{
$hour = (int)$dateTime->format('G');
$minute = (int)$dateTime->format('i');
return $this->isMatchWithTimeString($hour, $cronTime->getTimeHours()) &&
$this->isMatchWithTimeString($minute, $cronTime->getTimeMinutes());
}
/**
* @param int $value
* @param string $timeString
* @return bool
*/
protected function isMatchWithTimeString(int $value, string $timeString): bool
{
$timeValues = explode(',', $timeString);
$matches = null;
foreach ($timeValues as $timeValue) {
if (
$timeValue === '*'
|| $timeValue === str_pad((string)$value, strlen($timeValue), '0', STR_PAD_LEFT)
|| preg_match('@^\*/(\d+)$@', $timeValue, $matches)
&& $value % $matches[1] === 0 // syntax */[int]
) {
return true;
}
}
return false;
}
/**
* @param string $timeString
* @param int $maxValue
* @param int $divisibleBy
*/
public function validateTimeString(string $timeString, int $maxValue, int $divisibleBy): void
{
$timeValues = explode(',', $timeString);
$matches = null;
foreach ($timeValues as $timeValue) {
// syntax */[int]
if (preg_match('@^\*/(\d+)$@', $timeValue, $matches)) {
$timeNumber = $matches[1];
} else {
$timeNumber = $timeValue;
}
if (
$timeNumber !== '*'
&& !(
is_numeric($timeNumber)
&& $timeNumber <= $maxValue
&& $timeNumber % $divisibleBy === 0
)
) {
throw new InvalidTimeFormatException($timeValue, $maxValue, $divisibleBy);
}
}
}
}