You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

390 lines
14 KiB

  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. *
  169. * @return \DateTime
  170. * @throws \RuntimeException on too many iterations
  171. */
  172. public function getNextRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false)
  173. {
  174. return $this->getRunDate($currentTime, $nth, false, $allowCurrentDate);
  175. }
  176. /**
  177. * Get a previous run date relative to the current date or a specific date
  178. *
  179. * @param string|\DateTime $currentTime Relative calculation date
  180. * @param int $nth Number of matches to skip before returning
  181. * @param bool $allowCurrentDate Set to TRUE to return the
  182. * current date if it matches the cron expression
  183. *
  184. * @return \DateTime
  185. * @throws \RuntimeException on too many iterations
  186. * @see \Cron\CronExpression::getNextRunDate
  187. */
  188. public function getPreviousRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false)
  189. {
  190. return $this->getRunDate($currentTime, $nth, true, $allowCurrentDate);
  191. }
  192. /**
  193. * Get multiple run dates starting at the current date or a specific date
  194. *
  195. * @param int $total Set the total number of dates to calculate
  196. * @param string|\DateTime $currentTime Relative calculation date
  197. * @param bool $invert Set to TRUE to retrieve previous dates
  198. * @param bool $allowCurrentDate Set to TRUE to return the
  199. * current date if it matches the cron expression
  200. *
  201. * @return array Returns an array of run dates
  202. */
  203. public function getMultipleRunDates($total, $currentTime = 'now', $invert = false, $allowCurrentDate = false)
  204. {
  205. $matches = array();
  206. for ($i = 0; $i < max(0, $total); $i++) {
  207. try {
  208. $matches[] = $this->getRunDate($currentTime, $i, $invert, $allowCurrentDate);
  209. } catch (RuntimeException $e) {
  210. break;
  211. }
  212. }
  213. return $matches;
  214. }
  215. /**
  216. * Get all or part of the CRON expression
  217. *
  218. * @param string $part Specify the part to retrieve or NULL to get the full
  219. * cron schedule string.
  220. *
  221. * @return string|null Returns the CRON expression, a part of the
  222. * CRON expression, or NULL if the part was specified but not found
  223. */
  224. public function getExpression($part = null)
  225. {
  226. if (null === $part) {
  227. return implode(' ', $this->cronParts);
  228. } elseif (array_key_exists($part, $this->cronParts)) {
  229. return $this->cronParts[$part];
  230. }
  231. return null;
  232. }
  233. /**
  234. * Helper method to output the full expression.
  235. *
  236. * @return string Full CRON expression
  237. */
  238. public function __toString()
  239. {
  240. return $this->getExpression();
  241. }
  242. /**
  243. * Determine if the cron is due to run based on the current date or a
  244. * specific date. This method assumes that the current number of
  245. * seconds are irrelevant, and should be called once per minute.
  246. *
  247. * @param string|\DateTime $currentTime Relative calculation date
  248. *
  249. * @return bool Returns TRUE if the cron is due to run or FALSE if not
  250. */
  251. public function isDue($currentTime = 'now')
  252. {
  253. if ('now' === $currentTime) {
  254. $currentDate = date('Y-m-d H:i');
  255. $currentTime = strtotime($currentDate);
  256. } elseif ($currentTime instanceof DateTime) {
  257. $currentDate = clone $currentTime;
  258. // Ensure time in 'current' timezone is used
  259. $currentDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
  260. $currentDate = $currentDate->format('Y-m-d H:i');
  261. $currentTime = strtotime($currentDate);
  262. } elseif ($currentTime instanceof DateTimeImmutable) {
  263. $currentDate = DateTime::createFromFormat('U', $currentTime->format('U'));
  264. $currentDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
  265. $currentDate = $currentDate->format('Y-m-d H:i');
  266. $currentTime = strtotime($currentDate);
  267. } else {
  268. $currentTime = new DateTime($currentTime);
  269. $currentTime->setTime($currentTime->format('H'), $currentTime->format('i'), 0);
  270. $currentDate = $currentTime->format('Y-m-d H:i');
  271. $currentTime = $currentTime->getTimeStamp();
  272. }
  273. try {
  274. return $this->getNextRunDate($currentDate, 0, true)->getTimestamp() == $currentTime;
  275. } catch (Exception $e) {
  276. return false;
  277. }
  278. }
  279. /**
  280. * Get the next or previous run date of the expression relative to a date
  281. *
  282. * @param string|\DateTime $currentTime Relative calculation date
  283. * @param int $nth Number of matches to skip before returning
  284. * @param bool $invert Set to TRUE to go backwards in time
  285. * @param bool $allowCurrentDate Set to TRUE to return the
  286. * current date if it matches the cron expression
  287. *
  288. * @return \DateTime
  289. * @throws \RuntimeException on too many iterations
  290. */
  291. protected function getRunDate($currentTime = null, $nth = 0, $invert = false, $allowCurrentDate = false)
  292. {
  293. if ($currentTime instanceof DateTime) {
  294. $currentDate = clone $currentTime;
  295. } elseif ($currentTime instanceof DateTimeImmutable) {
  296. $currentDate = DateTime::createFromFormat('U', $currentTime->format('U'));
  297. $currentDate->setTimezone($currentTime->getTimezone());
  298. } else {
  299. $currentDate = new DateTime($currentTime ?: 'now');
  300. $currentDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
  301. }
  302. $currentDate->setTime($currentDate->format('H'), $currentDate->format('i'), 0);
  303. $nextRun = clone $currentDate;
  304. $nth = (int) $nth;
  305. // We don't have to satisfy * or null fields
  306. $parts = array();
  307. $fields = array();
  308. foreach (self::$order as $position) {
  309. $part = $this->getExpression($position);
  310. if (null === $part || '*' === $part) {
  311. continue;
  312. }
  313. $parts[$position] = $part;
  314. $fields[$position] = $this->fieldFactory->getField($position);
  315. }
  316. // Set a hard limit to bail on an impossible date
  317. for ($i = 0; $i < $this->maxIterationCount; $i++) {
  318. foreach ($parts as $position => $part) {
  319. $satisfied = false;
  320. // Get the field object used to validate this part
  321. $field = $fields[$position];
  322. // Check if this is singular or a list
  323. if (strpos($part, ',') === false) {
  324. $satisfied = $field->isSatisfiedBy($nextRun, $part);
  325. } else {
  326. foreach (array_map('trim', explode(',', $part)) as $listPart) {
  327. if ($field->isSatisfiedBy($nextRun, $listPart)) {
  328. $satisfied = true;
  329. break;
  330. }
  331. }
  332. }
  333. // If the field is not satisfied, then start over
  334. if (!$satisfied) {
  335. $field->increment($nextRun, $invert, $part);
  336. continue 2;
  337. }
  338. }
  339. // Skip this match if needed
  340. if ((!$allowCurrentDate && $nextRun == $currentDate) || --$nth > -1) {
  341. $this->fieldFactory->getField(0)->increment($nextRun, $invert, isset($parts[0]) ? $parts[0] : null);
  342. continue;
  343. }
  344. return $nextRun;
  345. }
  346. // @codeCoverageIgnoreStart
  347. throw new RuntimeException('Impossible CRON expression');
  348. // @codeCoverageIgnoreEnd
  349. }
  350. }