AbstractField.php
1 year ago
CronExpression.php
8 months ago
DayOfMonthField.php
1 year ago
DayOfWeekField.php
1 year ago
FieldFactory.php
1 year ago
FieldFactoryInterface.php
1 year ago
FieldInterface.php
1 year ago
HoursField.php
1 year ago
MinutesField.php
1 year ago
MonthField.php
1 year ago
index.php
1 year ago
CronExpression.php
309 lines
| 1 | <?php |
| 2 | declare(strict_types=1); |
| 3 | namespace Cron; |
| 4 | if (!defined('ABSPATH')) exit; |
| 5 | use DateTime; |
| 6 | use DateTimeImmutable; |
| 7 | use DateTimeInterface; |
| 8 | use DateTimeZone; |
| 9 | use Exception; |
| 10 | use InvalidArgumentException; |
| 11 | use LogicException; |
| 12 | use RuntimeException; |
| 13 | use Webmozart\Assert\Assert; |
| 14 | class CronExpression |
| 15 | { |
| 16 | public const MINUTE = 0; |
| 17 | public const HOUR = 1; |
| 18 | public const DAY = 2; |
| 19 | public const MONTH = 3; |
| 20 | public const WEEKDAY = 4; |
| 21 | public const YEAR = 5; |
| 22 | public const MAPPINGS = [ |
| 23 | '@yearly' => '0 0 1 1 *', |
| 24 | '@annually' => '0 0 1 1 *', |
| 25 | '@monthly' => '0 0 1 * *', |
| 26 | '@weekly' => '0 0 * * 0', |
| 27 | '@daily' => '0 0 * * *', |
| 28 | '@midnight' => '0 0 * * *', |
| 29 | '@hourly' => '0 * * * *', |
| 30 | ]; |
| 31 | protected $cronParts; |
| 32 | protected $fieldFactory; |
| 33 | protected $maxIterationCount = 1000; |
| 34 | protected static $order = [ |
| 35 | self::YEAR, |
| 36 | self::MONTH, |
| 37 | self::DAY, |
| 38 | self::WEEKDAY, |
| 39 | self::HOUR, |
| 40 | self::MINUTE, |
| 41 | ]; |
| 42 | private static $registeredAliases = self::MAPPINGS; |
| 43 | public static function registerAlias(string $alias, string $expression): void |
| 44 | { |
| 45 | try { |
| 46 | new self($expression); |
| 47 | } catch (InvalidArgumentException $exception) { |
| 48 | throw new LogicException("The expression `$expression` is invalid", 0, $exception); |
| 49 | } |
| 50 | $shortcut = strtolower($alias); |
| 51 | if (1 !== preg_match('/^@\w+$/', $shortcut)) { |
| 52 | throw new LogicException("The alias `$alias` is invalid. It must start with an `@` character and contain alphanumeric (letters, numbers, regardless of case) plus underscore (_)."); |
| 53 | } |
| 54 | if (isset(self::$registeredAliases[$shortcut])) { |
| 55 | throw new LogicException("The alias `$alias` is already registered."); |
| 56 | } |
| 57 | self::$registeredAliases[$shortcut] = $expression; |
| 58 | } |
| 59 | public static function unregisterAlias(string $alias): bool |
| 60 | { |
| 61 | $shortcut = strtolower($alias); |
| 62 | if (isset(self::MAPPINGS[$shortcut])) { |
| 63 | throw new LogicException("The alias `$alias` is a built-in alias; it can not be unregistered."); |
| 64 | } |
| 65 | if (!isset(self::$registeredAliases[$shortcut])) { |
| 66 | return false; |
| 67 | } |
| 68 | unset(self::$registeredAliases[$shortcut]); |
| 69 | return true; |
| 70 | } |
| 71 | public static function supportsAlias(string $alias): bool |
| 72 | { |
| 73 | return isset(self::$registeredAliases[strtolower($alias)]); |
| 74 | } |
| 75 | public static function getAliases(): array |
| 76 | { |
| 77 | return self::$registeredAliases; |
| 78 | } |
| 79 | public static function factory(string $expression,?FieldFactoryInterface $fieldFactory = null): CronExpression |
| 80 | { |
| 81 | return new static($expression, $fieldFactory); |
| 82 | } |
| 83 | public static function isValidExpression(string $expression): bool |
| 84 | { |
| 85 | try { |
| 86 | new CronExpression($expression); |
| 87 | } catch (InvalidArgumentException $e) { |
| 88 | return false; |
| 89 | } |
| 90 | return true; |
| 91 | } |
| 92 | public function __construct(string $expression,?FieldFactoryInterface $fieldFactory = null) |
| 93 | { |
| 94 | $shortcut = strtolower($expression); |
| 95 | $expression = self::$registeredAliases[$shortcut] ?? $expression; |
| 96 | $this->fieldFactory = $fieldFactory ?: new FieldFactory(); |
| 97 | $this->setExpression($expression); |
| 98 | } |
| 99 | public function setExpression(string $value): CronExpression |
| 100 | { |
| 101 | $split = preg_split('/\s/', $value, -1, PREG_SPLIT_NO_EMPTY); |
| 102 | Assert::isArray($split); |
| 103 | $notEnoughParts = \count($split) < 5; |
| 104 | $questionMarkInInvalidPart = array_key_exists(0, $split) && $split[0] === '?' |
| 105 | || array_key_exists(1, $split) && $split[1] === '?' |
| 106 | || array_key_exists(3, $split) && $split[3] === '?'; |
| 107 | $tooManyQuestionMarks = array_key_exists(2, $split) && $split[2] === '?' |
| 108 | && array_key_exists(4, $split) && $split[4] === '?'; |
| 109 | if ($notEnoughParts || $questionMarkInInvalidPart || $tooManyQuestionMarks) { |
| 110 | throw new InvalidArgumentException( |
| 111 | $value . ' is not a valid CRON expression' |
| 112 | ); |
| 113 | } |
| 114 | $this->cronParts = $split; |
| 115 | foreach ($this->cronParts as $position => $part) { |
| 116 | $this->setPart($position, $part); |
| 117 | } |
| 118 | return $this; |
| 119 | } |
| 120 | public function setPart(int $position, string $value): CronExpression |
| 121 | { |
| 122 | if (!$this->fieldFactory->getField($position)->validate($value)) { |
| 123 | throw new InvalidArgumentException( |
| 124 | 'Invalid CRON field value ' . $value . ' at position ' . $position |
| 125 | ); |
| 126 | } |
| 127 | $this->cronParts[$position] = $value; |
| 128 | return $this; |
| 129 | } |
| 130 | public function setMaxIterationCount(int $maxIterationCount): CronExpression |
| 131 | { |
| 132 | $this->maxIterationCount = $maxIterationCount; |
| 133 | return $this; |
| 134 | } |
| 135 | public function getNextRunDate($currentTime = 'now', int $nth = 0, bool $allowCurrentDate = false, $timeZone = null): DateTime |
| 136 | { |
| 137 | return $this->getRunDate($currentTime, $nth, false, $allowCurrentDate, $timeZone); |
| 138 | } |
| 139 | public function getPreviousRunDate($currentTime = 'now', int $nth = 0, bool $allowCurrentDate = false, $timeZone = null): DateTime |
| 140 | { |
| 141 | return $this->getRunDate($currentTime, $nth, true, $allowCurrentDate, $timeZone); |
| 142 | } |
| 143 | public function getMultipleRunDates(int $total, $currentTime = 'now', bool $invert = false, bool $allowCurrentDate = false, $timeZone = null): array |
| 144 | { |
| 145 | $timeZone = $this->determineTimeZone($currentTime, $timeZone); |
| 146 | if ('now' === $currentTime) { |
| 147 | $currentTime = new DateTime(); |
| 148 | } elseif ($currentTime instanceof DateTime) { |
| 149 | $currentTime = clone $currentTime; |
| 150 | } elseif ($currentTime instanceof DateTimeImmutable) { |
| 151 | $currentTime = DateTime::createFromFormat('U', $currentTime->format('U')); |
| 152 | } elseif (\is_string($currentTime)) { |
| 153 | $currentTime = new DateTime($currentTime); |
| 154 | } |
| 155 | Assert::isInstanceOf($currentTime, DateTime::class); |
| 156 | $currentTime->setTimezone(new DateTimeZone($timeZone)); |
| 157 | $matches = []; |
| 158 | for ($i = 0; $i < $total; ++$i) { |
| 159 | try { |
| 160 | $result = $this->getRunDate($currentTime, 0, $invert, $allowCurrentDate, $timeZone); |
| 161 | } catch (RuntimeException $e) { |
| 162 | break; |
| 163 | } |
| 164 | $allowCurrentDate = false; |
| 165 | $currentTime = clone $result; |
| 166 | $matches[] = $result; |
| 167 | } |
| 168 | return $matches; |
| 169 | } |
| 170 | public function getExpression($part = null): ?string |
| 171 | { |
| 172 | if (null === $part) { |
| 173 | return implode(' ', $this->cronParts); |
| 174 | } |
| 175 | if (array_key_exists($part, $this->cronParts)) { |
| 176 | return $this->cronParts[$part]; |
| 177 | } |
| 178 | return null; |
| 179 | } |
| 180 | public function getParts() |
| 181 | { |
| 182 | return $this->cronParts; |
| 183 | } |
| 184 | public function __toString(): string |
| 185 | { |
| 186 | return (string) $this->getExpression(); |
| 187 | } |
| 188 | public function isDue($currentTime = 'now', $timeZone = null): bool |
| 189 | { |
| 190 | $timeZone = $this->determineTimeZone($currentTime, $timeZone); |
| 191 | if ('now' === $currentTime) { |
| 192 | $currentTime = new DateTime(); |
| 193 | } elseif ($currentTime instanceof DateTime) { |
| 194 | $currentTime = clone $currentTime; |
| 195 | } elseif ($currentTime instanceof DateTimeImmutable) { |
| 196 | $currentTime = DateTime::createFromFormat('U', $currentTime->format('U')); |
| 197 | } elseif (\is_string($currentTime)) { |
| 198 | $currentTime = new DateTime($currentTime); |
| 199 | } |
| 200 | Assert::isInstanceOf($currentTime, DateTime::class); |
| 201 | $currentTime->setTimezone(new DateTimeZone($timeZone)); |
| 202 | // drop the seconds to 0 |
| 203 | $currentTime->setTime((int) $currentTime->format('H'), (int) $currentTime->format('i'), 0); |
| 204 | try { |
| 205 | return $this->getNextRunDate($currentTime, 0, true)->getTimestamp() === $currentTime->getTimestamp(); |
| 206 | } catch (Exception $e) { |
| 207 | return false; |
| 208 | } |
| 209 | } |
| 210 | protected function getRunDate($currentTime = null, int $nth = 0, bool $invert = false, bool $allowCurrentDate = false, $timeZone = null): DateTime |
| 211 | { |
| 212 | $timeZone = $this->determineTimeZone($currentTime, $timeZone); |
| 213 | if ($currentTime instanceof DateTime) { |
| 214 | $currentDate = clone $currentTime; |
| 215 | } elseif ($currentTime instanceof DateTimeImmutable) { |
| 216 | $currentDate = DateTime::createFromFormat('U', $currentTime->format('U')); |
| 217 | } elseif (\is_string($currentTime)) { |
| 218 | $currentDate = new DateTime($currentTime); |
| 219 | } else { |
| 220 | $currentDate = new DateTime('now'); |
| 221 | } |
| 222 | Assert::isInstanceOf($currentDate, DateTime::class); |
| 223 | $currentDate->setTimezone(new DateTimeZone($timeZone)); |
| 224 | // Workaround for setTime causing an offset change: https://bugs.php.net/bug.php?id=81074 |
| 225 | $currentDate = DateTime::createFromFormat("!Y-m-d H:iO", $currentDate->format("Y-m-d H:iP"), $currentDate->getTimezone()); |
| 226 | if ($currentDate === false) { |
| 227 | throw new \RuntimeException('Unable to create date from format'); |
| 228 | } |
| 229 | $currentDate->setTimezone(new DateTimeZone($timeZone)); |
| 230 | $nextRun = clone $currentDate; |
| 231 | // We don't have to satisfy * or null fields |
| 232 | $parts = []; |
| 233 | $fields = []; |
| 234 | foreach (self::$order as $position) { |
| 235 | $part = $this->getExpression($position); |
| 236 | if (null === $part || '*' === $part) { |
| 237 | continue; |
| 238 | } |
| 239 | $parts[$position] = $part; |
| 240 | $fields[$position] = $this->fieldFactory->getField($position); |
| 241 | } |
| 242 | if (isset($parts[self::DAY]) && isset($parts[self::WEEKDAY])) { |
| 243 | $domExpression = sprintf('%s %s %s %s *', $this->getExpression(0), $this->getExpression(1), $this->getExpression(2), $this->getExpression(3)); |
| 244 | $dowExpression = sprintf('%s %s * %s %s', $this->getExpression(0), $this->getExpression(1), $this->getExpression(3), $this->getExpression(4)); |
| 245 | $domExpression = new self($domExpression); |
| 246 | $dowExpression = new self($dowExpression); |
| 247 | $domRunDates = $domExpression->getMultipleRunDates($nth + 1, $currentTime, $invert, $allowCurrentDate, $timeZone); |
| 248 | $dowRunDates = $dowExpression->getMultipleRunDates($nth + 1, $currentTime, $invert, $allowCurrentDate, $timeZone); |
| 249 | if ($parts[self::DAY] === '?' || $parts[self::DAY] === '*') { |
| 250 | $domRunDates = []; |
| 251 | } |
| 252 | if ($parts[self::WEEKDAY] === '?' || $parts[self::WEEKDAY] === '*') { |
| 253 | $dowRunDates = []; |
| 254 | } |
| 255 | $combined = array_merge($domRunDates, $dowRunDates); |
| 256 | usort($combined, function ($a, $b) { |
| 257 | return $a->format('Y-m-d H:i:s') <=> $b->format('Y-m-d H:i:s'); |
| 258 | }); |
| 259 | if ($invert) { |
| 260 | $combined = array_reverse($combined); |
| 261 | } |
| 262 | return $combined[$nth]; |
| 263 | } |
| 264 | // Set a hard limit to bail on an impossible date |
| 265 | for ($i = 0; $i < $this->maxIterationCount; ++$i) { |
| 266 | foreach ($parts as $position => $part) { |
| 267 | $satisfied = false; |
| 268 | // Get the field object used to validate this part |
| 269 | $field = $fields[$position]; |
| 270 | // Check if this is singular or a list |
| 271 | if (false === strpos($part, ',')) { |
| 272 | $satisfied = $field->isSatisfiedBy($nextRun, $part, $invert); |
| 273 | } else { |
| 274 | foreach (array_map('trim', explode(',', $part)) as $listPart) { |
| 275 | if ($field->isSatisfiedBy($nextRun, $listPart, $invert)) { |
| 276 | $satisfied = true; |
| 277 | break; |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | // If the field is not satisfied, then start over |
| 282 | if (!$satisfied) { |
| 283 | $field->increment($nextRun, $invert, $part); |
| 284 | continue 2; |
| 285 | } |
| 286 | } |
| 287 | // Skip this match if needed |
| 288 | if ((!$allowCurrentDate && $nextRun == $currentDate) || --$nth > -1) { |
| 289 | $this->fieldFactory->getField(self::MINUTE)->increment($nextRun, $invert, $parts[self::MINUTE] ?? null); |
| 290 | continue; |
| 291 | } |
| 292 | return $nextRun; |
| 293 | } |
| 294 | // @codeCoverageIgnoreStart |
| 295 | throw new RuntimeException('Impossible CRON expression'); |
| 296 | // @codeCoverageIgnoreEnd |
| 297 | } |
| 298 | protected function determineTimeZone($currentTime, ?string $timeZone): string |
| 299 | { |
| 300 | if (null !== $timeZone) { |
| 301 | return $timeZone; |
| 302 | } |
| 303 | if ($currentTime instanceof DateTimeInterface) { |
| 304 | return $currentTime->getTimezone()->getName(); |
| 305 | } |
| 306 | return date_default_timezone_get(); |
| 307 | } |
| 308 | } |
| 309 |