Passed
Push — 2.4 ( e87f45...3cf5b6 )
by René
18:00 queued 11:07
created

CronExpression::validateDate()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 10
nc 6
nop 1
dl 0
loc 21
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
namespace Cron;
4
5
use \DateTime;
0 ignored issues
show
Bug introduced by
The type \DateTime was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use \DateTimeInterface;
0 ignored issues
show
Bug introduced by
The type \DateTimeInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use \DateTimeZone;
0 ignored issues
show
Bug introduced by
The type \DateTimeZone was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use \Exception;
0 ignored issues
show
Bug introduced by
The type \Exception was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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
            $this->registers = $this->parse($expression);
103
        } catch (Exception $e) {
104
            $this->registers = null;
105
        }
106
    }
107
108
    /**
109
     * Whether current cron expression has been parsed successfully
110
     *
111
     * @return bool
112
     */
113
    public function isValid(): bool
114
    {
115
        return null !== $this->registers;
116
    }
117
118
    /**
119
     * 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
            $when = (new DateTime())->setTimestamp($when === null ? time() : $when);
129
        }
130
131
        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 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
     * @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
     * @throws Exception
144
     */
145
    public function getNext($start = null)
146
    {
147
        if ($this->isValid()) {
148
            $next = $this->toDateTime($start);
149
            $pos = sscanf($next->format('i G j n Y w'), '%d %d %d %d %d %d');
150
151
            while ($this->increase($next, $pos)) {
152
                $this->reset($next, $pos);
153
            }
154
155
            return $next->getTimestamp();
156
        }
157
158
        return false;
159
    }
160
161
    /**
162
     * @param mixed $start a DateTime object, a timestamp (int) or "now" if not set
163
     * @return DateTime
164
     */
165
    private function toDateTime($start): DateTime
166
    {
167
        if ($start instanceof DateTimeInterface) {
168
            $next = $start;
169
        } elseif ((int)$start > 0) {
170
            $next = new DateTime('@' . $start);
171
        } else {
172
            $next = new DateTime('@' . time());
173
        }
174
175
        $next->setTimestamp($next->getTimeStamp() - $next->getTimeStamp() % 60);
176
        $next->setTimezone($this->timeZone ?: new DateTimeZone(date_default_timezone_get()));
177
178
        if ($this->isMatching($next)) {
179
            $next->modify('+1 minute');
180
        }
181
182
        return $next;
183
    }
184
185
    /**
186
     * Increases the timestamp in step sizes depending on which segment(s) of the cron pattern are matching.
187
     * Returns FALSE if the cron pattern is matching and thus no further cycle is required.
188
     *
189
     * @param DateTimeInterface $next
190
     * @param array $pos
191
     * @return bool
192
     */
193
    private function increase(DateTimeInterface $next, array $pos): bool
194
    {
195
        if (isset($this->registers[3][$pos[3]]) === false) {
196
            $next->modify('+1 month');
197
            return true;
198
        } elseif (false === (isset($this->registers[2][$pos[2]]) && isset($this->registers[4][$pos[5]]))) {
199
            $next->modify('+1 day');
200
            return true;
201
        } elseif (isset($this->registers[0][$pos[0]]) === false) {
202
            $next->modify('+1 minute');
203
            return true;
204
        } elseif (isset($this->registers[1][$pos[1]]) === false) {
205
            $next->modify('+1 hour');
206
            return true;
207
        }
208
209
        return false;
210
    }
211
212
    /**
213
     * @param DateTimeInterface $next
214
     * @param array $pos
215
     */
216
    private function reset(DateTimeInterface $next, array &$pos): void
217
    {
218
        $current = sscanf($next->format('i G j n Y w'), '%d %d %d %d %d %d');
219
220
        if ($pos[4] !== $current[4]) {
221
            // next year, reset month/day/hour/minute
222
            $next->setTime(0, 0);
223
            $next->setDate($current[4], 1, 1);
224
        } elseif ($pos[3] !== $current[3]) {
225
            // next month, reset day/hour/minute
226
            $next->setTime(0, 0);
227
            $next->setDate($current[4], $current[3], 1);
228
        } elseif ($pos[2] !== $current[2]) {
229
            // next day, reset hour/minute
230
            $next->setTime(0, 0);
231
        }
232
233
        $pos = sscanf($next->format('i G j n Y w'), '%d %d %d %d %d %d');
234
    }
235
236
    /**
237
     * @param array $segments
238
     * @return bool
239
     */
240
    private function match(array $segments): bool
241
    {
242
        foreach ($this->registers as $i => $item) {
243
            if (isset($item[(int)$segments[$i]]) === false) {
244
                return false;
245
            }
246
        }
247
248
        return true;
249
    }
250
251
    /**
252
     * Parse whole cron expression
253
     *
254
     * @param string $expression
255
     * @return array
256
     * @throws Exception
257
     */
258
    private function parse(string $expression): array
259
    {
260
        $segments = preg_split('/\s+/', trim($expression));
261
262
        if (is_array($segments) && sizeof($segments) === 5) {
263
            $registers = array_fill(0, 5, []);
264
265
            foreach ($segments as $index => $segment) {
266
                $this->parseSegment($registers[$index], $index, $segment);
267
            }
268
269
            $this->validateDate($registers);
270
271
            if (isset($registers[4][7])) {
272
                $registers[4][0] = true;
273
            }
274
275
            return $registers;
276
        }
277
278
        throw new Exception('invalid number of segments');
279
    }
