Passed
Push — main ( 9dc448...6eb0b1 )
by René
02:04
created

CronExpression::forward()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
eloc 13
c 1
b 1
f 0
nc 5
nop 2
dl 0
loc 17
ccs 14
cts 14
cp 1
crap 6
rs 9.2222
1
<?php
2
3
namespace Poliander\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 112
    public function __construct(string $expression, DateTimeZone $timeZone = null)
98
    {
99 112
        $this->timeZone = $timeZone;
100
101
        try {
102 112
            $this->registers = $this->parse($expression);
103 27
        } catch (Exception $e) {
104 27
            $this->registers = null;
105
        }
106
    }
107
108
    /**
109
     * Whether current cron expression has been parsed successfully
110
     *
111
     * @return bool
112
     */
113 112
    public function isValid(): bool
114
    {
115 112
        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 112
    public function isMatching($when = null): bool
126
    {
127 112
        if (false === ($when instanceof DateTimeInterface)) {
128 94
            $when = (new DateTime())->setTimestamp($when === null ? time() : $when);
129
        }
130
131 112
        if ($this->timeZone !== null) {
132 110
            $when->setTimezone($this->timeZone);
133
        }
134
135 112
        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
     * @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 17
    public function getNext($start = null)
146
    {
147 17
        if ($this->isValid()) {
148 17
            $now = $this->toDateTime($start);
149 17
            $pos = sscanf($now->format('i G j n Y'), '%d %d %d %d %d');
150
151
            do {
152 17
                $this->adjust($now, $pos);
153 17
            } while ($this->forward($now, $pos));
154
155 17
            return $now->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 17
    private function toDateTime($start): DateTime
166
    {
167 17
        if ($start instanceof DateTimeInterface) {
168 1
            $now = $start;
169 16
        } elseif ((int)$start > 0) {
170 15
            $now = new DateTime('@' . $start);
171
        } else {
172 1
            $now = new DateTime('@' . time());
173
        }
174
175 17
        $now->setTimestamp($now->getTimeStamp() - $now->getTimeStamp() % 60);
176 17
        $now->setTimezone($this->timeZone ?: new DateTimeZone(date_default_timezone_get()));
177
178 17
        if ($this->isMatching($now)) {
179 5
            $now->modify('+1 minute');
180
        }
181
182 17
        return $now;
183
    }
184
185
    /**
186
     * @param DateTimeInterface $now
187
     * @param array $pos
188
     */
189 17
    private function adjust(DateTimeInterface $now, array &$pos): void
190
    {
191 17
        $current = sscanf($now->format('i G j n Y w'), '%d %d %d %d %d %d');
192
193 17
        if ($pos[0] !== $current[0] || $pos[1] !== $current[1]) {
194 12
            $now->setTime($current[1], $current[0]);
195 17
        } elseif ($pos[2] !== $current[2]) {
196
            // next day, reset hour/minute
197 2
            $now->setTime(0, 0);
198 17
        } elseif ($pos[3] !== $current[3]) {
199
            // next month, reset day/hour/minute
200 3
            $now->setTime(0, 0);
201 3
            $now->setDate($current[4], $current[3], 1);
202 17
        } elseif ($pos[4] !== $current[4]) {
203
            // next year, reset month/day/hour/minute
204
            $now->setTime(0, 0);
205
            $now->setDate($current[4], 1, 1);
206
        }
207
208 17
        $pos = sscanf($now->format('i G j n Y w'), '%d %d %d %d %d %d');
209
    }
210
211
    /**
212
     * @param DateTimeInterface $now
213
     * @param array $current
214
     * @return bool
215
     */
216 17
    private function forward(DateTimeInterface $now, array $current): bool
217
    {
218 17
        if (isset($this->registers[3][$current[3]]) === false) {
219 3
            $now->modify('+1 month');
220 3
            return true;
221 17
        } elseif (false === (isset($this->registers[2][$current[2]]) && isset($this->registers[4][$current[5]]))) {
222 2
            $now->modify('+1 day');
223 2
            return true;
224 17
        } elseif (isset($this->registers[0][$current[0]]) === false) {
225 11
            $now->modify('+1 minute');
226 11
            return true;
227 17
        } elseif (isset($this->registers[1][$current[1]]) === false) {
228 7
            $now->modify('+1 hour');
229 7
            return true;
230
        }
231
232 17
        return false;
233
    }
234
235
    /**
236
     * @param array $segments
237
     * @return bool
238
     */
239 85
    private function match(array $segments): bool
240
    {
241 85
        $result = true;
242
243 85
        foreach ($this->registers as $i => $item) {
244 85
            if (isset($item[(int)$segments[$i]]) === false) {
245 43
                $result = false;
246 43
                break;
247
            }
248
        }
249
250 85
        return $result;
251
    }
252
253
    /**
254
     * Parse whole cron expression
255
     *
256
     * @param string $expression
257
     * @return array
258
     * @throws Exception
259
     */
260 112
    private function parse(string $expression): array
261
    {
262 112
        $segments = preg_split('/\s+/', trim($expression));
263
264 112
        if (is_array($segments) && sizeof($segments) === 5) {
265 108
            $registers = array_fill(0, 5, []);
266
267 108
            foreach ($segments as $index => $segment) {
268 108
                $this->parseSegment($registers[$index], $index, $segment);
269
            }
270
271 85
            if (isset($registers[4][7])) {
272 2
                $registers[4][0] = true;
273
            }
274
275 85
            return $registers;
276
        }
277
278 4
        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 108
    private function parseSegment(array &$register, $index, $segment): void
290
    {
291 108
        $allowed = [false, false, false, self::MONTH_NAMES, self::WEEKDAY_NAMES];
292
293
        // month names, weekdays
294 108
        if ($allowed[$index] !== false && isset($allowed[$index][strtolower($segment)])) {
295
            // cannot be used together with lists or ranges
296 5
            $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 108
            foreach (explode(',', $segment) as $element) {
300 108
                $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 108
    private function parseElement(array &$register, int $index, string $element): void
312
    {
313 108
        $step = 1;
314 108
        $segments = explode('/', $element);
315
316 108
        if (sizeof($segments) > 1) {
317 55
            $this->validateStepping($segments, $index);
318
319 51
            $element = (string)$segments[0];
320 51
            $step = (int)$segments[1];
321
        }
322
323 105
        if (is_numeric($element)) {
324 54
            $this->validateValue($element, $index, $step);
325 47
            $register[intval($element)] = true;
326
        } else {
327 101
            $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 101
    private function parseRange(array &$register, int $index, string $range, int $stepping): void
341
    {
342 101
        if ($range === '*') {
343 94
            $range = [self::VALUE_BOUNDARIES[$index]['min'], self::VALUE_BOUNDARIES[$index]['max']];
344
        } else {
345 61
            $range = explode('-', $range);
346
        }
347
348 101
        $this->validateRange($range, $index);
349 96
        $this->fillRange($register, $index, $range, $stepping);
350
    }
351
352
    /**
353
     * @param array $register
354
     * @param int $index
355
     * @param array $range
356
     * @param int $stepping
357
     */
358 96
    private function fillRange(array &$register, int $index, array $range, int $stepping): void
359
    {
360 96
        $boundary = self::VALUE_BOUNDARIES[$index]['max'] + self::VALUE_BOUNDARIES[$index]['mod'];
361 96
        $length = $range[1] - $range[0];
362
363 96
        if ($range[0] > $range[1]) {
364 38
            $length += $boundary;
365
        }
366
367 96
        for ($i = 0; $i <= $length; $i += $stepping) {
368 96
            $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 101
    private function validateRange(array $range, int $index): void
380
    {
381 101
        if (sizeof($range) !== 2) {
382 9
            throw new Exception('invalid range notation');
383
        }
384
385 98
        foreach ($range as $value) {
386 98
            $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 102
    private function validateValue(string $value, int $index, int $step = 1): void
397
    {
398 102
        if ((string)$value !== (string)(int)$value) {
399 1
            throw new Exception('non-integer value');
400
        }
401
402 102
        if (intval($value) < self::VALUE_BOUNDARIES[$index]['min'] ||
403 102
            intval($value) > self::VALUE_BOUNDARIES[$index]['max']
404
        ) {
405 8
            throw new Exception('value out of boundary');
406
        }
407
408 100
        if ($step !== 1) {
409 1
            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 55
    private function validateStepping(array $segments, int $index): void
419
    {
420 55
        if (sizeof($segments) !== 2) {
421 1
            throw new Exception('invalid stepping notation');
422
        }
423
424 54
        if ((int)$segments[1] < 1 || (int)$segments[1] > self::VALUE_BOUNDARIES[$index]['max']) {
425 3
            throw new Exception('stepping out of allowed range');
426
        }
427
    }
428
}
429