No Description

CronExpression.php 11KB

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