280
281
    /**
282
     * Parse one segment of a cron expression
283
     *
284
     * @param array $register
285
     * @param int $index
286
     * @param string $segment
287
     * @throws Exception
288
     */
289
    private function parseSegment(array &$register, int $index, string $segment): void
290
    {
291
        $allowed = [false, false, false, self::MONTH_NAMES, self::WEEKDAY_NAMES];
292
293
        // month names, weekdays
294
        if ($allowed[$index] !== false && isset($allowed[$index][strtolower($segment)])) {
295
            // cannot be used together with lists or ranges
296
            $register[$allowed[$index][strtolower($segment)]] = true;
297
        } else {
298
            // split up current segment into single elements, e.g. "1,5-7,*/2" => [ "1", "5-7", "*/2" ]
299
            foreach (explode(',', $segment) as $element) {
300
                $this->parseElement($register, $index, $element);
301
            }
302
        }
303
    }
304
305
    /**
306
     * @param array $register
307
     * @param int $index
308
     * @param string $element
309
     * @throws Exception
310
     */
311
    private function parseElement(array &$register, int $index, string $element): void
312
    {
313
        $step = 1;
314
        $segments = explode('/', $element);
315
316
        if (sizeof($segments) > 1) {
317
            $this->validateStepping($segments, $index);
318
319
            $element = (string)$segments[0];
320
            $step = (int)$segments[1];
321
        }
322
323
        if (is_numeric($element)) {
324
            $this->validateValue($element, $index, $step);
325
            $register[intval($element)] = true;
326
        } else {
327
            $this->parseRange($register, $index, $element, $step);
328
        }
329
    }
330
331
    /**
332
     * Parse range of values, e.g. "5-10"
333
     *
334
     * @param array $register
335
     * @param int $index
336
     * @param string $range
337
     * @param int $stepping
338
     * @throws Exception
339
     */
340
    private function parseRange(array &$register, int $index, string $range, int $stepping): void
341
    {
342
        if ($range === '*') {
343
            $rangeArr = [self::VALUE_BOUNDARIES[$index]['min'], self::VALUE_BOUNDARIES[$index]['max']];
344
        } else {
345
            $rangeArr = explode('-', $range);
346
        }
347
348
        $this->validateRange($rangeArr, $index);
349
        $this->fillRange($register, $index, $rangeArr, $stepping);
350
    }
351
352
    /**
353
     * @param array $register
354
     * @param int $index
355
     * @param array $range
356
     * @param int $stepping
357
     */
358
    private function fillRange(array &$register, int $index, array $range, int $stepping): void
359
    {
360
        $boundary = self::VALUE_BOUNDARIES[$index]['max'] + self::VALUE_BOUNDARIES[$index]['mod'];
361
        $length = $range[1] - $range[0];
362
363
        if ($range[0] > $range[1]) {
364
            $length += $boundary;
365
        }
366
367
        for ($i = 0; $i <= $length; $i += $stepping) {
368
            $register[($range[0] + $i) % $boundary] = true;
369
        }
370
    }
371
372
    /**
373
     * Validate whether a given range of values exceeds allowed value boundaries
374
     *
375
     * @param array $range
376
     * @param int $index
377
     * @throws Exception
378
     */
379
    private function validateRange(array $range, int $index): void
380
    {
381
        if (sizeof($range) !== 2) {
382
            throw new Exception('invalid range notation');
383
        }
384
385
        foreach ($range as $value) {
386
            $this->validateValue($value, $index);
387
        }
388
    }
389
390
    /**
391
     * @param string $value
392
     * @param int $index
393
     * @param int $step
394
     * @throws Exception
395
     */
396
    private function validateValue(string $value, int $index, int $step = 1): void
397
    {
398
        if ((string)$value !== (string)(int)$value) {
399
            throw new Exception('non-integer value');
400
        }
401
402
        if (intval($value) < self::VALUE_BOUNDARIES[$index]['min'] ||
403
            intval($value) > self::VALUE_BOUNDARIES[$index]['max']
404
        ) {
405
            throw new Exception('value out of boundary');
406
        }
407
408
        if ($step !== 1) {
409
            throw new Exception('invalid combination of value and stepping notation');
410
        }
411
    }
412
413
    /**
414
     * @param array $segments
415
     * @param int $index
416
     * @throws Exception
417
     */
418
    private function validateStepping(array $segments, int $index): void
419
    {
420
        if (sizeof($segments) !== 2) {
421
            throw new Exception('invalid stepping notation');
422
        }
423
424
        if ((int)$segments[1] < 1 || (int)$segments[1] > self::VALUE_BOUNDARIES[$index]['max']) {
425
            throw new Exception('stepping out of allowed range');
426
        }
427
    }
428
429
    /**
430
     * @param array $segments
431
     * @throws Exception
432
     */
433
    private function validateDate(array $segments): void
434
    {
435
        $year = date('Y');
436
437
        for ($y = 0; $y < 27; $y++) {
438
            foreach (array_keys($segments[3]) as $month) {
439
                foreach (array_keys($segments[2]) as $day) {
440
                    if (false === checkdate($month, $day, $year + $y)) {
441
                        continue;
442
                    }
443
444
                    if (isset($segments[date('w', strtotime(sprintf('%d-%d-%d', $year + $y, $month, $day)))])) {
445
                        continue;
446
                    }
447
448
                    return;
449
                }
450
            }
451
        }
452
453
        throw new Exception('no date ever can match the given combination of day/month/weekday');
454
    }
455
}
456