MinutesField.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. declare(strict_types=1);
  3. namespace Cron;
  4. use DateTimeInterface;
  5. /**
  6. * Minutes field. Allows: * , / -.
  7. */
  8. class MinutesField extends AbstractField
  9. {
  10. /**
  11. * {@inheritdoc}
  12. */
  13. protected $rangeStart = 0;
  14. /**
  15. * {@inheritdoc}
  16. */
  17. protected $rangeEnd = 59;
  18. /**
  19. * {@inheritdoc}
  20. */
  21. public function isSatisfiedBy(DateTimeInterface $date, $value):bool
  22. {
  23. if ($value == '?') {
  24. return true;
  25. }
  26. return $this->isSatisfied((int)$date->format('i'), $value);
  27. }
  28. /**
  29. * {@inheritdoc}
  30. * {@inheritDoc}
  31. *
  32. * @param \DateTime|\DateTimeImmutable $date
  33. * @param string|null $parts
  34. */
  35. public function increment(DateTimeInterface &$date, $invert = false, $parts = null): FieldInterface
  36. {
  37. if (is_null($parts)) {
  38. $date = $date->modify(($invert ? '-' : '+') . '1 minute');
  39. return $this;
  40. }
  41. $parts = false !== strpos($parts, ',') ? explode(',', $parts) : [$parts];
  42. $minutes = [];
  43. foreach ($parts as $part) {
  44. $minutes = array_merge($minutes, $this->getRangeForExpression($part, 59));
  45. }
  46. $current_minute = $date->format('i');
  47. $position = $invert ? \count($minutes) - 1 : 0;
  48. if (\count($minutes) > 1) {
  49. for ($i = 0; $i < \count($minutes) - 1; ++$i) {
  50. if ((!$invert && $current_minute >= $minutes[$i] && $current_minute < $minutes[$i + 1]) ||
  51. ($invert && $current_minute > $minutes[$i] && $current_minute <= $minutes[$i + 1])) {
  52. $position = $invert ? $i : $i + 1;
  53. break;
  54. }
  55. }
  56. }
  57. if ((!$invert && $current_minute >= $minutes[$position]) || ($invert && $current_minute <= $minutes[$position])) {
  58. $date = $date->modify(($invert ? '-' : '+') . '1 hour');
  59. $date = $date->setTime((int) $date->format('H'), $invert ? 59 : 0);
  60. } else {
  61. $date = $date->setTime((int) $date->format('H'), (int) $minutes[$position]);
  62. }
  63. return $this;
  64. }
  65. }