Passed
Push — 2.4 ( a7bb08...074943 )
by René
02:43 queued 45s
created

CronExpression   F

Complexity

Total Complexity 60

Size/Duplication

Total Lines 414
Duplicated Lines 0 %

Importance

Changes 28
Bugs 1 Features 1
Metric Value
eloc 165
c 28
b 1
f 1
dl 0
loc 414
rs 3.6
wmc 60

16 Methods

Rating   Name   Duplication   Size   Complexity  
A adjust() 0 22 6
A getNext() 0 14 3
A validateStepping() 0 8 4
A fillRange() 0 11 3
A isValid() 0 3 1
A parseElement() 0 17 3
A validateRange() 0 8 3
A isMatching() 0 11 5
A toDateTime() 0 18 5
A parse() 0 19 5
A match() 0 12 3
A validateValue() 0 14 5
A __construct() 0 8 2
A parseSegment() 0 12 4
A forward() 0 17 6
A parseRange() 0 10 2

How to fix   Complexity   

Complex Class

Complex classes like CronExpression often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CronExpression, and based on these observations, apply Extract Interface, too.

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
            $now = $this->toDateTime($start);
149
            $pointer = sscanf($now->format('i G j n Y'), '%d %d %d %d %d');
150
151
            do {
152
                $current = $this->adjust($now, $pointer);
153
            } while ($this->forward($now, $current));
154
155
            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
    private function toDateTime($start): DateTime
166
    {
167
        if ($start instanceof DateTimeInterface) {
168
            $now = $start;
169
        } elseif ((int)$start > 0) {
170
            $now = new DateTime('@' . $start);
171
        } else {
172
            $now = new DateTime('@' . time());
173
        }
174
175
        $now->setTimestamp($now->getTimeStamp() - $now->getTimeStamp() % 60);
176
        $now->setTimezone($this->timeZone ?: new DateTimeZone(date_default_timezone_get()));
177
178
        if ($this->isMatching($now)) {
179
            $now->modify('+1 minute');
180
        }
181
182
        return $now;
183
    }
184
185
    /**
186
     * @param DateTimeInterface $now
187
     * @param array $pointer
188
     * @return array
189
     */
190
    private function adjust(DateTimeInterface $now, array &$pointer): array
191
    {
192
        $current = sscanf($now->format('i G j n Y w'), '%d %d %d %d %d %d');
193
194
        if ($pointer[0] !== $current[0] || $pointer[1] !== $current[1]) {
195
            $pointer[0] = $current[0];
196
            $pointer[1] = $current[1];
197
            $now->setTime($current[1], $current[0]);
198
        } elseif ($pointer[4] !== $current[4]) {
199
            $pointer[4] = $current[4];
200
            $now->setDate($current[4], 1, 1);
201
            $now->setTime(0, 0);
202
        } elseif ($pointer[3] !== $current[3]) {
203
            $pointer[3] = $current[3];
204
            $now->setDate($current[4], $current[3], 1);
205
            $now->setTime(0, 0);
206
        } elseif ($pointer[2] !== $current[2]) {
207
            $pointer[2] = $current[2];
208
            $now->setTime(0, 0);
209
        }
210
211
        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
    private function forward(DateTimeInterface $now, array $current): bool
220
    {
221
        if (isset($this->registers[3][$current[3]]) === false) {
222
            $now->modify('+1 month');
223
            return true;
224
        } elseif (false === (isset($this->registers[2][$current[2]]) && isset($this->registers[4][$current[5]]))) {
225
            $now->modify('+1 day');
226
            return true;
227
        } elseif (isset($this->registers[0][$current[0]]) === false) {
228
            $now->modify('+1 minute');
229
            return true;
230
        } elseif (isset($this->registers[1][$current[1]]) === false) {
231
            $now->modify('+1 hour');
232
            return true;
233
        }
234
235
        return false;
236
    }
237
238
    /**
239
     * @param array $segments
240
     * @return bool
241
     */
242
    private function match(array $segments): bool
243
    {
244
        $result = true;
245
246
        foreach ($this->registers as $i => $item) {
247
            if (isset($item[(int)$segments[$i]]) === false) {
248
                $result = false;
249
                break;
250
            }
251
        }
252
253
        return $result;
254
    }
255
256
    /**
257
     * 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
        if (is_array($segments) && sizeof($segments) === 5) {
268
            $registers = array_fill(0, 5, []);
269
270
            foreach ($segments as $index => $segment) {
271
                $this->parseSegment($registers[$index], $index, $segment);
272
            }
273
274
            if (isset($registers[4][7])) {
275
                $registers[4][0] = true;
276
            }
277
278
            return $registers;
279
        }
280
281
        throw new Exception('invalid number of segments');
282
    }
283
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
     */
292
    private function parseSegment(array &$register, $index, $segment): void
293
    {
294
        $allowed = [false, false, false, self::MONTH_NAMES, self::WEEKDAY_NAMES];
295
296
        // month names, weekdays
297
        if ($allowed[$index] !== false && isset($allowed[$index][strtolower($segment)])) {
298
            // 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
            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
     * @param string $element
312
     * @throws Exception
313
     */
314
    private function parseElement(array &$register, int $index, string $element): void
315
    {
316
        $step = 1;
317
        $segments = explode('/', $element);
318
319
        if (sizeof($segments) > 1) {
320
            $this->validateStepping($segments, $index);
321
322
            $element = (string)$segments[0];
323
            $step = (int)$segments[1];
324
        }
325
326
        if (is_numeric($element)) {
327
            $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
     * @param int $index
339
     * @param string $range
340
     * @param int $stepping
341
     * @throws Exception
342
     */
343
    private function parseRange(array &$register, int $index, string $range, int $stepping): void
344
    {
345
        if ($range === '*') {
346
            $range = [self::VALUE_BOUNDARIES[$index]['min'], self::VALUE_BOUNDARIES[$index]['max']];
347
        } else {
348
            $range = explode('-', $range);
349
        }
350
351
        $this->validateRange($range, $index);
352
        $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
     */
361
    private function fillRange(array &$register, int $index, array $range, int $stepping): void
362
    {
363
        $boundary = self::VALUE_BOUNDARIES[$index]['max'] + self::VALUE_BOUNDARIES[$index]['mod'];
364
        $length = $range[1] - $range[0];
365
366
        if ($range[0] > $range[1]) {
367
            $length += $boundary;
368
        }
369
370
        for ($i = 0; $i <= $length; $i += $stepping) {
371
            $register[($range[0] + $i) % $boundary] = true;
372
        }
373
    }
374
375
    /**
376
     * Validate whether a given range of values exceeds allowed value boundaries
377
     *
378
     * @param array $range
379
     * @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
        }
391
    }
392
393
    /**
394
     * @param string $value
395
     * @param int $index
396
     * @param int $step
397
     * @throws Exception
398
     */
399
    private function validateValue(string $value, int $index, int $step = 1): void
400
    {
401
        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
        if ($step !== 1) {
412
            throw new Exception('invalid combination of value and stepping notation');
413
        }
414
    }
415
416
    /**
417
     * @param array $segments
418
     * @param int $index
419
     * @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
        }
430
    }
431
}
432