Debian Codegraph @

vendor/ipl/scheduler/src/Cron.php

raw
1 <?php
2
3 namespace ipl\Scheduler;
4
5 use Cron\CronExpression;
6 use DateTime;
7 use DateTimeInterface;
8 use DateTimeZone;
9 use InvalidArgumentException;
10 use ipl\Scheduler\Contract\Frequency;
11
12 use function ipl\Stdlib\get_php_type;
13
14 /**
15 * Cron-expression-based scheduling frequency
16 *
17 * Schedules a task based on a standard five-field cron expression (minute, hour, day-of-month, month, day-of-week).
18 * Supports optional start and end bounds via {@see Cron::startAt()} and {@see Cron::endAt()}.
19 */
20 class Cron implements Frequency
21 {
22 /** @var int Position of the minute field in the cron expression */
23 public const PART_MINUTE = 0;
24
25 /** @var int Position of the hour field in the cron expression */
26 public const PART_HOUR = 1;
27
28 /** @var int Position of the day-of-month field in the cron expression */
29 public const PART_DAY = 2;
30
31 /** @var int Position of the month field in the cron expression */
32 public const PART_MONTH = 3;
33
34 /** @var int Position of the day-of-week field in the cron expression */
35 public const PART_WEEKDAY = 4;
36
37 protected CronExpression $cron;
38
39 /** @var ?DateTime Start time of this frequency */
40 protected ?DateTime $start = null;
41
42 /** @var ?DateTime End time of this frequency */
43 protected ?DateTime $end = null;
44
45 /** @var string String representation of the cron expression */
46 protected string $expression;
47
48 /**
49 * Create frequency from the specified cron expression
50 *
51 * @param string $expression
52 *
53 * @throws InvalidArgumentException If expression is not a valid cron expression
54 */
55 public function __construct(string $expression)
56 {
57 $this->cron = new CronExpression($expression);
58 $this->expression = $expression;
59 }
60
61 /**
62 * Create a {@see Cron} instance from its stored JSON representation
63 *
64 * The JSON must decode to an array with at least an `expression` key, and optionally `start` and `end` keys
65 * formatted according to {@see Frequency::SERIALIZED_DATETIME_FORMAT}.
66 *
67 * @param string $json
68 *
69 * @return static
70 *
71 * @throws InvalidArgumentException If the JSON does not decode to an array
72 */
73 public static function fromJson(string $json): static
74 {
75 $data = json_decode($json, true);
76 if (! is_array($data)) {
77 throw new InvalidArgumentException(
78 sprintf(
79 '%s expects json decoded value to be an array, got %s instead',
80 __METHOD__,
81 get_php_type($data)
82 )
83 );
84 }
85
86 $self = new static($data['expression']);
87 if (isset($data['start'])) {
88 $self->startAt(new DateTime($data['start']));
89 }
90
91 if (isset($data['end'])) {
92 $self->endAt(new DateTime($data['end']));
93 }
94
95 return $self;
96 }
97
98 /**
99 * Get whether the given cron expression is valid
100 *
101 * @param string $expression
102 *
103 * @return bool
104 */
105 public static function isValid(string $expression): bool
106 {
107 return CronExpression::isValidExpression($expression);
108 }
109
110 public function isDue(DateTimeInterface $dateTime): bool
111 {
112 if ($this->isExpired($dateTime) || $dateTime < $this->start) {
113 return false;
114 }
115
116 return $this->cron->isDue($dateTime);
117 }
118
119 /**
120 * Get the next due date relative to the given time
121 *
122 * Returns the start time if the given time is before the start, or the end time if the frequency is expired.
123 *
124 * @param DateTimeInterface $dateTime
125 *
126 * @return DateTimeInterface
127 */
128 public function getNextDue(DateTimeInterface $dateTime): DateTimeInterface
129 {
130 if ($this->isExpired($dateTime)) {
131 return $this->end;
132 }
133
134 if ($dateTime < $this->start) {
135 return $this->start;
136 }
137
138 return $this->cron->getNextRunDate($dateTime);
139 }
140
141 public function isExpired(DateTimeInterface $dateTime): bool
142 {
143 return $this->end !== null && $this->end < $dateTime;
144 }
145
146 public function getStart(): ?DateTimeInterface
147 {
148 return $this->start;
149 }
150
151 public function getEnd(): ?DateTimeInterface
152 {
153 return $this->end;
154 }
155
156 /**
157 * Set the start time of this frequency
158 *
159 * @param DateTimeInterface $start
160 *
161 * @return $this
162 */
163 public function startAt(DateTimeInterface $start): static
164 {
165 $this->start = DateTime::createFromInterface($start);
166 $this->start->setTimezone(new DateTimeZone(date_default_timezone_get()));
167
168 return $this;
169 }
170
171 /**
172 * Set the end time of this frequency
173 *
174 * @param DateTimeInterface $end
175 *
176 * @return $this
177 */
178 public function endAt(DateTimeInterface $end): static
179 {
180 $this->end = DateTime::createFromInterface($end);
181 $this->end->setTimezone(new DateTimeZone(date_default_timezone_get()));
182
183 return $this;
184 }
185
186 /**
187 * Get the configured cron expression
188 *
189 * @return string
190 */
191 public function getExpression(): string
192 {
193 return $this->expression;
194 }
195
196 /**
197 * Get the given part of the underlying cron expression
198 *
199 * @param int $part One of the classes `PART_*` constants
200 *
201 * @return string
202 *
203 * @throws InvalidArgumentException If the given part is invalid
204 */
205 public function getPart(int $part): string
206 {
207 $value = $this->cron->getExpression($part);
208 if ($value === null) {
209 throw new InvalidArgumentException(sprintf('Invalid expression part specified: %d', $part));
210 }
211
212 return $value;
213 }
214
215 /**
216 * Get the parts of the underlying cron expression as an array
217 *
218 * @return string[]
219 */
220 public function getParts(): array
221 {
222 return $this->cron->getParts();
223 }
224
225 /**
226 * Serialize this frequency to a JSON-encodable array
227 *
228 * Always includes the `expression` key; `start` and `end` are included only when set,
229 * formatted according to {@see Frequency::SERIALIZED_DATETIME_FORMAT}.
230 *
231 * @return array<string, string>
232 */
233 public function jsonSerialize(): array
234 {
235 $data = ['expression' => $this->getExpression()];
236 if ($this->start) {
237 $data['start'] = $this->start->format(static::SERIALIZED_DATETIME_FORMAT);
238 }
239
240 if ($this->end) {
241 $data['end'] = $this->end->format(static::SERIALIZED_DATETIME_FORMAT);
242 }
243
244 return $data;
245 }
246 }