Passed
Branch master (53b6fb)
by René
06:56
created

CronExpression::isValid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Poliander\Cron;
4
5
use \DateTime;
6
use \DateTimeInterface;
7
use \DateTimeZone;
8
use \Exception;
9
10
/**
11
 * Cron expression parser and validator
12
 *
13
 * @author René Pollesch
14
 */
15
class CronExpression
16
{
17
    /**
18
     * Weekday name look-up table
19
     */
20
    private const WEEKDAY_NAMES = [
21
        'sun' => 0,
22
        'mon' => 1,
23
        'tue' => 2,
24
        'wed' => 3,
25
        'thu' => 4,
26
        'fri' => 5,
27
        'sat' => 6
28
    ];
29
30
    /**
31
     * Month name look-up table
32
     */
33
    private const MONTH_NAMES = [
34
        'jan' => 1,
35
        'feb' => 2,
36
        'mar' => 3,
37
        'apr' => 4,
38
        'may' => 5,
39
        'jun' => 6,
40
        'jul' => 7,
41
        'aug' => 8,
42
        'sep' => 9,
43
        'oct' => 10,
44
        'nov' => 11,
45
        'dec' => 12
46
    ];
47
48
    /**
49
     * Value boundaries
50
     */
51
    private const VALUE_BOUNDARIES = [
52
        0 => [
53
            'min' => 0,
54
            'max' => 59,
55
            'mod' => 1
56
        ],
57
        1 => [
58
            'min' => 0,
59
            'max' => 23,
60
            'mod' => 1
61
        ],
62
        2 => [
63
            'min' => 1,
64
            'max' => 31,
65
            'mod' => 1
66
        ],
67
        3 => [
68
            'min' => 1,
69
            'max' => 12,
70
            'mod' => 1
71
        ],
72
        4 => [
73
            'min' => 0,
74
            'max' => 7,
75
            'mod' => 0
76
        ]
77
    ];
78
79
    /**
80
     * Time zone
81
     *
82
     * @var DateTimeZone|null
83
     */
84
    protected $timeZone = null;
85
86
    /**
87
     * Matching registers
88
     *
89
     * @var array|null
90
     */
91
    protected $registers = null;
92
93
    /**
94
     * @param string $expression a cron expression, e.g. "* * * * *"
95
     * @param DateTimeZone|null $timeZone time zone object
96
     */
97
    public function __construct(string $expression, DateTimeZone $timeZone = null)
98
    {
99
        $this->timeZone = $timeZone;
100
101
        try {
102 93
            $this->registers = $this->parse($expression);
103
        } catch (Exception $e) {
104 93
            $this->registers = null;
105 93
        }
106 93
    }
107
108
    /**
109
     * Whether current cron expression has been parsed successfully
110
     *
111
     * @return bool
112
     */
113
    public function isValid(): bool
114 93
    {
115
        return null !== $this->registers;
116 93
    }
117 93
118
    /**
119 93
     * Match either "now", a given date/time object or a timestamp against current cron expression
120
     *
121
     * @param mixed $when a DateTime object, a timestamp (int), or "now" if not set
122
     * @return bool
123
     * @throws Exception
124
     */
125
    public function isMatching($when = null): bool
126
    {
127
        if (false === ($when instanceof DateTimeInterface)) {
128 93
            $when = (new DateTime())->setTimestamp($when === null ? time() : $when);
129
        }
130 93
131 93
        if ($this->timeZone !== null) {
132
            $when->setTimezone($this->timeZone);
133
        }
134
135
        return $this->isValid() && $this->match(sscanf($when->format('i G j n w'), '%d %d %d %d %d'));
0 ignored issues
show
Bug introduced by
It seems like sscanf($when->format('i ... w'), '%d %d %d %d %d') can also be of type integer and null; however, parameter $segments of Poliander\Cron\CronExpression::match() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

135
        return $this->isValid() && $this->match(/** @scrutinizer ignore-type */ sscanf($when->format('i G j n w'), '%d %d %d %d %d'));
Loading history...
136
    }
137
138
    /**
139
     * Calculate next matching timestamp
140
     *
141 11
     * @param mixed $start a DateTime object, a timestamp (int) or "now" if not set
142
     * @return int|bool next matching timestamp, or false on error
143 11
     * @throws Exception
144
     */
145 11
    public function getNext($start = null)
146 11
    {
147 1
        if ($this->isValid()) {
148 10
            $now = $this->toDateTime($start);
149 9
            $now->setTimezone($this->timeZone ?: new DateTimeZone(date_default_timezone_get()));
150
151 1
            $pointer = sscanf($now->format('i G j n Y'), '%d %d %d %d %d');
152
153
            do {
154 11
                $current = $this->adjust($now, $pointer);
155 11
            } while ($this->forward($now, $current));
156
157 11
            return $now->getTimestamp();
158 4
        }
159
160
        return false;
161 11
    }
162
163
    /**
164 11
     * @param mixed $start a DateTime object, a timestamp (int) or "now" if not set
165 11
     * @return DateTime
166
     */
167 11
    private function toDateTime($start): DateTime
168
    {
169
        if ($start instanceof DateTimeInterface) {
170 11
            $now = $start;
171
        } elseif ((int)$start > 0) {
172
            $now = new DateTime('@' . $start);
173
        } else {
174
            $now = new DateTime('@' . time());
175
        }
176
177
        $now->setTimestamp($now->getTimeStamp() - $now->getTimeStamp() % 60);
178 11
179
        if ($this->isMatching($now)) {
180 11
            $now->modify('+1 minute');
181
        }
182
183 11
        return $now;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $now could return the type DateTimeInterface which includes types incompatible with the type-hinted return DateTime. Consider adding an additional type-check to rule them out.
Loading history...
184 6
    }
185 6
186 6
    /**
187
     * @param DateTimeInterface $now
188 11
     * @param array $pointer
189 9
     * @return array
190 9
     */
191 9
    private function adjust(DateTimeInterface $now, array &$pointer): array
192
    {
193 11
        $current = sscanf($now->format('i G j n Y w'), '%d %d %d %d %d %d');
194 1
195 1
        if ($pointer[0] !== $current[0] || $pointer[1] !== $current[1]) {
196 1
            $pointer[0] = $current[0];
197 1
            $now->setTime($current[1], $current[0]);
198
        } elseif ($pointer[4] !== $current[4]) {
199 11
            $pointer[4] = $current[4];
200 2
            $now->setDate($current[4], 1, 1);
201 2
            $now->setTime(0, 0);
202 2
        } elseif ($pointer[3] !== $current[3]) {
203 2
            $pointer[3] = $current[3];
204
            $now->setDate($current[4], $current[3], 1);
205 11
            $now->setTime(0, 0);
206 2
        } elseif ($pointer[2] !== $current[2]) {
207 2
            $pointer[2] = $current[2];
208 2
            $now->setTime(0, 0);
209
        }
210
211 11
        return $current;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $current could return the type integer|null which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
212
    }
213
214
    /**
215
     * @param DateTimeInterface $now
216
     * @param array $current
217
     * @return bool
218
     */
219 11
    private function forward(DateTimeInterface $now, array $current): bool
220
    {
221 11
        if (isset($this->registers[3][$current[3]]) === false) {
222
            $now->modify('+1 month');
223 11
            return true;
224 1
        } elseif (false === (isset($this->registers[2][$current[2]]) && isset($this->registers[4][$current[5]]))) {
225 1
            $now->modify('+1 day');
226 11
            return true;
227 2
        } elseif (isset($this->registers[0][$current[0]]) === false) {
228 2
            $now->modify('+1 minute');
229 11
            return true;
230 4
        } elseif (isset($this->registers[1][$current[1]]) === false) {
231 4
            $now->modify('+1 hour');
232 11
            return true;
233 8
        }
234 8
235
        return false;
236
    }
237 11
238
    /**
239
     * @param array $segments
240
     * @return bool
241
     */
242
    private function match(array $segments): bool
243
    {
244
        $result = true;
245 92
246
        foreach ($this->registers as $i => $item) {
247 92
            if (isset($item[(int)$segments[$i]]) === false) {
248
                $result = false;
249 92
                break;
250
            }
251 92
        }
252 27
253 27
        return $result;
254
    }
255
256
    /**
257 92
     * Parse whole cron expression
258
     *
259
     * @param string $expression
260
     * @return array
261
     * @throws Exception
262
     */
263
    private function parse(string $expression): array
264
    {
265
        $segments = preg_split('/\s+/', trim($expression));
266
267 93
        if (is_array($segments) && sizeof($segments) === 5) {
268
            $registers = array_fill(0, 5, []);
269 93
270 81
            foreach ($segments as $index => $segment) {
271
                $this->parseSegment($registers[$index], $index, $segment);
272
            }
273 93
274 91
            if (isset($registers[4][7])) {
275
                $registers[4][0] = true;
276
            }
277
278 93
            return $registers;
279 27
        }
280 27
281
        throw new Exception('invalid number of segments');
282
    }
283 93
284
    /**
285
     * Parse one segment of a cron expression
286
     *
287
     * @param array $register
288
     * @param int $index
289
     * @param string $segment
290
     * @throws Exception
291 93
     */
292
    private function parseSegment(array &$register, $index, $segment): void
293 93
    {
294
        $allowed = [false, false, false, self::MONTH_NAMES, self::WEEKDAY_NAMES];
295 93
296 66
        // month names, weekdays
297 32
        if ($allowed[$index] !== false && isset($allowed[$index][strtolower($segment)])) {
298 66
            // cannot be used together with lists or ranges
299
            $register[$allowed[$index][strtolower($segment)]] = true;
300
        } else {
301
            // split up current segment into single elements, e.g. "1,5-7,*/2" => [ "1", "5-7", "*/2" ]
302 66
            foreach (explode(',', $segment) as $element) {
303
                $this->parseElement($register, $index, $element);
304
            }
305
        }
306
    }
307
308
    /**
309
     * @param array $register
310
     * @param int $index
311 93
     * @param string $element
312
     * @throws Exception
313 93
     */
314
    private function parseElement(array &$register, int $index, string $element): void
315 93
    {
316 89
        $step = 1;
317 89
        $segments = explode('/', $element);
318
319
        if (sizeof($segments) > 1) {
320 66
            $this->validateStepping($segments, $index);
321 66
322
            $element = (string)$segments[0];
323
            $step = (int)$segments[1];
324 4
        }
325
326
        if (is_numeric($element)) {
327 66
            $this->validateValue($element, $index, $step);
328
            $register[intval($element)] = true;
329
        } else {
330
            $this->parseRange($register, $index, $element, $step);
331
        }
332
    }
333
334
    /**
335
     * Parse range of values, e.g. "5-10"
336
     *
337
     * @param array $register
338 89
     * @param int $index
339
     * @param string $range
340 89
     * @param int $stepping
341
     * @throws Exception
342
     */
343 89
    private function parseRange(array &$register, int $index, string $range, int $stepping): void
344
    {
345 5
        if ($range === '*') {
346
            $range = [self::VALUE_BOUNDARIES[$index]['min'], self::VALUE_BOUNDARIES[$index]['max']];
347
        } else {
348 89
            $range = explode('-', $range);
349 89
        }
350
351
        $this->validateRange($range, $index);
352 77
        $this->fillRange($register, $index, $range, $stepping);
353
    }
354
355
    /**
356
     * @param array $register
357
     * @param int $index
358
     * @param array $range
359
     * @param int $stepping
360 89
     */
361
    private function fillRange(array &$register, int $index, array $range, int $stepping): void
362 89
    {
363
        $boundary = self::VALUE_BOUNDARIES[$index]['max'] + self::VALUE_BOUNDARIES[$index]['mod'];
364 89
        $length = $range[1] - $range[0];
365 42
366
        if ($range[0] > $range[1]) {
367
            $length += $boundary;
368 86
        }
369 35
370
        for ($i = 0; $i <= $length; $i += $stepping) {
371 29
            $register[($range[0] + $i) % $boundary] = true;
372 1
        }
373
    }
374
375 28
    /**
376
     * Validate whether a given range of values exceeds allowed value boundaries
377 82
     *
378
     * @param array $range
379 78
     * @param int $index
380
     * @throws Exception
381
     */
382
    private function validateRange(array $range, int $index): void
383
    {
384
        if (sizeof($range) !== 2) {
385
            throw new Exception('invalid range notation');
386
        }
387
388
        foreach ($range as $value) {
389
            $this->validateValue($value, $index);
390 82
        }
391
    }
392 82
393 75
    /**
394 51
     * @param string $value
395 44
     * @param int $index
396
     * @param int $step
397 8
     * @throws Exception
398
     */
399
    private function validateValue(string $value, int $index, int $step = 1): void
400 77
    {
401 77
        if ((string)$value !== (string)(int)$value) {
402
            throw new Exception('non-integer value');
403
        }
404
405
        if (intval($value) < self::VALUE_BOUNDARIES[$index]['min'] ||
406
            intval($value) > self::VALUE_BOUNDARIES[$index]['max']
407
        ) {
408
            throw new Exception('value out of boundary');
409
        }
410
411 42
        if ($step !== 1) {
412
            throw new Exception('invalid combination of value and stepping notation');
413 42
        }
414
    }
415 42
416
    /**
417 38
     * @param array $segments
418 38
     * @param int $index
419 38
     * @throws Exception
420
     */
421
    private function validateStepping(array $segments, int $index): void
422
    {
423
        if (sizeof($segments) !== 2) {
424
            throw new Exception('invalid stepping notation');
425
        }
426
427
        if ((int)$segments[1] < 1 || (int)$segments[1] > self::VALUE_BOUNDARIES[$index]['max']) {
428
            throw new Exception('stepping out of allowed range');
429 44
        }
430
    }
431
}
432