CronExpression.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. namespace Cron;
  3. use DateTime;
  4. use DateTimeImmutable;
  5. use DateTimeZone;
  6. use Exception;
  7. use InvalidArgumentException;
  8. use RuntimeException;
  9. /**
  10. * CRON expression parser that can determine whether or not a CRON expression is
  11. * due to run, the next run date and previous run date of a CRON expression.
  12. * The determinations made by this class are accurate if checked run once per
  13. * minute (seconds are dropped from date time comparisons).
  14. *
  15. * Schedule parts must map to:
  16. * minute [0-59], hour [0-23], day of month, month [1-12|JAN-DEC], day of week
  17. * [1-7|MON-SUN], and an optional year.
  18. *
  19. * @link http://en.wikipedia.org/wiki/Cron
  20. */
  21. class CronExpression
  22. {
  23. const MINUTE = 0;
  24. const HOUR = 1;
  25. const DAY = 2;
  26. const MONTH = 3;
  27. const WEEKDAY = 4;
  28. const YEAR = 5;
  29. /**
  30. * @var array CRON expression parts
  31. */
  32. private $cronParts;
  33. /**
  34. * @var FieldFactory CRON field factory
  35. */
  36. private $fieldFactory;
  37. /**
  38. * @var int Max iteration count when searching for next run date
  39. */
  40. private $maxIterationCount = 1000;
  41. /**
  42. * @var array Order in which to test of cron parts
  43. */
  44. private static $order = array(self::YEAR, self::MONTH, self::DAY, self::WEEKDAY, self::HOUR, self::MINUTE);
  45. /**
  46. * Factory method to create a new CronExpression.
  47. *
  48. * @param string $expression The CRON expression to create. There are
  49. * several special predefined values which can be used to substitute the
  50. * CRON expression:
  51. *
  52. * `@yearly`, `@annually` - Run once a year, midnight, Jan. 1 - 0 0 1 1 *
  53. * `@monthly` - Run once a month, midnight, first of month - 0 0 1 * *
  54. * `@weekly` - Run once a week, midnight on Sun - 0 0 * * 0
  55. * `@daily` - Run once a day, midnight - 0 0 * * *
  56. * `@hourly` - Run once an hour, first minute - 0 * * * *
  57. * @param FieldFactory $fieldFactory Field factory to use
  58. *
  59. * @return CronExpression
  60. */
  61. public static function factory($expression, FieldFactory $fieldFactory = null)
  62. {
  63. $mappings = array(
  64. '@yearly' => '0 0 1 1 *',
  65. '@annually' => '0 0 1 1 *',
  66. '@monthly' => '0 0 1 * *',
  67. '@weekly' => '0 0 * * 0',
  68. '@daily' => '0 0 * * *',
  69. '@hourly' => '0 * * * *'
  70. );
  71. if (isset($mappings[$expression])) {
  72. $expression = $mappings[$expression];
  73. }
  74. return new static($expression, $fieldFactory ?: new FieldFactory());
  75. }
  76. /**
  77. * Validate a CronExpression.
  78. *
  79. * @param string $expression The CRON expression to validate.
  80. *
  81. * @return bool True if a valid CRON expression was passed. False if not.
  82. * @see \Cron\CronExpression::factory
  83. */
  84. public static function isValidExpression($expression)
  85. {
  86. try {
  87. self::factory($expression);
  88. } catch (InvalidArgumentException $e) {
  89. return false;
  90. }
  91. return true;
  92. }
  93. /**
  94. * Parse a CRON expression
  95. *
  96. * @param string $expression CRON expression (e.g. '8 * * * *')
  97. * @param FieldFactory $fieldFactory Factory to create cron fields
  98. */
  99. public function __construct($expression, FieldFactory $fieldFactory)
  100. {
  101. $this->fieldFactory = $fieldFactory;
  102. $this->setExpression($expression);
  103. }
  104. /**
  105. * Set or change the CRON expression
  106. *
  107. * @param string $value CRON expression (e.g. 8 * * * *)
  108. *
  109. * @return CronExpression
  110. * @throws \InvalidArgumentException if not a valid CRON expression
  111. */
  112. public function setExpression($value)
  113. {
  114. $this->cronParts = preg_split('/\s/', $value, -1, PREG_SPLIT_NO_EMPTY);
  115. if (count($this->cronParts) < 5) {
  116. throw new InvalidArgumentException(
  117. $value . ' is not a valid CRON expression'
  118. );
  119. }
  120. foreach ($this->cronParts as $position => $part) {
  121. $this->setPart($position, $part);
  122. }
  123. return $this;
  124. }
  125. /**
  126. * Set part of the CRON expression
  127. *
  128. * @param int $position The position of the CRON expression to set
  129. * @param string $value The value to set
  130. *
  131. * @return CronExpression
  132. * @throws \InvalidArgumentException if the value is not valid for the part
  133. */
  134. public function setPart($position, $value)
  135. {
  136. if (!$this->fieldFactory->getField($position)->validate($value)) {
  137. throw new InvalidArgumentException(
  138. 'Invalid CRON field value ' . $value . ' at position ' . $position
  139. );
  140. }
  141. $this->cronParts[$position] = $value;
  142. return $this;
  143. }
  144. /**
  145. * Set max iteration count for searching next run dates
  146. *
  147. * @param int $maxIterationCount Max iteration count when searching for next run date
  148. *
  149. * @return CronExpression
  150. */
  151. public function setMaxIterationCount($maxIterationCount)
  152. {
  153. $this->maxIterationCount = $maxIterationCount;
  154. return $this;
  155. }
  156. /**
  157. * Get a next run date relative to the current date or a specific date
  158. *
  159. * @param string|\DateTime $currentTime Relative calculation date
  160. * @param int $nth Number of matches to skip before returning a
  161. * matching next run date. 0, the default, will return the current
  162. * date and time if the next run date falls on the current date and
  163. * time. Setting this value to 1 will skip the first match and go to
  164. * the second match. Setting this value to 2 will skip the first 2
  165. * matches and so on.
  166. * @param bool $allowCurrentDate Set to TRUE to return the current date if
  167. * it matches the cron expression.
  168. * @param null|string $timeZone Timezone to use instead of the system default
  169. *
  170. * @return \DateTime
  171. * @throws \RuntimeException on too many iterations
  172. */
  173. public function getNextRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false, $timeZone = null)
  174. {
  175. return $this->getRunDate($currentTime, $nth, false, $allowCurrentDate, $timeZone);
  176. }
  177. /**
  178. * Get a previous run date relative to the current date or a specific date
  179. *
  180. * @param string|\DateTime $currentTime Relative calculation date
  181. * @param int $nth Number of matches to skip before returning
  182. * @param bool $allowCurrentDate Set to TRUE to return the
  183. * current date if it matches the cron expression
  184. * @param null|string $timeZone Timezone to use instead of the system default
  185. *
  186. * @return \DateTime
  187. * @throws \RuntimeException on too many iterations
  188. * @see \Cron\CronExpression::getNextRunDate
  189. */
  190. public function getPreviousRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false, $timeZone = null)
  191. {
  192. return $this->getRunDate($currentTime, $nth, true, $allowCurrentDate, $timeZone);
  193. }
  194. /**
  195. * Get multiple run dates starting at the current date or a specific date
  196. *
  197. * @param int $total Set the total number of dates to calculate
  198. * @param string|\DateTime $currentTime Relative calculation date
  199. * @param bool $invert Set to TRUE to retrieve previous dates
  200. * @param bool $allowCurrentDate Set to TRUE to return the
  201. * current date if it matches the cron expression
  202. * @param null|string $timeZone Timezone to use instead of the system default
  203. *
  204. * @return array Returns an array of run dates
  205. */
  206. public function getMultipleRunDates($total, $currentTime = 'now', $invert = false, $allowCurrentDate = false, $timeZone = null)
  207. {
  208. $matches = array();
  209. for ($i = 0; $i < max(0, $total); $i++) {
  210. try {
  211. $matches[] = $this->getRunDate($currentTime, $i, $invert, $allowCurrentDate, $timeZone);
  212. } catch (RuntimeException $e) {
  213. break;
  214. }
  215. }
  216. return $matches;
  217. }
  218. /**
  219. * Get all or part of the CRON expression
  220. *
  221. * @param string $part Specify the part to retrieve or NULL to get the full
  222. * cron schedule string.
  223. *
  224. * @return string|null Returns the CRON expression, a part of the
  225. * CRON expression, or NULL if the part was specified but not found
  226. */
  227. public function getExpression($part = null)
  228. {
  229. if (null === $part) {
  230. return implode(' ', $this->cronParts);
  231. } elseif (array_key_exists($part, $this->cronParts)) {
  232. return $this->cronParts[$part];
  233. }
  234. return null;
  235. }
  236. /**
  237. * Helper method to output the full expression.
  238. *
  239. * @return string Full CRON expression
  240. */
  241. public function __toString()
  242. {
  243. return $this->getExpression();
  244. }
  245. /**
  246. * Determine if the cron is due to run based on the current date or a
  247. * specific date. This method assumes that the current number of
  248. * seconds are irrelevant, and should be called once per minute.
  249. *
  250. * @param string|\DateTime $currentTime Relative calculation date
  251. * @param null|string $timeZone Timezone to use instead of the system default
  252. *
  253. * @return bool Returns TRUE if the cron is due to run or FALSE if not
  254. */
  255. public function isDue($currentTime = 'now', $timeZone = null)
  256. {
  257. if (is_null($timeZone)) {
  258. $timeZone = date_default_timezone_get();
  259. }
  260. if ('now' === $currentTime) {
  261. $currentDate = date('Y-m-d H:i');
  262. $currentTime = strtotime($currentDate);
  263. } elseif ($currentTime instanceof DateTime) {
  264. $currentDate = clone $currentTime;
  265. // Ensure time in 'current' timezone is used
  266. $currentDate->setTimezone(new DateTimeZone($timeZone));
  267. $currentDate = $currentDate->format('Y-m-d H:i');
  268. $currentTime = strtotime($currentDate);
  269. } elseif ($currentTime instanceof DateTimeImmutable) {
  270. $currentDate = DateTime::createFromFormat('U', $currentTime->format('U'));
  271. $currentDate->setTimezone(new DateTimeZone($timeZone));
  272. $currentDate = $currentDate->format('Y-m-d H:i');
  273. $currentTime = strtotime($currentDate);
  274. } else {
  275. $currentTime = new DateTime($currentTime);
  276. $currentTime->setTime($currentTime->format('H'), $currentTime->format('i'), 0);
  277. $currentDate = $currentTime->format('Y-m-d H:i');
  278. $currentTime = $currentTime->getTimeStamp();
  279. }
  280. try {
  281. return $this->getNextRunDate($currentDate, 0, true)->getTimestamp() == $currentTime;
  282. } catch (Exception $e) {
  283. return false;
  284. }
  285. }
  286. /**
  287. * Get the next or previous run date of the expression relative to a date
  288. *
  289. * @param string|\DateTime $currentTime Relative calculation date
  290. * @param int $nth Number of matches to skip before returning
  291. * @param bool $invert Set to TRUE to go backwards in time
  292. * @param bool $allowCurrentDate Set to TRUE to return the
  293. * current date if it matches the cron expression
  294. * @param string|null $timeZone Timezone to use instead of the system default
  295. *
  296. * @return \DateTime
  297. * @throws \RuntimeException on too many iterations
  298. */
  299. protected function getRunDate($currentTime = null, $nth = 0, $invert = false, $allowCurrentDate = false, $timeZone = null)
  300. {
  301. if (is_null($timeZone)) {
  302. $timeZone = date_default_timezone_get();
  303. }
  304. if ($currentTime instanceof DateTime) {
  305. $currentDate = clone $currentTime;
  306. } elseif ($currentTime instanceof DateTimeImmutable) {
  307. $currentDate = DateTime::createFromFormat('U', $currentTime->format('U'));
  308. $currentDate->setTimezone($currentTime->getTimezone());
  309. } else {
  310. $currentDate = new DateTime($currentTime ?: 'now');
  311. $currentDate->setTimezone(new DateTimeZone($timeZone));
  312. }
  313. $currentDate->setTime($currentDate->format('H'), $currentDate->format('i'), 0);
  314. $nextRun = clone $currentDate;
  315. $nth = (int) $nth;
  316. // We don't have to satisfy * or null fields
  317. $parts = array();
  318. $fields = array();
  319. foreach (self::$order as $position) {
  320. $part = $this->getExpression($position);
  321. if (null === $part || '*' === $part) {
  322. continue;
  323. }
  324. $parts[$position] = $part;
  325. $fields[$position] = $this->fieldFactory->getField($position);
  326. }
  327. // Set a hard limit to bail on an impossible date
  328. for ($i = 0; $i < $this->maxIterationCount; $i++) {
  329. foreach ($parts as $position => $part) {
  330. $satisfied = false;
  331. // Get the field object used to validate this part
  332. $field = $fields[$position];
  333. // Check if this is singular or a list
  334. if (strpos($part, ',') === false) {
  335. $satisfied = $field->isSatisfiedBy($nextRun, $part);
  336. } else {
  337. foreach (array_map('trim', explode(',', $part)) as $listPart) {
  338. if ($field->isSatisfiedBy($nextRun, $listPart)) {
  339. $satisfied = true;
  340. break;
  341. }
  342. }
  343. }
  344. // If the field is not satisfied, then start over
  345. if (!$satisfied) {
  346. $field->increment($nextRun, $invert, $part);
  347. continue 2;
  348. }
  349. }
  350. // Skip this match if needed
  351. if ((!$allowCurrentDate && $nextRun == $currentDate) || --$nth > -1) {
  352. $this->fieldFactory->getField(0)->increment($nextRun, $invert, isset($parts[0]) ? $parts[0] : null);
  353. continue;
  354. }
  355. return $nextRun;
  356. }
  357. // @codeCoverageIgnoreStart
  358. throw new RuntimeException('Impossible CRON expression');
  359. // @codeCoverageIgnoreEnd
  360. }
  361. }