HoursField.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace Cron;
  3. use DateTime;
  4. use DateTimeZone;
  5. /**
  6. * Hours field. Allows: * , / -
  7. */
  8. class HoursField extends AbstractField
  9. {
  10. protected $rangeStart = 0;
  11. protected $rangeEnd = 23;
  12. public function isSatisfiedBy(DateTime $date, $value)
  13. {
  14. return $this->isSatisfied($date->format('H'), $value);
  15. }
  16. public function increment(DateTime $date, $invert = false, $parts = null)
  17. {
  18. // Change timezone to UTC temporarily. This will
  19. // allow us to go back or forwards and hour even
  20. // if DST will be changed between the hours.
  21. if (is_null($parts) || $parts == '*') {
  22. $timezone = $date->getTimezone();
  23. $date->setTimezone(new DateTimeZone('UTC'));
  24. if ($invert) {
  25. $date->modify('-1 hour');
  26. } else {
  27. $date->modify('+1 hour');
  28. }
  29. $date->setTimezone($timezone);
  30. $date->setTime($date->format('H'), $invert ? 59 : 0);
  31. return $this;
  32. }
  33. $parts = strpos($parts, ',') !== false ? explode(',', $parts) : array($parts);
  34. $hours = array();
  35. foreach ($parts as $part) {
  36. $hours = array_merge($hours, $this->getRangeForExpression($part, 23));
  37. }
  38. $current_hour = $date->format('H');
  39. $position = $invert ? count($hours) - 1 : 0;
  40. if (count($hours) > 1) {
  41. for ($i = 0; $i < count($hours) - 1; $i++) {
  42. if ((!$invert && $current_hour >= $hours[$i] && $current_hour < $hours[$i + 1]) ||
  43. ($invert && $current_hour > $hours[$i] && $current_hour <= $hours[$i + 1])) {
  44. $position = $invert ? $i : $i + 1;
  45. break;
  46. }
  47. }
  48. }
  49. $hour = $hours[$position];
  50. if ((!$invert && $date->format('H') >= $hour) || ($invert && $date->format('H') <= $hour)) {
  51. $date->modify(($invert ? '-' : '+') . '1 day');
  52. $date->setTime($invert ? 23 : 0, $invert ? 59 : 0);
  53. }
  54. else {
  55. $date->setTime($hour, $invert ? 59 : 0);
  56. }
  57. return $this;
  58. }
  59. }