Debian Codegraph @

vendor/ipl/scheduler/src/RRule.php

raw
1 <?php
2
3 namespace ipl\Scheduler;
4
5 use BadMethodCallException;
6 use DateTime;
7 use DateTimeInterface;
8 use DateTimeZone;
9 use Generator;
10 use InvalidArgumentException;
11 use ipl\Scheduler\Contract\Frequency;
12 use Recurr\Exception\InvalidRRule;
13 use Recurr\Rule as RecurrRule;
14 use Recurr\Transformer\ArrayTransformer;
15 use Recurr\Transformer\ArrayTransformerConfig;
16 use Recurr\Transformer\Constraint\AfterConstraint;
17 use Recurr\Transformer\Constraint\BetweenConstraint;
18 use stdClass;
19
20 use function ipl\Stdlib\get_php_type;
21
22 /**
23 * iCalendar recurrence rule-based scheduling frequency
24 *
25 * Schedules a task based on a recurrence rule in iCalendar format (RFC 5545).
26 * Supports common frequencies via the {@see RRule::MINUTELY}, {@see RRule::HOURLY},
27 * {@see RRule::DAILY}, {@see RRule::WEEKLY}, {@see RRule::MONTHLY}, and
28 * {@see RRule::YEARLY} constants, or arbitrary RRULE strings for fine-grained control.
29 * Supports optional start and end bounds via {@see RRule::startAt()} and {@see RRule::endAt()},
30 * and an optional display timezone via {@see RRule::setTimezone()}.
31 */
32 class RRule implements Frequency
33 {
34 /** @var string Run once a year */
35 public const YEARLY = 'YEARLY';
36
37 /** @var string Run every 3 month starting from the given start time */
38 public const QUARTERLY = 'QUARTERLY';
39
40 /** @var string Run once a month */
41 public const MONTHLY = 'MONTHLY';
42
43 /** @var string Run once a week based on the specified start time */
44 public const WEEKLY = 'WEEKLY';
45
46 /** @var string Run once a day at the specified start time */
47 public const DAILY = 'DAILY';
48
49 /** @var string Run once an hour */
50 public const HOURLY = 'HOURLY';
51
52 /** @var string Run once a minute */
53 public const MINUTELY = 'MINUTELY';
54
55 /** @var int Default limit of the recurrences to be generated by the transformer */
56 private const DEFAULT_LIMIT = 1;
57
58 /** @var RecurrRule Underlying recurrence rule object */
59 protected RecurrRule $rrule;
60
61 /** @var ArrayTransformer Transformer that expands the rule into concrete occurrences */
62 protected ArrayTransformer $transformer;
63
64 /** @var ArrayTransformerConfig Configuration for the transformer, including the virtual limit */
65 protected ArrayTransformerConfig $transformerConfig;
66
67 /** @var string Human-readable frequency label, e.g. one of the class constants */
68 protected string $frequency;
69
70 /**
71 * Create a new RRule
72 *
73 * @param string|array<string, mixed> $rule
74 *
75 * @throws InvalidRRule
76 */
77 public function __construct(array|string $rule)
78 {
79 $this->rrule = new RecurrRule($rule);
80 $this->frequency = $this->rrule->getFreqAsText();
81 $this->transformerConfig = new ArrayTransformerConfig();
82 $this->transformerConfig->setVirtualLimit(self::DEFAULT_LIMIT);
83
84 // If no specific run day is set, enable the "last-day-of-month fix"
85 // to avoid skipping months without days 29, 30, or 31.
86 if (
87 $this->getFrequency() === static::MONTHLY
88 && ! $this->rrule->getByDay()
89 && ! $this->rrule->getByMonthDay()
90 ) {
91 $this->transformerConfig->enableLastDayOfMonthFix();
92 }
93
94 $this->transformer = new ArrayTransformer($this->transformerConfig);
95 }
96
97 /**
98 * Create an {@see RRule} instance from its stored JSON representation
99 *
100 * The JSON must decode to an object with an `rrule` key and a `frequency` key,
101 * and optionally a `start` key formatted according to {@see Frequency::SERIALIZED_DATETIME_FORMAT}.
102 *
103 * @param string $json
104 *
105 * @return static
106 *
107 * @throws InvalidArgumentException If the start datetime cannot be deserialized
108 */
109 public static function fromJson(string $json): static
110 {
111 /** @var stdClass $data */
112 $data = json_decode($json);
113 $self = new static($data->rrule);
114 $self->frequency = $data->frequency;
115 if (isset($data->start)) {
116 $start = DateTime::createFromFormat(static::SERIALIZED_DATETIME_FORMAT, $data->start);
117 if (! $start) {
118 throw new InvalidArgumentException(sprintf('Cannot deserialize start time: %s', $data->start));
119 }
120
121 $self->startAt($start);
122 }
123
124 return $self;
125 }
126
127 /**
128 * Create an RRule instance from one of the predefined frequency constants
129 *
130 * @param string $frequency One of the class frequency constants
131 *
132 * @return static
133 *
134 * @throws InvalidArgumentException If the frequency is not one of the known constants
135 */
136 public static function fromFrequency(string $frequency): static
137 {
138 $frequencies = array_flip([
139 static::MINUTELY,
140 static::HOURLY,
141 static::DAILY,
142 static::WEEKLY,
143 static::MONTHLY,
144 static::QUARTERLY,
145 static::YEARLY
146 ]);
147
148 if (! isset($frequencies[$frequency])) {
149 throw new InvalidArgumentException(sprintf('Unknown frequency provided: %s', $frequency));
150 }
151
152 if ($frequency === static::QUARTERLY) {
153 $repeat = static::MONTHLY;
154 $rule = "FREQ=$repeat;INTERVAL=3";
155 } else {
156 $rule = "FREQ=$frequency";
157 }
158
159 $self = new static($rule);
160 $self->frequency = $frequency;
161
162 return $self;
163 }
164
165 public function isDue(DateTimeInterface $dateTime): bool
166 {
167 if ($dateTime < $this->rrule->getStartDate() || $this->isExpired($dateTime)) {
168 return false;
169 }
170
171 $nextDue = $this->getNextRecurrences($dateTime);
172 if (! $nextDue->valid()) {
173 return false;
174 }
175
176 return $nextDue->current() == $dateTime;
177 }
178
179 /**
180 * Get the next due date relative to the given time
181 *
182 * Returns the end time if the frequency is expired, or the given time itself if no further recurrence exists.
183 *
184 * @param DateTimeInterface $dateTime
185 *
186 * @return DateTimeInterface
187 */
188 public function getNextDue(DateTimeInterface $dateTime): DateTimeInterface
189 {
190 if ($this->isExpired($dateTime)) {
191 return $this->getEnd();
192 }
193
194 $nextDue = $this->getNextRecurrences($dateTime, 1, false);
195 if (! $nextDue->valid()) {
196 return $dateTime;
197 }
198
199 return $nextDue->current();
200 }
201
202 public function isExpired(DateTimeInterface $dateTime): bool
203 {
204 if ($this->rrule->repeatsIndefinitely()) {
205 return false;
206 }
207
208 return $this->getEnd() !== null && $this->getEnd() < $dateTime;
209 }
210
211 public function getStart(): ?DateTimeInterface
212 {
213 return $this->rrule->getStartDate();
214 }
215
216 /**
217 * Get the end time of this frequency
218 *
219 * Returns the rule's end date if set, falling back to the `UNTIL` value.
220 *
221 * @return ?DateTimeInterface
222 */
223 public function getEnd(): ?DateTimeInterface
224 {
225 return $this->rrule->getEndDate() ?? $this->rrule->getUntil();
226 }
227
228 /**
229 * Set timezone for the rrule
230 *
231 * @param string $timezone
232 *
233 * @return $this
234 */
235 public function setTimezone(string $timezone): static
236 {
237 $this->rrule->setTimezone($timezone);
238
239 $this->rrule->setStartDate($this->alignTimezone($this->rrule->getStartDate()));
240 $this->rrule->setEndDate($this->alignTimezone($this->rrule->getEndDate()));
241 $until = $this->rrule->getUntil();
242 if ($until !== null) {
243 $this->rrule->setUntil($this->alignTimezone($until));
244 }
245
246 return $this;
247 }
248
249 /**
250 * Set the start time of this frequency
251 *
252 * The given datetime will be cloned and microseconds removed since iCalendar datetimes only work to the second.
253 *
254 * @param DateTimeInterface $start
255 *
256 * @return $this
257 */
258 public function startAt(DateTimeInterface $start): static
259 {
260 $this->rrule->setStartDate($this->normalizeDateTime($start));
261
262 return $this;
263 }
264
265 /**
266 * Set the time until this frequency lasts
267 *
268 * The given datetime will be cloned and microseconds removed since iCalendar datetimes only work to the second.
269 *
270 * @param DateTimeInterface $end
271 *
272 * @return $this
273 */
274 public function endAt(DateTimeInterface $end): static
275 {
276 $this->rrule->setUntil($this->normalizeDateTime($end));
277
278 return $this;
279 }
280
281 /**
282 * Get the frequency of this rule
283 *
284 * @return string
285 */
286 public function getFrequency(): string
287 {
288 return $this->frequency;
289 }
290
291 /**
292 * Get a set of recurrences relative to the given time
293 *
294 * @param DateTimeInterface $dateTime
295 * @param int $limit Limit the recurrences to be generated to the given value
296 * @param bool $include Whether to include the passed time in the result set
297 *
298 * @return Generator<DateTimeInterface>
299 */
300 public function getNextRecurrences(
301 DateTimeInterface $dateTime,
302 int $limit = self::DEFAULT_LIMIT,
303 bool $include = true
304 ): Generator {
305 // The virtual limit is Recurr's guard against infinite loops: it caps
306 // the total number of candidates processed. It is shared config, so we
307 // raise it temporarily for multi-result calls and restore it afterward.
308 $resetTransformerConfig = function (int $limit = self::DEFAULT_LIMIT): void {
309 $this->transformerConfig->setVirtualLimit($limit);
310 $this->transformer->setConfig($this->transformerConfig);
311 };
312
313 if ($limit > self::DEFAULT_LIMIT) {
314 $resetTransformerConfig($limit);
315 }
316
317 // For bounded rules, BetweenConstraint also caps at the end time.
318 // AfterConstraint alone would let the transformer run past it.
319 $constraint = new AfterConstraint($dateTime, $include);
320 if (! $this->rrule->repeatsIndefinitely()) {
321 $constraint = new BetweenConstraint($dateTime, $this->getEnd(), $include);
322 }
323
324 // By default, non-matching candidates count toward the virtual limit too.
325 // With a past start date this exhausts it before any match is found.
326 // Pass false so only matches count.
327 $recurrences = $this->transformer->transform($this->rrule, $constraint, countConstraintFailures: false);
328 foreach ($recurrences as $recurrence) {
329 /** @var \Recurr\Recurrence $recurrence */
330
331 // Return results in the caller's timezone, not the rrule's.
332 yield DateTime::createFromInterface($recurrence->getStart())->setTimezone($dateTime->getTimezone());
333 }
334
335 if ($limit > self::DEFAULT_LIMIT) {
336 $resetTransformerConfig();
337 }
338 }
339
340 /**
341 * Serialize this frequency to a JSON-encodable array
342 *
343 * Always includes `rrule` and `frequency` keys; `start` is included only when set,
344 * formatted according to {@see Frequency::SERIALIZED_DATETIME_FORMAT}.
345 *
346 * @return array<string, string>
347 */
348 public function jsonSerialize(): array
349 {
350 $data = [
351 'rrule' => $this->rrule->getString(RecurrRule::TZ_FIXED),
352 'frequency' => $this->frequency
353 ];
354
355 $start = $this->getStart();
356 if ($start) {
357 $data['start'] = $start->format(static::SERIALIZED_DATETIME_FORMAT);
358 }
359
360 return $data;
361 }
362
363 /**
364 * Redirect all public method calls to the underlying rrule object
365 *
366 * @param string $methodName
367 * @param array<mixed> $args
368 *
369 * @return mixed
370 *
371 * @throws BadMethodCallException If the given method doesn't exist or when setter method is called
372 */
373 public function __call(string $methodName, array $args)
374 {
375 if (! method_exists($this->rrule, $methodName)) {
376 throw new BadMethodCallException(
377 sprintf('Call to undefined method %s::%s()', get_php_type($this->rrule), $methodName)
378 );
379 }
380
381 if (strtolower(substr($methodName, 0, 3)) !== 'get') {
382 throw new BadMethodCallException(
383 sprintf('Dynamic method %s is not supported. Only getters (get*) are', $methodName)
384 );
385 }
386
387 return call_user_func_array([$this->rrule, $methodName], $args);
388 }
389
390 /**
391 * Normalize a datetime for Recurr
392 *
393 * The given datetime is cloned, stripped of microseconds, and aligned to
394 * the rrule's configured timezone.
395 *
396 * @param DateTimeInterface $dateTime
397 *
398 * @return DateTime
399 */
400 protected function normalizeDateTime(DateTimeInterface $dateTime): DateTime
401 {
402 $dateTime = DateTime::createFromInterface($dateTime);
403 // Microseconds in the datetime can cause the first recurrence to be
404 // skipped, as the transformer only operates to the second.
405 // See upstream issue #155.
406 $dateTime->setTime(
407 (int) $dateTime->format('H'),
408 (int) $dateTime->format('i'),
409 (int) $dateTime->format('s')
410 );
411
412 return $this->alignTimezone($dateTime);
413 }
414
415 /**
416 * Align a datetime to the rrule's configured timezone
417 *
418 * Recurr requires all dates to share the rrule's own timezone, otherwise
419 * recurrences are calculated against the wrong UTC offset.
420 *
421 * @param ?DateTimeInterface $dateTime
422 *
423 * @return ?DateTime
424 */
425 protected function alignTimezone(?DateTimeInterface $dateTime): ?DateTime
426 {
427 if ($dateTime === null) {
428 return null;
429 }
430
431 return DateTime::createFromInterface($dateTime)
432 ->setTimezone(new DateTimeZone($this->rrule->getTimezone()));
433 }
434 }