|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of the PHP-CRON-EXPR package. |
| 7 | + * |
| 8 | + * (c) Jitendra Adhikari <jiten.adhikary@gmail.com> |
| 9 | + * <https://github.com/adhocore> |
| 10 | + * |
| 11 | + * Licensed under MIT license. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Ahc\Cron; |
| 15 | + |
| 16 | +class Normalizer |
| 17 | +{ |
| 18 | + const YEARLY = '@yearly'; |
| 19 | + const ANNUALLY = '@annually'; |
| 20 | + const MONTHLY = '@monthly'; |
| 21 | + const WEEKLY = '@weekly'; |
| 22 | + const DAILY = '@daily'; |
| 23 | + const HOURLY = '@hourly'; |
| 24 | + const ALWAYS = '@always'; |
| 25 | + const FIVE_MIN = '@5minutes'; |
| 26 | + const TEN_MIN = '@10minutes'; |
| 27 | + const FIFTEEN_MIN = '@15minutes'; |
| 28 | + const THIRTY_MIN = '@30minutes'; |
| 29 | + |
| 30 | + protected static $expressions = [ |
| 31 | + self::YEARLY => '0 0 1 1 *', |
| 32 | + self::ANNUALLY => '0 0 1 1 *', |
| 33 | + self::MONTHLY => '0 0 1 * *', |
| 34 | + self::WEEKLY => '0 0 * * 0', |
| 35 | + self::DAILY => '0 0 * * *', |
| 36 | + self::HOURLY => '0 * * * *', |
| 37 | + self::ALWAYS => '* * * * *', |
| 38 | + self::FIVE_MIN => '*/5 * * * *', |
| 39 | + self::TEN_MIN => '*/10 * * * *', |
| 40 | + self::FIFTEEN_MIN => '*/15 * * * *', |
| 41 | + self::THIRTY_MIN => '0,30 * * * *', |
| 42 | + ]; |
| 43 | + |
| 44 | + protected static $literals = [ |
| 45 | + 'sun' => 0, |
| 46 | + 'mon' => 1, |
| 47 | + 'tue' => 2, |
| 48 | + 'wed' => 3, |
| 49 | + 'thu' => 4, |
| 50 | + 'fri' => 5, |
| 51 | + 'sat' => 6, |
| 52 | + |
| 53 | + 'jan' => 1, |
| 54 | + 'feb' => 2, |
| 55 | + 'mar' => 3, |
| 56 | + 'apr' => 4, |
| 57 | + 'may' => 5, |
| 58 | + 'jun' => 6, |
| 59 | + 'jul' => 7, |
| 60 | + 'aug' => 8, |
| 61 | + 'sep' => 9, |
| 62 | + 'oct' => 10, |
| 63 | + 'nov' => 11, |
| 64 | + 'dec' => 12, |
| 65 | + ]; |
| 66 | + |
| 67 | + public function normalizeExpr(string $expr): string |
| 68 | + { |
| 69 | + $expr = \trim($expr); |
| 70 | + |
| 71 | + if (isset(static::$expressions[$expr])) { |
| 72 | + return static::$expressions[$expr]; |
| 73 | + } |
| 74 | + |
| 75 | + $expr = \preg_replace('~\s+~', ' ', $expr); |
| 76 | + $count = \substr_count($expr, ' '); |
| 77 | + |
| 78 | + if ($count < 4 || $count > 5) { |
| 79 | + throw new \UnexpectedValueException( |
| 80 | + 'Cron $expr should have 5 or 6 segments delimited by space' |
| 81 | + ); |
| 82 | + } |
| 83 | + |
| 84 | + return \str_ireplace(\array_keys(static::$literals), \array_values(static::$literals), $expr); |
| 85 | + } |
| 86 | +} |
0 commit comments