Debian Codegraph @

vendor/dragonmantank/cron-expression/src/Cron/CronExpression.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Cron;
6
7 use DateTime;
8 use DateTimeImmutable;
9 use DateTimeInterface;
10 use DateTimeZone;
11 use Exception;
12 use InvalidArgumentException;
13 use LogicException;
14 use RuntimeException;
15
16 /**
17 * CRON expression parser that can determine whether or not a CRON expression is
18 * due to run, the next run date and previous run date of a CRON expression.
19 * The determinations made by this class are accurate if checked run once per
20 * minute (seconds are dropped from date time comparisons).
21 *
22 * Schedule parts must map to:
23 * minute [0-59], hour [0-23], day of month, month [1-12|JAN-DEC], day of week
24 * [1-7|MON-SUN], and an optional year.
25 *
26 * @see http://en.wikipedia.org/wiki/Cron
27 */
28 class CronExpression
29 {
30 public const MINUTE = 0;
31 public const HOUR = 1;
32 public const DAY = 2;
33 public const MONTH = 3;
34 public const WEEKDAY = 4;
35
36 /** @deprecated */
37 public const YEAR = 5;
38
39 public const MAPPINGS = [
40 '@yearly' => '0 0 1 1 *',
41 '@annually' => '0 0 1 1 *',
42 '@monthly' => '0 0 1 * *',
43 '@weekly' => '0 0 * * 0',
44 '@daily' => '0 0 * * *',
45 '@midnight' => '0 0 * * *',
46 '@hourly' => '0 * * * *',
47 ];
48
49 /**
50 * @var array<int, string> CRON expression parts
51 */
52 protected $cronParts;
53
54 /**
55 * @var FieldFactoryInterface CRON field factory
56 */
57 protected $fieldFactory;
58
59 /**
60 * @var int Max iteration count when searching for next run date
61 */
62 protected $maxIterationCount = 1000;
63
64 /**
65 * @var array<int, int> Order in which to test of cron parts
66 */
67 protected static $order = [
68 self::YEAR,
69 self::MONTH,
70 self::DAY,
71 self::WEEKDAY,
72 self::HOUR,
73 self::MINUTE,
74 ];
75
76 /**
77 * @var array<string, string>
78 */
79 private static $registeredAliases = self::MAPPINGS;
80
81 /**
82 * Registered a user defined CRON Expression Alias.
83 *
84 * @throws LogicException If the expression or the alias name are invalid
85 * or if the alias is already registered.
86 */
87 public static function registerAlias(string $alias, string $expression): void
88 {
89 try {
90 new self($expression);
91 } catch (InvalidArgumentException $exception) {
92 throw new LogicException("The expression `$expression` is invalid", 0, $exception);
93 }
94
95 $shortcut = strtolower($alias);
96 if (1 !== preg_match('/^@\w+$/', $shortcut)) {
97 throw new LogicException("The alias `$alias` is invalid. It must start with an `@` character and contain alphanumeric (letters, numbers, regardless of case) plus underscore (_).");
98 }
99
100 if (isset(self::$registeredAliases[$shortcut])) {
101 throw new LogicException("The alias `$alias` is already registered.");
102 }
103
104 self::$registeredAliases[$shortcut] = $expression;
105 }
106
107 /**
108 * Unregistered a user defined CRON Expression Alias.
109 *
110 * @throws LogicException If the user tries to unregister a built-in alias
111 */
112 public static function unregisterAlias(string $alias): bool
113 {
114 $shortcut = strtolower($alias);
115 if (isset(self::MAPPINGS[$shortcut])) {
116 throw new LogicException("The alias `$alias` is a built-in alias; it can not be unregistered.");
117 }
118
119 if (!isset(self::$registeredAliases[$shortcut])) {
120 return false;
121 }
122
123 unset(self::$registeredAliases[$shortcut]);
124
125 return true;
126 }
127
128 /**
129 * Tells whether a CRON Expression alias is registered.
130 */
131 public static function supportsAlias(string $alias): bool
132 {
133 return isset(self::$registeredAliases[strtolower($alias)]);
134 }
135
136 /**
137 * Returns all registered aliases as an associated array where the aliases are the key
138 * and their associated expressions are the values.
139 *
140 * @return array<string, string>
141 */
142 public static function getAliases(): array
143 {
144 return self::$registeredAliases;
145 }
146
147 /**
148 * @deprecated since version 3.0.2, use __construct instead.
149 */
150 public static function factory(string $expression, ?FieldFactoryInterface $fieldFactory = null): CronExpression
151 {
152 /** @phpstan-ignore-next-line */
153 return new static($expression, $fieldFactory);
154 }
155
156 /**
157 * Validate a CronExpression.
158 *
159 * @param string $expression the CRON expression to validate
160 *
161 * @return bool True if a valid CRON expression was passed. False if not.
162 */
163 public static function isValidExpression(string $expression): bool
164 {
165 try {
166 new CronExpression($expression);
167 } catch (InvalidArgumentException $e) {
168 return false;
169 }
170
171 return true;
172 }
173
174 /**
175 * Parse a CRON expression.
176 *
177 * @param string $expression CRON expression (e.g. '8 * * * *')
178 * @param null|FieldFactoryInterface $fieldFactory Factory to create cron fields
179 * @throws InvalidArgumentException
180 */
181 public function __construct(string $expression, ?FieldFactoryInterface $fieldFactory = null)
182 {
183 $shortcut = strtolower($expression);
184 $expression = self::$registeredAliases[$shortcut] ?? $expression;
185
186 $this->fieldFactory = $fieldFactory ?: new FieldFactory();
187 $this->setExpression($expression);
188 }
189
190 /**
191 * Set or change the CRON expression.
192 *
193 * @param string $value CRON expression (e.g. 8 * * * *)
194 *
195 * @throws \InvalidArgumentException if not a valid CRON expression
196 *
197 * @return CronExpression
198 */
199 public function setExpression(string $value): CronExpression
200 {
201 $split = preg_split('/\s/', $value, -1, PREG_SPLIT_NO_EMPTY);
202
203 if (!\is_array($split)) {
204 throw new InvalidArgumentException(
205 $value . ' is not a valid CRON expression'
206 );
207 }
208
209 $notEnoughParts = \count($split) < 5;
210
211 $questionMarkInInvalidPart = array_key_exists(0, $split) && $split[0] === '?'
212 || array_key_exists(1, $split) && $split[1] === '?'
213 || array_key_exists(3, $split) && $split[3] === '?';
214
215 $tooManyQuestionMarks = array_key_exists(2, $split) && $split[2] === '?'
216 && array_key_exists(4, $split) && $split[4] === '?';
217
218 if ($notEnoughParts || $questionMarkInInvalidPart || $tooManyQuestionMarks) {
219 throw new InvalidArgumentException(
220 $value . ' is not a valid CRON expression'
221 );
222 }
223
224 $this->cronParts = $split;
225 foreach ($this->cronParts as $position => $part) {
226 $this->setPart($position, $part);
227 }
228
229 return $this;
230 }
231
232 /**
233 * Set part of the CRON expression.
234 *
235 * @param int $position The position of the CRON expression to set
236 * @param string $value The value to set
237 *
238 * @throws \InvalidArgumentException if the value is not valid for the part
239 *
240 * @return CronExpression
241 */
242 public function setPart(int $position, string $value): CronExpression
243 {
244 if (!$this->fieldFactory->getField($position)->validate($value)) {
245 throw new InvalidArgumentException(
246 'Invalid CRON field value ' . $value . ' at position ' . $position
247 );
248 }
249
250 $this->cronParts[$position] = $value;
251
252 return $this;
253 }
254
255 /**
256 * Set max iteration count for searching next run dates.
257 *
258 * @param int $maxIterationCount Max iteration count when searching for next run date
259 *
260 * @return CronExpression
261 */
262 public function setMaxIterationCount(int $maxIterationCount): CronExpression
263 {
264 $this->maxIterationCount = $maxIterationCount;
265
266 return $this;
267 }
268
269 /**
270 * Get a next run date relative to the current date or a specific date
271 *
272 * @param string|\DateTimeInterface $currentTime Relative calculation date
273 * @param int $nth Number of matches to skip before returning a
274 * matching next run date. 0, the default, will return the
275 * current date and time if the next run date falls on the
276 * current date and time. Setting this value to 1 will
277 * skip the first match and go to the second match.
278 * Setting this value to 2 will skip the first 2
279 * matches and so on.
280 * @param bool $allowCurrentDate Set to TRUE to return the current date if
281 * it matches the cron expression.
282 * @param null|string $timeZone TimeZone to use instead of the system default
283 *
284 * @throws \RuntimeException on too many iterations
285 * @throws \Exception
286 *
287 * @return \DateTime
288 */
289 public function getNextRunDate($currentTime = 'now', int $nth = 0, bool $allowCurrentDate = false, $timeZone = null): DateTime
290 {
291 return $this->getRunDate($currentTime, $nth, false, $allowCurrentDate, $timeZone);
292 }
293
294 /**
295 * Get a previous run date relative to the current date or a specific date.
296 *
297 * @param string|\DateTimeInterface $currentTime Relative calculation date
298 * @param int $nth Number of matches to skip before returning
299 * @param bool $allowCurrentDate Set to TRUE to return the
300 * current date if it matches the cron expression
301 * @param null|string $timeZone TimeZone to use instead of the system default
302 *
303 * @throws \RuntimeException on too many iterations
304 * @throws \Exception
305 *
306 * @return \DateTime
307 *
308 * @see \Cron\CronExpression::getNextRunDate
309 */
310 public function getPreviousRunDate($currentTime = 'now', int $nth = 0, bool $allowCurrentDate = false, $timeZone = null): DateTime
311 {
312 return $this->getRunDate($currentTime, $nth, true, $allowCurrentDate, $timeZone);
313 }
314
315 /**
316 * Get multiple run dates starting at the current date or a specific date.
317 *
318 * @param int $total Set the total number of dates to calculate
319 * @param string|\DateTimeInterface|null $currentTime Relative calculation date
320 * @param bool $invert Set to TRUE to retrieve previous dates
321 * @param bool $allowCurrentDate Set to TRUE to return the
322 * current date if it matches the cron expression
323 * @param null|string $timeZone TimeZone to use instead of the system default
324 *
325 * @return \DateTime[] Returns an array of run dates
326 */
327 public function getMultipleRunDates(int $total, $currentTime = 'now', bool $invert = false, bool $allowCurrentDate = false, $timeZone = null): array
328 {
329 $timeZone = $this->determineTimeZone($currentTime, $timeZone);
330
331 if ('now' === $currentTime) {
332 $currentTime = new DateTime();
333 } elseif ($currentTime instanceof DateTime) {
334 $currentTime = clone $currentTime;
335 } elseif ($currentTime instanceof DateTimeImmutable) {
336 $currentTime = DateTime::createFromFormat('U', $currentTime->format('U'));
337 } elseif (\is_string($currentTime)) {
338 $currentTime = new DateTime($currentTime);
339 }
340
341 if (!$currentTime instanceof DateTime) {
342 throw new InvalidArgumentException('invalid current time');
343 }
344
345 $currentTime->setTimezone(new DateTimeZone($timeZone));
346
347 $matches = [];
348 for ($i = 0; $i < $total; ++$i) {
349 try {
350 $result = $this->getRunDate($currentTime, 0, $invert, $allowCurrentDate, $timeZone);
351 } catch (RuntimeException $e) {
352 break;
353 }
354
355 $allowCurrentDate = false;
356 $currentTime = clone $result;
357 $matches[] = $result;
358 }
359
360 return $matches;
361 }
362
363 /**
364 * Get all or part of the CRON expression.
365 *
366 * @param int|string|null $part specify the part to retrieve or NULL to get the full
367 * cron schedule string
368 *
369 * @return null|string Returns the CRON expression, a part of the
370 * CRON expression, or NULL if the part was specified but not found
371 */
372 public function getExpression($part = null): ?string
373 {
374 if (null === $part) {
375 return implode(' ', $this->cronParts);
376 }
377
378 if (array_key_exists($part, $this->cronParts)) {
379 return $this->cronParts[$part];
380 }
381
382 return null;
383 }
384
385 /**
386 * Gets the parts of the cron expression as an array.
387 *
388 * @return string[]
389 * The array of parts that make up this expression.
390 */
391 public function getParts()
392 {
393 return $this->cronParts;
394 }
395
396 /**
397 * Helper method to output the full expression.
398 *
399 * @return string Full CRON expression
400 */
401 public function __toString(): string
402 {
403 return (string) $this->getExpression();
404 }
405
406 /**
407 * Determine if the cron is due to run based on the current date or a
408 * specific date. This method assumes that the current number of
409 * seconds are irrelevant, and should be called once per minute.
410 *
411 * @param string|\DateTimeInterface $currentTime Relative calculation date
412 * @param null|string $timeZone TimeZone to use instead of the system default
413 *
414 * @return bool Returns TRUE if the cron is due to run or FALSE if not
415 */
416 public function isDue($currentTime = 'now', $timeZone = null): bool
417 {
418 $timeZone = $this->determineTimeZone($currentTime, $timeZone);
419
420 if ('now' === $currentTime) {
421 $currentTime = new DateTime();
422 } elseif ($currentTime instanceof DateTime) {
423 $currentTime = clone $currentTime;
424 } elseif ($currentTime instanceof DateTimeImmutable) {
425 $currentTime = DateTime::createFromFormat('U', $currentTime->format('U'));
426 } elseif (\is_string($currentTime)) {
427 $currentTime = new DateTime($currentTime);
428 }
429
430 if (!$currentTime instanceof DateTime) {
431 throw new InvalidArgumentException('invalid current time');
432 }
433
434 $currentTime->setTimezone(new DateTimeZone($timeZone));
435
436 // drop the seconds to 0
437 $currentTime->setTime((int) $currentTime->format('H'), (int) $currentTime->format('i'), 0);
438
439 try {
440 return $this->getNextRunDate($currentTime, 0, true)->getTimestamp() === $currentTime->getTimestamp();
441 } catch (Exception $e) {
442 return false;
443 }
444 }
445
446 /**
447 * Get the next or previous run date of the expression relative to a date.
448 *
449 * @param string|\DateTimeInterface|null $currentTime Relative calculation date
450 * @param int $nth Number of matches to skip before returning
451 * @param bool $invert Set to TRUE to go backwards in time
452 * @param bool $allowCurrentDate Set to TRUE to return the
453 * current date if it matches the cron expression
454 * @param string|null $timeZone TimeZone to use instead of the system default
455 *
456 * @throws \RuntimeException on too many iterations
457 * @throws Exception
458 *
459 * @return \DateTime
460 */
461 protected function getRunDate($currentTime = null, int $nth = 0, bool $invert = false, bool $allowCurrentDate = false, $timeZone = null): DateTime
462 {
463 $timeZone = $this->determineTimeZone($currentTime, $timeZone);
464
465 if ($currentTime instanceof DateTime) {
466 $currentDate = clone $currentTime;
467 } elseif ($currentTime instanceof DateTimeImmutable) {
468 $currentDate = DateTime::createFromFormat('U', $currentTime->format('U'));
469 } elseif (\is_string($currentTime)) {
470 $currentDate = new DateTime($currentTime);
471 } else {
472 $currentDate = new DateTime('now');
473 }
474
475 if (!$currentDate instanceof DateTime) {
476 throw new InvalidArgumentException('invalid current date');
477 }
478
479 $currentDate->setTimezone(new DateTimeZone($timeZone));
480 // Workaround for setTime causing an offset change: https://bugs.php.net/bug.php?id=81074
481 $currentDate = DateTime::createFromFormat("!Y-m-d H:iO", $currentDate->format("Y-m-d H:iP"), $currentDate->getTimezone());
482 if ($currentDate === false) {
483 throw new \RuntimeException('Unable to create date from format');
484 }
485 $currentDate->setTimezone(new DateTimeZone($timeZone));
486
487 $nextRun = clone $currentDate;
488
489 // We don't have to satisfy * or null fields
490 $parts = [];
491 $fields = [];
492 foreach (self::$order as $position) {
493 $part = $this->getExpression($position);
494 if (null === $part || '*' === $part) {
495 continue;
496 }
497 $parts[$position] = $part;
498 $fields[$position] = $this->fieldFactory->getField($position);
499 }
500
501 if (isset($parts[self::DAY]) && isset($parts[self::WEEKDAY])) {
502 $domExpression = sprintf('%s %s %s %s *', $this->getExpression(0), $this->getExpression(1), $this->getExpression(2), $this->getExpression(3));
503 $dowExpression = sprintf('%s %s * %s %s', $this->getExpression(0), $this->getExpression(1), $this->getExpression(3), $this->getExpression(4));
504
505 $domExpression = new self($domExpression);
506 $dowExpression = new self($dowExpression);
507
508 $domRunDates = $domExpression->getMultipleRunDates($nth + 1, $currentTime, $invert, $allowCurrentDate, $timeZone);
509 $dowRunDates = $dowExpression->getMultipleRunDates($nth + 1, $currentTime, $invert, $allowCurrentDate, $timeZone);
510
511 if ($parts[self::DAY] === '?' || $parts[self::DAY] === '*') {
512 $domRunDates = [];
513 }
514
515 if ($parts[self::WEEKDAY] === '?' || $parts[self::WEEKDAY] === '*') {
516 $dowRunDates = [];
517 }
518
519 $combined = array_merge($domRunDates, $dowRunDates);
520 usort($combined, function ($a, $b) {
521 return $a->format('Y-m-d H:i:s') <=> $b->format('Y-m-d H:i:s');
522 });
523 if ($invert) {
524 $combined = array_reverse($combined);
525 }
526
527 return $combined[$nth];
528 }
529
530 // Set a hard limit to bail on an impossible date
531 for ($i = 0; $i < $this->maxIterationCount; ++$i) {
532 foreach ($parts as $position => $part) {
533 $satisfied = false;
534 // Get the field object used to validate this part
535 $field = $fields[$position];
536 // Check if this is singular or a list
537 if (false === strpos($part, ',')) {
538 $satisfied = $field->isSatisfiedBy($nextRun, $part, $invert);
539 } else {
540 foreach (array_map('trim', explode(',', $part)) as $listPart) {
541 if ($field->isSatisfiedBy($nextRun, $listPart, $invert)) {
542 $satisfied = true;
543
544 break;
545 }
546 }
547 }
548
549 // If the field is not satisfied, then start over
550 if (!$satisfied) {
551 $field->increment($nextRun, $invert, $part);
552
553 continue 2;
554 }
555 }
556
557 // Skip this match if needed
558 if ((!$allowCurrentDate && $nextRun == $currentDate) || --$nth > -1) {
559 $this->fieldFactory->getField(self::MINUTE)->increment($nextRun, $invert, $parts[self::MINUTE] ?? null);
560 continue;
561 }
562
563 return $nextRun;
564 }
565
566 // @codeCoverageIgnoreStart
567 throw new RuntimeException('Impossible CRON expression');
568 // @codeCoverageIgnoreEnd
569 }
570
571 /**
572 * Workout what timeZone should be used.
573 *
574 * @param string|\DateTimeInterface|null $currentTime Relative calculation date
575 * @param string|null $timeZone TimeZone to use instead of the system default
576 *
577 * @return string
578 */
579 protected function determineTimeZone($currentTime, ?string $timeZone): string
580 {
581 if (null !== $timeZone) {
582 return $timeZone;
583 }
584
585 if ($currentTime instanceof DateTimeInterface) {
586 return $currentTime->getTimezone()->getName();
587 }
588
589 return date_default_timezone_get();
590 }
591 }