Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/CarbonPeriod.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 /**
6 * This file is part of the Carbon package.
7 *
8 * (c) Brian Nesbitt <[email protected]>
9 *
10 * For the full copyright and license information, please view the LICENSE
11 * file that was distributed with this source code.
12 */
13
14 namespace Carbon;
15
16 use Carbon\Constants\UnitValue;
17 use Carbon\Exceptions\EndLessPeriodException;
18 use Carbon\Exceptions\InvalidCastException;
19 use Carbon\Exceptions\InvalidIntervalException;
20 use Carbon\Exceptions\InvalidPeriodDateException;
21 use Carbon\Exceptions\InvalidPeriodParameterException;
22 use Carbon\Exceptions\NotACarbonClassException;
23 use Carbon\Exceptions\NotAPeriodException;
24 use Carbon\Exceptions\UnknownGetterException;
25 use Carbon\Exceptions\UnknownMethodException;
26 use Carbon\Exceptions\UnreachableException;
27 use Carbon\Traits\DeprecatedPeriodProperties;
28 use Carbon\Traits\IntervalRounding;
29 use Carbon\Traits\LocalFactory;
30 use Carbon\Traits\Mixin;
31 use Carbon\Traits\Options;
32 use Carbon\Traits\ToStringFormat;
33 use Closure;
34 use Countable;
35 use DateInterval;
36 use DatePeriod;
37 use DateTime;
38 use DateTimeImmutable;
39 use DateTimeInterface;
40 use DateTimeZone;
41 use Generator;
42 use InvalidArgumentException;
43 use JsonSerializable;
44 use ReflectionException;
45 use ReturnTypeWillChange;
46 use RuntimeException;
47 use Throwable;
48
49 // @codeCoverageIgnoreStart
50 require PHP_VERSION < 8.2
51 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php'
52 : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php';
53 // @codeCoverageIgnoreEnd
54
55 /**
56 * Substitution of DatePeriod with some modifications and many more features.
57 *
58 * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance.
59 * @method static static since($date = null, $inclusive = null) Alias for start().
60 * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance.
61 * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance.
62 * @method static static until($date = null, $inclusive = null) Alias for end().
63 * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance.
64 * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance.
65 * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance.
66 * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance.
67 * @method static static times($recurrences = null) Alias for recurrences().
68 * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance.
69 * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance.
70 * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance.
71 * @method static static push($callback, $name = null) Alias for filter().
72 * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance.
73 * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance.
74 * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance.
75 * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance.
76 * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance.
77 * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance.
78 * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance.
79 * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance.
80 * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance.
81 * @method static static year($years = 1) Alias for years().
82 * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance.
83 * @method static static month($months = 1) Alias for months().
84 * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance.
85 * @method static static week($weeks = 1) Alias for weeks().
86 * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance.
87 * @method static static dayz($days = 1) Alias for days().
88 * @method static static day($days = 1) Alias for days().
89 * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance.
90 * @method static static hour($hours = 1) Alias for hours().
91 * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance.
92 * @method static static minute($minutes = 1) Alias for minutes().
93 * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance.
94 * @method static static second($seconds = 1) Alias for seconds().
95 * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance.
96 * @method static static millisecond($milliseconds = 1) Alias for milliseconds().
97 * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance.
98 * @method static static microsecond($microseconds = 1) Alias for microseconds().
99 * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function.
100 * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function.
101 * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision.
102 * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision.
103 * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision.
104 * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision.
105 * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function.
106 * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function.
107 * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision.
108 * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision.
109 * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision.
110 * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision.
111 * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
112 * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
113 * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision.
114 * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision.
115 * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision.
116 * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision.
117 * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
118 * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
119 * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision.
120 * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision.
121 * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision.
122 * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision.
123 * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function.
124 * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function.
125 * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision.
126 * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision.
127 * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision.
128 * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision.
129 * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function.
130 * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function.
131 * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision.
132 * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision.
133 * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision.
134 * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision.
135 * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function.
136 * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function.
137 * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision.
138 * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision.
139 * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision.
140 * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision.
141 * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function.
142 * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function.
143 * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision.
144 * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision.
145 * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision.
146 * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision.
147 * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function.
148 * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function.
149 * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision.
150 * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision.
151 * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision.
152 * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision.
153 * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function.
154 * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function.
155 * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision.
156 * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision.
157 * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision.
158 * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision.
159 * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function.
160 * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function.
161 * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision.
162 * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision.
163 * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision.
164 * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision.
165 * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function.
166 * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function.
167 * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision.
168 * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision.
169 * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision.
170 * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision.
171 * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function.
172 * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function.
173 * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision.
174 * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision.
175 * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision.
176 * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision.
177 *
178 * @mixin DeprecatedPeriodProperties
179 *
180 * @SuppressWarnings(TooManyFields)
181 * @SuppressWarnings(CamelCasePropertyName)
182 * @SuppressWarnings(CouplingBetweenObjects)
183 */
184 class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue
185 {
186 use LocalFactory;
187 use IntervalRounding;
188 use Mixin {
189 Mixin::mixin as baseMixin;
190 }
191 use Options {
192 Options::__debugInfo as baseDebugInfo;
193 }
194 use ToStringFormat;
195
196 /**
197 * Built-in filter for limit by recurrences.
198 *
199 * @var callable
200 */
201 public const RECURRENCES_FILTER = [self::class, 'filterRecurrences'];
202
203 /**
204 * Built-in filter for limit to an end.
205 *
206 * @var callable
207 */
208 public const END_DATE_FILTER = [self::class, 'filterEndDate'];
209
210 /**
211 * Special value which can be returned by filters to end iteration. Also a filter.
212 *
213 * @var callable
214 */
215 public const END_ITERATION = [self::class, 'endIteration'];
216
217 /**
218 * Exclude end date from iteration.
219 *
220 * @var int
221 */
222 public const EXCLUDE_END_DATE = 8;
223
224 /**
225 * Yield CarbonImmutable instances.
226 *
227 * @var int
228 */
229 public const IMMUTABLE = 4;
230
231 /**
232 * Number of maximum attempts before giving up on finding next valid date.
233 *
234 * @var int
235 */
236 public const NEXT_MAX_ATTEMPTS = 1000;
237
238 /**
239 * Number of maximum attempts before giving up on finding end date.
240 *
241 * @var int
242 */
243 public const END_MAX_ATTEMPTS = 10000;
244
245 /**
246 * Default date class of iteration items.
247 *
248 * @var string
249 */
250 protected const DEFAULT_DATE_CLASS = Carbon::class;
251
252 /**
253 * The registered macros.
254 */
255 protected static array $macros = [];
256
257 /**
258 * Date class of iteration items.
259 */
260 protected string $dateClass = Carbon::class;
261
262 /**
263 * Underlying date interval instance. Always present, one day by default.
264 */
265 protected ?CarbonInterval $dateInterval = null;
266
267 /**
268 * True once __construct is finished.
269 */
270 protected bool $constructed = false;
271
272 /**
273 * Whether current date interval was set by default.
274 */
275 protected bool $isDefaultInterval = false;
276
277 /**
278 * The filters stack.
279 */
280 protected array $filters = [];
281
282 /**
283 * Period start date. Applied on rewind. Always present, now by default.
284 */
285 protected ?CarbonInterface $startDate = null;
286
287 /**
288 * Period end date. For inverted interval should be before the start date. Applied via a filter.
289 */
290 protected ?CarbonInterface $endDate = null;
291
292 /**
293 * Limit for number of recurrences. Applied via a filter.
294 */
295 protected int|float|null $carbonRecurrences = null;
296
297 /**
298 * Iteration options.
299 */
300 protected ?int $options = null;
301
302 /**
303 * Index of current date. Always sequential, even if some dates are skipped by filters.
304 * Equal to null only before the first iteration.
305 */
306 protected int $key = 0;
307
308 /**
309 * Current date. May temporarily hold unaccepted value when looking for a next valid date.
310 * Equal to null only before the first iteration.
311 */
312 protected ?CarbonInterface $carbonCurrent = null;
313
314 /**
315 * Timezone of current date. Taken from the start date.
316 */
317 protected ?DateTimeZone $timezone = null;
318
319 /**
320 * The cached validation result for current date.
321 */
322 protected array|string|bool|null $validationResult = null;
323
324 /**
325 * Timezone handler for settings() method.
326 */
327 protected DateTimeZone|string|int|null $timezoneSetting = null;
328
329 public function getIterator(): Generator
330 {
331 $this->rewind();
332
333 while ($this->valid()) {
334 $key = $this->key();
335 $value = $this->current();
336
337 yield $key => $value;
338
339 $this->next();
340 }
341 }
342
343 /**
344 * Make a CarbonPeriod instance from given variable if possible.
345 */
346 public static function make(mixed $var): ?static
347 {
348 try {
349 return static::instance($var);
350 } catch (NotAPeriodException) {
351 return static::create($var);
352 }
353 }
354
355 /**
356 * Create a new instance from a DatePeriod or CarbonPeriod object.
357 */
358 public static function instance(mixed $period): static
359 {
360 if ($period instanceof static) {
361 return $period->copy();
362 }
363
364 if ($period instanceof self) {
365 return new static(
366 $period->getStartDate(),
367 $period->getEndDate() ?? $period->getRecurrences(),
368 $period->getDateInterval(),
369 $period->getOptions(),
370 );
371 }
372
373 if ($period instanceof DatePeriod) {
374 return new static(
375 $period->start,
376 $period->end ?: ($period->recurrences - 1),
377 $period->interval,
378 $period->include_start_date ? 0 : static::EXCLUDE_START_DATE,
379 );
380 }
381
382 $class = static::class;
383 $type = \gettype($period);
384 $chunks = explode('::', __METHOD__);
385
386 throw new NotAPeriodException(
387 'Argument 1 passed to '.$class.'::'.end($chunks).'() '.
388 'must be an instance of DatePeriod or '.$class.', '.
389 ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.',
390 );
391 }
392
393 /**
394 * Create a new instance.
395 */
396 public static function create(...$params): static
397 {
398 return static::createFromArray($params);
399 }
400
401 /**
402 * Create a new instance from an array of parameters.
403 */
404 public static function createFromArray(array $params): static
405 {
406 return new static(...$params);
407 }
408
409 /**
410 * Create CarbonPeriod from ISO 8601 string.
411 */
412 public static function createFromIso(string $iso, ?int $options = null): static
413 {
414 $params = static::parseIso8601($iso);
415
416 $instance = static::createFromArray($params);
417
418 $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options;
419 $instance->handleChangedParameters();
420
421 return $instance;
422 }
423
424 public static function createFromISO8601String(string $iso, ?int $options = null): static
425 {
426 return self::createFromIso($iso, $options);
427 }
428
429 /**
430 * Return whether the given interval contains non-zero value of any time unit.
431 */
432 protected static function intervalHasTime(DateInterval $interval): bool
433 {
434 return $interval->h || $interval->i || $interval->s || $interval->f;
435 }
436
437 /**
438 * Return whether given variable is an ISO 8601 specification.
439 *
440 * Note: Check is very basic, as actual validation will be done later when parsing.
441 * We just want to ensure that variable is not any other type of valid parameter.
442 */
443 protected static function isIso8601(mixed $var): bool
444 {
445 if (!\is_string($var)) {
446 return false;
447 }
448
449 // Match slash but not within a timezone name.
450 $part = '[a-z]+(?:[_-][a-z]+)*';
451
452 preg_match("#\b$part/$part\b|(/)#i", $var, $match);
453
454 return isset($match[1]);
455 }
456
457 /**
458 * Parse given ISO 8601 string into an array of arguments.
459 *
460 * @SuppressWarnings(ElseExpression)
461 */
462 protected static function parseIso8601(string $iso): array
463 {
464 $result = [];
465
466 $interval = null;
467 $start = null;
468 $end = null;
469 $dateClass = static::DEFAULT_DATE_CLASS;
470
471 foreach (explode('/', $iso) as $key => $part) {
472 if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) {
473 $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null;
474 } elseif ($interval === null && $parsed = self::makeInterval($part)) {
475 $interval = $part;
476 } elseif ($start === null && $parsed = $dateClass::make($part)) {
477 $start = $part;
478 } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) {
479 $end = $part;
480 } else {
481 throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso.");
482 }
483
484 $result[] = $parsed;
485 }
486
487 return $result;
488 }
489
490 /**
491 * Add missing parts of the target date from the source date.
492 */
493 protected static function addMissingParts(string $source, string $target): string
494 {
495 $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/';
496
497 $result = preg_replace($pattern, $target, $source, 1, $count);
498
499 return $count ? $result : $target;
500 }
501
502 private static function makeInterval(mixed $input): ?CarbonInterval
503 {
504 try {
505 return CarbonInterval::make($input);
506 } catch (Throwable) {
507 return null;
508 }
509 }
510
511 private static function makeTimezone(mixed $input): ?CarbonTimeZone
512 {
513 if (!\is_string($input)) {
514 return null;
515 }
516
517 try {
518 return CarbonTimeZone::create($input);
519 } catch (Throwable) {
520 return null;
521 }
522 }
523
524 /**
525 * Register a custom macro.
526 *
527 * Pass null macro to remove it.
528 *
529 * @example
530 * ```
531 * CarbonPeriod::macro('middle', function () {
532 * return $this->getStartDate()->average($this->getEndDate());
533 * });
534 * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle();
535 * ```
536 *
537 * @param-closure-this static $macro
538 */
539 public static function macro(string $name, ?callable $macro): void
540 {
541 static::$macros[$name] = $macro;
542 }
543
544 /**
545 * Register macros from a mixin object.
546 *
547 * @example
548 * ```
549 * CarbonPeriod::mixin(new class {
550 * public function addDays() {
551 * return function ($count = 1) {
552 * return $this->setStartDate(
553 * $this->getStartDate()->addDays($count)
554 * )->setEndDate(
555 * $this->getEndDate()->addDays($count)
556 * );
557 * };
558 * }
559 * public function subDays() {
560 * return function ($count = 1) {
561 * return $this->setStartDate(
562 * $this->getStartDate()->subDays($count)
563 * )->setEndDate(
564 * $this->getEndDate()->subDays($count)
565 * );
566 * };
567 * }
568 * });
569 * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3);
570 * ```
571 *
572 * @throws ReflectionException
573 */
574 public static function mixin(object|string $mixin): void
575 {
576 static::baseMixin($mixin);
577 }
578
579 /**
580 * Check if macro is registered.
581 */
582 public static function hasMacro(string $name): bool
583 {
584 return isset(static::$macros[$name]);
585 }
586
587 /**
588 * Provide static proxy for instance aliases.
589 */
590 public static function __callStatic(string $method, array $parameters): mixed
591 {
592 $date = new static();
593
594 if (static::hasMacro($method)) {
595 return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters));
596 }
597
598 return $date->$method(...$parameters);
599 }
600
601 /**
602 * CarbonPeriod constructor.
603 *
604 * @SuppressWarnings(ElseExpression)
605 *
606 * @throws InvalidArgumentException
607 */
608 public function __construct(...$arguments)
609 {
610 $raw = null;
611
612 if (isset($arguments['raw'])) {
613 $raw = $arguments['raw'];
614 $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false;
615
616 if (isset($arguments['dateClass'])) {
617 $this->dateClass = $arguments['dateClass'];
618 }
619
620 $arguments = $raw;
621 }
622
623 // Parse and assign arguments one by one. First argument may be an ISO 8601 spec,
624 // which will be first parsed into parts and then processed the same way.
625
626 $argumentsCount = \count($arguments);
627
628 if ($argumentsCount && static::isIso8601($iso = $arguments[0])) {
629 array_splice($arguments, 0, 1, static::parseIso8601($iso));
630 }
631
632 if ($argumentsCount === 1) {
633 if ($arguments[0] instanceof self) {
634 $arguments = [
635 $arguments[0]->getStartDate(),
636 $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(),
637 $arguments[0]->getDateInterval(),
638 $arguments[0]->getOptions(),
639 ];
640 } elseif ($arguments[0] instanceof DatePeriod) {
641 $arguments = [
642 $arguments[0]->start,
643 $arguments[0]->end ?: ($arguments[0]->recurrences - 1),
644 $arguments[0]->interval,
645 $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE,
646 ];
647 }
648 }
649
650 if (is_a($this->dateClass, DateTimeImmutable::class, true)) {
651 $this->options = static::IMMUTABLE;
652 }
653
654 $optionsSet = false;
655 $originalArguments = [];
656 $sortedArguments = [];
657
658 foreach ($arguments as $argument) {
659 $parsedDate = null;
660
661 if ($argument instanceof DateTimeZone) {
662 $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments);
663 } elseif (!isset($sortedArguments['interval']) &&
664 (
665 (\is_string($argument) && preg_match(
666 '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i',
667 $argument,
668 )) ||
669 $argument instanceof DateInterval ||
670 $argument instanceof Closure ||
671 $argument instanceof Unit
672 ) &&
673 $parsedInterval = self::makeInterval($argument)
674 ) {
675 $sortedArguments['interval'] = $parsedInterval;
676 } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) {
677 $sortedArguments['start'] = $parsedDate;
678 $originalArguments['start'] = $argument;
679 } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) {
680 $sortedArguments['end'] = $parsedDate;
681 $originalArguments['end'] = $argument;
682 } elseif (!isset($sortedArguments['recurrences']) &&
683 !isset($sortedArguments['end']) &&
684 (\is_int($argument) || \is_float($argument))
685 && $argument >= 0
686 ) {
687 $sortedArguments['recurrences'] = $argument;
688 } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) {
689 $optionsSet = true;
690 $sortedArguments['options'] = (((int) $this->options) | ((int) $argument));
691 } elseif ($parsedTimezone = self::makeTimezone($argument)) {
692 $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments);
693 } else {
694 throw new InvalidPeriodParameterException('Invalid constructor parameters.');
695 }
696 }
697
698 if ($raw === null && isset($sortedArguments['start'])) {
699 $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1);
700
701 if (\is_float($end)) {
702 $end = $end === INF ? PHP_INT_MAX : (int) round($end);
703 }
704
705 $raw = [
706 $sortedArguments['start'],
707 $sortedArguments['interval'] ?? CarbonInterval::day(),
708 $end,
709 ];
710 }
711
712 $this->setFromAssociativeArray($sortedArguments);
713
714 if ($this->startDate === null) {
715 $dateClass = $this->dateClass;
716 $this->setStartDate($dateClass::now());
717 }
718
719 if ($this->dateInterval === null) {
720 $this->setDateInterval(CarbonInterval::day());
721
722 $this->isDefaultInterval = true;
723 }
724
725 if ($this->options === null) {
726 $this->setOptions(0);
727 }
728
729 parent::__construct(
730 $this->startDate,
731 $this->dateInterval,
732 $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)),
733 $this->options,
734 );
735
736 $this->constructed = true;
737 }
738
739 /**
740 * Get a copy of the instance.
741 */
742 public function copy(): static
743 {
744 return clone $this;
745 }
746
747 /**
748 * Prepare the instance to be set (self if mutable to be mutated,
749 * copy if immutable to generate a new instance).
750 */
751 protected function copyIfImmutable(): static
752 {
753 return $this;
754 }
755
756 /**
757 * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names.
758 */
759 protected function getGetter(string $name): ?callable
760 {
761 return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) {
762 'start', 'start_date' => [$this, 'getStartDate'],
763 'end', 'end_date' => [$this, 'getEndDate'],
764 'interval', 'date_interval' => [$this, 'getDateInterval'],
765 'recurrences' => [$this, 'getRecurrences'],
766 'include_start_date' => [$this, 'isStartIncluded'],
767 'include_end_date' => [$this, 'isEndIncluded'],
768 'current' => [$this, 'current'],
769 'locale' => [$this, 'locale'],
770 'tzname', 'tz_name' => fn () => match (true) {
771 $this->timezoneSetting === null => null,
772 \is_string($this->timezoneSetting) => $this->timezoneSetting,
773 $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(),
774 default => CarbonTimeZone::instance($this->timezoneSetting)->getName(),
775 },
776 default => null,
777 };
778 }
779
780 /**
781 * Get a property allowing both `DatePeriod` snakeCase and camelCase names.
782 *
783 * @param string $name
784 *
785 * @return bool|CarbonInterface|CarbonInterval|int|null
786 */
787 public function get(string $name)
788 {
789 $getter = $this->getGetter($name);
790
791 if ($getter) {
792 return $getter();
793 }
794
795 throw new UnknownGetterException($name);
796 }
797
798 /**
799 * Get a property allowing both `DatePeriod` snakeCase and camelCase names.
800 *
801 * @param string $name
802 *
803 * @return bool|CarbonInterface|CarbonInterval|int|null
804 */
805 public function __get(string $name)
806 {
807 return $this->get($name);
808 }
809
810 /**
811 * Check if an attribute exists on the object
812 *
813 * @param string $name
814 *
815 * @return bool
816 */
817 public function __isset(string $name): bool
818 {
819 return $this->getGetter($name) !== null;
820 }
821
822 /**
823 * @alias copy
824 *
825 * Get a copy of the instance.
826 *
827 * @return static
828 */
829 public function clone()
830 {
831 return clone $this;
832 }
833
834 /**
835 * Set the iteration item class.
836 *
837 * @param string $dateClass
838 *
839 * @return static
840 */
841 public function setDateClass(string $dateClass)
842 {
843 if (!is_a($dateClass, CarbonInterface::class, true)) {
844 throw new NotACarbonClassException($dateClass);
845 }
846
847 $self = $this->copyIfImmutable();
848 $self->dateClass = $dateClass;
849
850 if (is_a($dateClass, Carbon::class, true)) {
851 $self->options = $self->options & ~static::IMMUTABLE;
852 } elseif (is_a($dateClass, CarbonImmutable::class, true)) {
853 $self->options = $self->options | static::IMMUTABLE;
854 }
855
856 return $self;
857 }
858
859 /**
860 * Returns iteration item date class.
861 *
862 * @return string
863 */
864 public function getDateClass(): string
865 {
866 return $this->dateClass;
867 }
868
869 /**
870 * Change the period date interval.
871 *
872 * @param DateInterval|Unit|string|int $interval
873 * @param Unit|string $unit the unit of $interval if it's a number
874 *
875 * @throws InvalidIntervalException
876 *
877 * @return static
878 */
879 public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static
880 {
881 if ($interval instanceof Unit) {
882 $interval = $interval->interval();
883 }
884
885 if ($unit instanceof Unit) {
886 $unit = $unit->name;
887 }
888
889 if (!$interval = CarbonInterval::make($interval, $unit)) {
890 throw new InvalidIntervalException('Invalid interval.');
891 }
892
893 if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) {
894 throw new InvalidIntervalException('Empty interval is not accepted.');
895 }
896
897 $self = $this->copyIfImmutable();
898 $self->dateInterval = $interval;
899
900 $self->isDefaultInterval = false;
901
902 $self->handleChangedParameters();
903
904 return $self;
905 }
906
907 /**
908 * Reset the date interval to the default value.
909 *
910 * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String()
911 * and also next adding to the interval won't include the default 1-day.
912 */
913 public function resetDateInterval(): static
914 {
915 $self = $this->copyIfImmutable();
916 $self->setDateInterval(CarbonInterval::day());
917
918 $self->isDefaultInterval = true;
919
920 return $self;
921 }
922
923 /**
924 * Invert the period date interval.
925 */
926 public function invertDateInterval(): static
927 {
928 return $this->setDateInterval($this->dateInterval->invert());
929 }
930
931 /**
932 * Set start and end date.
933 *
934 * @param DateTime|DateTimeInterface|string $start
935 * @param DateTime|DateTimeInterface|string|null $end
936 *
937 * @return static
938 */
939 public function setDates(mixed $start, mixed $end): static
940 {
941 return $this->setStartDate($start)->setEndDate($end);
942 }
943
944 /**
945 * Change the period options.
946 *
947 * @param int|null $options
948 *
949 * @return static
950 */
951 public function setOptions(?int $options): static
952 {
953 $self = $this->copyIfImmutable();
954 $self->options = $options ?? 0;
955
956 $self->handleChangedParameters();
957
958 return $self;
959 }
960
961 /**
962 * Get the period options.
963 */
964 public function getOptions(): int
965 {
966 return $this->options ?? 0;
967 }
968
969 /**
970 * Toggle given options on or off.
971 *
972 * @param int $options
973 * @param bool|null $state
974 *
975 * @throws InvalidArgumentException
976 *
977 * @return static
978 */
979 public function toggleOptions(int $options, ?bool $state = null): static
980 {
981 $self = $this->copyIfImmutable();
982
983 if ($state === null) {
984 $state = ($this->options & $options) !== $options;
985 }
986
987 return $self->setOptions(
988 $state ?
989 $this->options | $options :
990 $this->options & ~$options,
991 );
992 }
993
994 /**
995 * Toggle EXCLUDE_START_DATE option.
996 */
997 public function excludeStartDate(bool $state = true): static
998 {
999 return $this->toggleOptions(static::EXCLUDE_START_DATE, $state);
1000 }
1001
1002 /**
1003 * Toggle EXCLUDE_END_DATE option.
1004 */
1005 public function excludeEndDate(bool $state = true): static
1006 {
1007 return $this->toggleOptions(static::EXCLUDE_END_DATE, $state);
1008 }
1009
1010 /**
1011 * Get the underlying date interval.
1012 */
1013 public function getDateInterval(): CarbonInterval
1014 {
1015 return $this->dateInterval->copy();
1016 }
1017
1018 /**
1019 * Get start date of the period.
1020 *
1021 * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval.
1022 */
1023 public function getStartDate(?string $rounding = null): CarbonInterface
1024 {
1025 $date = $this->startDate->avoidMutation();
1026
1027 return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date;
1028 }
1029
1030 /**
1031 * Get end date of the period.
1032 *
1033 * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval.
1034 */
1035 public function getEndDate(?string $rounding = null): ?CarbonInterface
1036 {
1037 if (!$this->endDate) {
1038 return null;
1039 }
1040
1041 $date = $this->endDate->avoidMutation();
1042
1043 return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date;
1044 }
1045
1046 /**
1047 * Get number of recurrences.
1048 */
1049 #[ReturnTypeWillChange]
1050 public function getRecurrences(): int|float|null
1051 {
1052 return $this->carbonRecurrences;
1053 }
1054
1055 /**
1056 * Returns true if the start date should be excluded.
1057 */
1058 public function isStartExcluded(): bool
1059 {
1060 return ($this->options & static::EXCLUDE_START_DATE) !== 0;
1061 }
1062
1063 /**
1064 * Returns true if the end date should be excluded.
1065 */
1066 public function isEndExcluded(): bool
1067 {
1068 return ($this->options & static::EXCLUDE_END_DATE) !== 0;
1069 }
1070
1071 /**
1072 * Returns true if the start date should be included.
1073 */
1074 public function isStartIncluded(): bool
1075 {
1076 return !$this->isStartExcluded();
1077 }
1078
1079 /**
1080 * Returns true if the end date should be included.
1081 */
1082 public function isEndIncluded(): bool
1083 {
1084 return !$this->isEndExcluded();
1085 }
1086
1087 /**
1088 * Return the start if it's included by option, else return the start + 1 period interval.
1089 */
1090 public function getIncludedStartDate(): CarbonInterface
1091 {
1092 $start = $this->getStartDate();
1093
1094 if ($this->isStartExcluded()) {
1095 return $start->add($this->getDateInterval());
1096 }
1097
1098 return $start;
1099 }
1100
1101 /**
1102 * Return the end if it's included by option, else return the end - 1 period interval.
1103 * Warning: if the period has no fixed end, this method will iterate the period to calculate it.
1104 */
1105 public function getIncludedEndDate(): CarbonInterface
1106 {
1107 $end = $this->getEndDate();
1108
1109 if (!$end) {
1110 return $this->calculateEnd();
1111 }
1112
1113 if ($this->isEndExcluded()) {
1114 return $end->sub($this->getDateInterval());
1115 }
1116
1117 return $end;
1118 }
1119
1120 /**
1121 * Add a filter to the stack.
1122 *
1123 * @SuppressWarnings(UnusedFormalParameter)
1124 */
1125 public function addFilter(callable|string $callback, ?string $name = null): static
1126 {
1127 $self = $this->copyIfImmutable();
1128 $tuple = $self->createFilterTuple(\func_get_args());
1129
1130 $self->filters[] = $tuple;
1131
1132 $self->handleChangedParameters();
1133
1134 return $self;
1135 }
1136
1137 /**
1138 * Prepend a filter to the stack.
1139 *
1140 * @SuppressWarnings(UnusedFormalParameter)
1141 */
1142 public function prependFilter(callable|string $callback, ?string $name = null): static
1143 {
1144 $self = $this->copyIfImmutable();
1145 $tuple = $self->createFilterTuple(\func_get_args());
1146
1147 array_unshift($self->filters, $tuple);
1148
1149 $self->handleChangedParameters();
1150
1151 return $self;
1152 }
1153
1154 /**
1155 * Remove a filter by instance or name.
1156 */
1157 public function removeFilter(callable|string $filter): static
1158 {
1159 $self = $this->copyIfImmutable();
1160 $key = \is_callable($filter) ? 0 : 1;
1161
1162 $self->filters = array_values(array_filter(
1163 $this->filters,
1164 static fn ($tuple) => $tuple[$key] !== $filter,
1165 ));
1166
1167 $self->updateInternalState();
1168
1169 $self->handleChangedParameters();
1170
1171 return $self;
1172 }
1173
1174 /**
1175 * Return whether given instance or name is in the filter stack.
1176 */
1177 public function hasFilter(callable|string $filter): bool
1178 {
1179 $key = \is_callable($filter) ? 0 : 1;
1180
1181 foreach ($this->filters as $tuple) {
1182 if ($tuple[$key] === $filter) {
1183 return true;
1184 }
1185 }
1186
1187 return false;
1188 }
1189
1190 /**
1191 * Get filters stack.
1192 */
1193 public function getFilters(): array
1194 {
1195 return $this->filters;
1196 }
1197
1198 /**
1199 * Set filters stack.
1200 */
1201 public function setFilters(array $filters): static
1202 {
1203 $self = $this->copyIfImmutable();
1204 $self->filters = $filters;
1205
1206 $self->updateInternalState();
1207
1208 $self->handleChangedParameters();
1209
1210 return $self;
1211 }
1212
1213 /**
1214 * Reset filters stack.
1215 */
1216 public function resetFilters(): static
1217 {
1218 $self = $this->copyIfImmutable();
1219 $self->filters = [];
1220
1221 if ($self->endDate !== null) {
1222 $self->filters[] = [static::END_DATE_FILTER, null];
1223 }
1224
1225 if ($self->carbonRecurrences !== null) {
1226 $self->filters[] = [static::RECURRENCES_FILTER, null];
1227 }
1228
1229 $self->handleChangedParameters();
1230
1231 return $self;
1232 }
1233
1234 /**
1235 * Add a recurrences filter (set maximum number of recurrences).
1236 *
1237 * @throws InvalidArgumentException
1238 */
1239 public function setRecurrences(int|float|null $recurrences): static
1240 {
1241 if ($recurrences === null) {
1242 return $this->removeFilter(static::RECURRENCES_FILTER);
1243 }
1244
1245 if ($recurrences < 0) {
1246 throw new InvalidPeriodParameterException('Invalid number of recurrences.');
1247 }
1248
1249 /** @var self $self */
1250 $self = $this->copyIfImmutable();
1251 $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences;
1252
1253 if (!$self->hasFilter(static::RECURRENCES_FILTER)) {
1254 return $self->addFilter(static::RECURRENCES_FILTER);
1255 }
1256
1257 $self->handleChangedParameters();
1258
1259 return $self;
1260 }
1261
1262 /**
1263 * Change the period start date.
1264 *
1265 * @param DateTime|DateTimeInterface|string $date
1266 * @param bool|null $inclusive
1267 *
1268 * @throws InvalidPeriodDateException
1269 *
1270 * @return static
1271 */
1272 public function setStartDate(mixed $date, ?bool $inclusive = null): static
1273 {
1274 if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) {
1275 throw new InvalidPeriodDateException('Invalid start date.');
1276 }
1277
1278 $self = $this->copyIfImmutable();
1279 $self->startDate = $date;
1280
1281 if ($inclusive !== null) {
1282 $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive);
1283 }
1284
1285 return $self;
1286 }
1287
1288 /**
1289 * Change the period end date.
1290 *
1291 * @param DateTime|DateTimeInterface|string|null $date
1292 * @param bool|null $inclusive
1293 *
1294 * @throws \InvalidArgumentException
1295 *
1296 * @return static
1297 */
1298 public function setEndDate(mixed $date, ?bool $inclusive = null): static
1299 {
1300 if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) {
1301 throw new InvalidPeriodDateException('Invalid end date.');
1302 }
1303
1304 if (!$date) {
1305 return $this->removeFilter(static::END_DATE_FILTER);
1306 }
1307
1308 $self = $this->copyIfImmutable();
1309 $self->endDate = $date;
1310
1311 if ($inclusive !== null) {
1312 $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive);
1313 }
1314
1315 if (!$self->hasFilter(static::END_DATE_FILTER)) {
1316 return $self->addFilter(static::END_DATE_FILTER);
1317 }
1318
1319 $self->handleChangedParameters();
1320
1321 return $self;
1322 }
1323
1324 /**
1325 * Check if the current position is valid.
1326 */
1327 public function valid(): bool
1328 {
1329 return $this->validateCurrentDate() === true;
1330 }
1331
1332 /**
1333 * Return the current key.
1334 */
1335 public function key(): ?int
1336 {
1337 return $this->valid()
1338 ? $this->key
1339 : null;
1340 }
1341
1342 /**
1343 * Return the current date.
1344 */
1345 public function current(): ?CarbonInterface
1346 {
1347 return $this->valid()
1348 ? $this->prepareForReturn($this->carbonCurrent)
1349 : null;
1350 }
1351
1352 /**
1353 * Move forward to the next date.
1354 *
1355 * @throws RuntimeException
1356 */
1357 public function next(): void
1358 {
1359 if ($this->carbonCurrent === null) {
1360 $this->rewind();
1361 }
1362
1363 if ($this->validationResult !== static::END_ITERATION) {
1364 $this->key++;
1365
1366 $this->incrementCurrentDateUntilValid();
1367 }
1368 }
1369
1370 /**
1371 * Rewind to the start date.
1372 *
1373 * Iterating over a date in the UTC timezone avoids bug during backward DST change.
1374 *
1375 * @see https://bugs.php.net/bug.php?id=72255
1376 * @see https://bugs.php.net/bug.php?id=74274
1377 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time
1378 *
1379 * @throws RuntimeException
1380 */
1381 public function rewind(): void
1382 {
1383 $this->key = 0;
1384 $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate);
1385 $settings = $this->getSettings();
1386
1387 if ($this->hasLocalTranslator()) {
1388 $settings['locale'] = $this->getTranslatorLocale();
1389 }
1390
1391 $this->carbonCurrent->settings($settings);
1392 $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null;
1393
1394 if ($this->timezone) {
1395 $this->carbonCurrent = $this->carbonCurrent->utc();
1396 }
1397
1398 $this->validationResult = null;
1399
1400 if ($this->isStartExcluded() || $this->validateCurrentDate() === false) {
1401 $this->incrementCurrentDateUntilValid();
1402 }
1403 }
1404
1405 /**
1406 * Skip iterations and returns iteration state (false if ended, true if still valid).
1407 *
1408 * @param int $count steps number to skip (1 by default)
1409 *
1410 * @return bool
1411 */
1412 public function skip(int $count = 1): bool
1413 {
1414 for ($i = $count; $this->valid() && $i > 0; $i--) {
1415 $this->next();
1416 }
1417
1418 return $this->valid();
1419 }
1420
1421 /**
1422 * Format the date period as ISO 8601.
1423 */
1424 public function toIso8601String(): string
1425 {
1426 $parts = [];
1427
1428 if ($this->carbonRecurrences !== null) {
1429 $parts[] = 'R'.$this->carbonRecurrences;
1430 }
1431
1432 $parts[] = $this->startDate->toIso8601String();
1433
1434 if (!$this->isDefaultInterval) {
1435 $parts[] = $this->dateInterval->spec();
1436 }
1437
1438 if ($this->endDate !== null) {
1439 $parts[] = $this->endDate->toIso8601String();
1440 }
1441
1442 return implode('/', $parts);
1443 }
1444
1445 /**
1446 * Convert the date period into a string.
1447 */
1448 public function toString(): string
1449 {
1450 $format = $this->localToStringFormat
1451 ?? $this->getFactory()->getSettings()['toStringFormat']
1452 ?? null;
1453
1454 if ($format instanceof Closure) {
1455 return $format($this);
1456 }
1457
1458 $translator = ([$this->dateClass, 'getTranslator'])();
1459
1460 $parts = [];
1461
1462 $format = $format ?? (
1463 !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay())
1464 ? 'Y-m-d H:i:s'
1465 : 'Y-m-d'
1466 );
1467
1468 if ($this->carbonRecurrences !== null) {
1469 $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator);
1470 }
1471
1472 $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([
1473 'join' => true,
1474 ])], null, $translator);
1475
1476 $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator);
1477
1478 if ($this->endDate !== null) {
1479 $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator);
1480 }
1481
1482 $result = implode(' ', $parts);
1483
1484 return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1);
1485 }
1486
1487 /**
1488 * Format the date period as ISO 8601.
1489 */
1490 public function spec(): string
1491 {
1492 return $this->toIso8601String();
1493 }
1494
1495 /**
1496 * Cast the current instance into the given class.
1497 *
1498 * @param string $className The $className::instance() method will be called to cast the current object.
1499 *
1500 * @return DatePeriod|object
1501 */
1502 public function cast(string $className): object
1503 {
1504 if (!method_exists($className, 'instance')) {
1505 if (is_a($className, DatePeriod::class, true)) {
1506 return new $className(
1507 $this->rawDate($this->getStartDate()),
1508 $this->getDateInterval(),
1509 $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(),
1510 $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0,
1511 );
1512 }
1513
1514 throw new InvalidCastException("$className has not the instance() method needed to cast the date.");
1515 }
1516
1517 return $className::instance($this);
1518 }
1519
1520 /**
1521 * Return native DatePeriod PHP object matching the current instance.
1522 *
1523 * @example
1524 * ```
1525 * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod());
1526 * ```
1527 */
1528 public function toDatePeriod(): DatePeriod
1529 {
1530 return $this->cast(DatePeriod::class);
1531 }
1532
1533 /**
1534 * Return `true` if the period has no custom filter and is guaranteed to be endless.
1535 *
1536 * Note that we can't check if a period is endless as soon as it has custom filters
1537 * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in
1538 * a way we can't predict without actually iterating the period.
1539 */
1540 public function isUnfilteredAndEndLess(): bool
1541 {
1542 foreach ($this->filters as $filter) {
1543 switch ($filter) {
1544 case [static::RECURRENCES_FILTER, null]:
1545 if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) {
1546 return false;
1547 }
1548
1549 break;
1550
1551 case [static::END_DATE_FILTER, null]:
1552 if ($this->endDate !== null && !$this->endDate->isEndOfTime()) {
1553 return false;
1554 }
1555
1556 break;
1557
1558 default:
1559 return false;
1560 }
1561 }
1562
1563 return true;
1564 }
1565
1566 /**
1567 * Convert the date period into an array without changing current iteration state.
1568 *
1569 * @return CarbonInterface[]
1570 */
1571 public function toArray(): array
1572 {
1573 if ($this->isUnfilteredAndEndLess()) {
1574 throw new EndLessPeriodException("Endless period can't be converted to array nor counted.");
1575 }
1576
1577 $state = [
1578 $this->key,
1579 $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null,
1580 $this->validationResult,
1581 ];
1582
1583 $result = iterator_to_array($this);
1584
1585 [$this->key, $this->carbonCurrent, $this->validationResult] = $state;
1586
1587 return $result;
1588 }
1589
1590 /**
1591 * Count dates in the date period.
1592 */
1593 public function count(): int
1594 {
1595 return \count($this->toArray());
1596 }
1597
1598 /**
1599 * Return the first date in the date period.
1600 */
1601 public function first(): ?CarbonInterface
1602 {
1603 if ($this->isUnfilteredAndEndLess()) {
1604 foreach ($this as $date) {
1605 $this->rewind();
1606
1607 return $date;
1608 }
1609
1610 return null;
1611 }
1612
1613 return ($this->toArray() ?: [])[0] ?? null;
1614 }
1615
1616 /**
1617 * Return the last date in the date period.
1618 */
1619 public function last(): ?CarbonInterface
1620 {
1621 $array = $this->toArray();
1622
1623 return $array ? $array[\count($array) - 1] : null;
1624 }
1625
1626 /**
1627 * Convert the date period into a string.
1628 */
1629 public function __toString(): string
1630 {
1631 return $this->toString();
1632 }
1633
1634 /**
1635 * Add aliases for setters.
1636 *
1637 * CarbonPeriod::days(3)->hours(5)->invert()
1638 * ->sinceNow()->until('2010-01-10')
1639 * ->filter(...)
1640 * ->count()
1641 *
1642 * Note: We use magic method to let static and instance aliases with the same names.
1643 */
1644 public function __call(string $method, array $parameters): mixed
1645 {
1646 if (static::hasMacro($method)) {
1647 return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters));
1648 }
1649
1650 $roundedValue = $this->callRoundMethod($method, $parameters);
1651
1652 if ($roundedValue !== null) {
1653 return $roundedValue;
1654 }
1655
1656 $count = \count($parameters);
1657
1658 switch ($method) {
1659 case 'start':
1660 case 'since':
1661 if ($count === 0) {
1662 return $this->getStartDate();
1663 }
1664
1665 self::setDefaultParameters($parameters, [
1666 [0, 'date', null],
1667 ]);
1668
1669 return $this->setStartDate(...$parameters);
1670
1671 case 'sinceNow':
1672 return $this->setStartDate(new Carbon(), ...$parameters);
1673
1674 case 'end':
1675 case 'until':
1676 if ($count === 0) {
1677 return $this->getEndDate();
1678 }
1679
1680 self::setDefaultParameters($parameters, [
1681 [0, 'date', null],
1682 ]);
1683
1684 return $this->setEndDate(...$parameters);
1685
1686 case 'untilNow':
1687 return $this->setEndDate(new Carbon(), ...$parameters);
1688
1689 case 'dates':
1690 case 'between':
1691 self::setDefaultParameters($parameters, [
1692 [0, 'start', null],
1693 [1, 'end', null],
1694 ]);
1695
1696 return $this->setDates(...$parameters);
1697
1698 case 'recurrences':
1699 case 'times':
1700 if ($count === 0) {
1701 return $this->getRecurrences();
1702 }
1703
1704 self::setDefaultParameters($parameters, [
1705 [0, 'recurrences', null],
1706 ]);
1707
1708 return $this->setRecurrences(...$parameters);
1709
1710 case 'options':
1711 if ($count === 0) {
1712 return $this->getOptions();
1713 }
1714
1715 self::setDefaultParameters($parameters, [
1716 [0, 'options', null],
1717 ]);
1718
1719 return $this->setOptions(...$parameters);
1720
1721 case 'toggle':
1722 self::setDefaultParameters($parameters, [
1723 [0, 'options', null],
1724 ]);
1725
1726 return $this->toggleOptions(...$parameters);
1727
1728 case 'filter':
1729 case 'push':
1730 return $this->addFilter(...$parameters);
1731
1732 case 'prepend':
1733 return $this->prependFilter(...$parameters);
1734
1735 case 'filters':
1736 if ($count === 0) {
1737 return $this->getFilters();
1738 }
1739
1740 self::setDefaultParameters($parameters, [
1741 [0, 'filters', []],
1742 ]);
1743
1744 return $this->setFilters(...$parameters);
1745
1746 case 'interval':
1747 case 'each':
1748 case 'every':
1749 case 'step':
1750 case 'stepBy':
1751 if ($count === 0) {
1752 return $this->getDateInterval();
1753 }
1754
1755 return $this->setDateInterval(...$parameters);
1756
1757 case 'invert':
1758 return $this->invertDateInterval();
1759
1760 case 'years':
1761 case 'year':
1762 case 'months':
1763 case 'month':
1764 case 'weeks':
1765 case 'week':
1766 case 'days':
1767 case 'dayz':
1768 case 'day':
1769 case 'hours':
1770 case 'hour':
1771 case 'minutes':
1772 case 'minute':
1773 case 'seconds':
1774 case 'second':
1775 case 'milliseconds':
1776 case 'millisecond':
1777 case 'microseconds':
1778 case 'microsecond':
1779 return $this->setDateInterval((
1780 // Override default P1D when instantiating via fluent setters.
1781 [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method]
1782 )(...$parameters));
1783 }
1784
1785 $dateClass = $this->dateClass;
1786
1787 if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) {
1788 throw new UnknownMethodException($method);
1789 }
1790
1791 return $this;
1792 }
1793
1794 /**
1795 * Set the instance's timezone from a string or object and apply it to start/end.
1796 */
1797 public function setTimezone(DateTimeZone|string|int $timezone): static
1798 {
1799 $self = $this->copyIfImmutable();
1800 $self->timezoneSetting = $timezone;
1801 $self->timezone = CarbonTimeZone::instance($timezone);
1802
1803 if ($self->startDate) {
1804 $self = $self->setStartDate($self->startDate->setTimezone($timezone));
1805 }
1806
1807 if ($self->endDate) {
1808 $self = $self->setEndDate($self->endDate->setTimezone($timezone));
1809 }
1810
1811 return $self;
1812 }
1813
1814 /**
1815 * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end.
1816 */
1817 public function shiftTimezone(DateTimeZone|string|int $timezone): static
1818 {
1819 $self = $this->copyIfImmutable();
1820 $self->timezoneSetting = $timezone;
1821 $self->timezone = CarbonTimeZone::instance($timezone);
1822
1823 if ($self->startDate) {
1824 $self = $self->setStartDate($self->startDate->shiftTimezone($timezone));
1825 }
1826
1827 if ($self->endDate) {
1828 $self = $self->setEndDate($self->endDate->shiftTimezone($timezone));
1829 }
1830
1831 return $self;
1832 }
1833
1834 /**
1835 * Returns the end is set, else calculated from start and recurrences.
1836 *
1837 * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval.
1838 *
1839 * @return CarbonInterface
1840 */
1841 public function calculateEnd(?string $rounding = null): CarbonInterface
1842 {
1843 if ($end = $this->getEndDate($rounding)) {
1844 return $end;
1845 }
1846
1847 if ($this->dateInterval->isEmpty()) {
1848 return $this->getStartDate($rounding);
1849 }
1850
1851 $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd();
1852
1853 if ($date && $rounding) {
1854 $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding);
1855 }
1856
1857 return $date;
1858 }
1859
1860 private function getEndFromRecurrences(): ?CarbonInterface
1861 {
1862 if ($this->carbonRecurrences === null) {
1863 throw new UnreachableException(
1864 "Could not calculate period end without either explicit end or recurrences.\n".
1865 "If you're looking for a forever-period, use ->setRecurrences(INF).",
1866 );
1867 }
1868
1869 if ($this->carbonRecurrences === INF) {
1870 $start = $this->getStartDate();
1871
1872 return $start < $start->avoidMutation()->add($this->getDateInterval())
1873 ? CarbonImmutable::endOfTime()
1874 : CarbonImmutable::startOfTime();
1875 }
1876
1877 if ($this->filters === [[static::RECURRENCES_FILTER, null]]) {
1878 return $this->getStartDate()->avoidMutation()->add(
1879 $this->getDateInterval()->times(
1880 $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1),
1881 ),
1882 );
1883 }
1884
1885 return null;
1886 }
1887
1888 private function iterateUntilEnd(): ?CarbonInterface
1889 {
1890 $attempts = 0;
1891 $date = null;
1892
1893 foreach ($this as $date) {
1894 if (++$attempts > static::END_MAX_ATTEMPTS) {
1895 throw new UnreachableException(
1896 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.',
1897 );
1898 }
1899 }
1900
1901 return $date;
1902 }
1903
1904 /**
1905 * Returns true if the current period overlaps the given one (if 1 parameter passed)
1906 * or the period between 2 dates (if 2 parameters passed).
1907 *
1908 * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart
1909 * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd
1910 *
1911 * @return bool
1912 */
1913 public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool
1914 {
1915 $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart;
1916
1917 if (!($range instanceof self)) {
1918 $range = static::create($range);
1919 }
1920
1921 [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd());
1922 [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd());
1923
1924 return $end > $rangeStart && $rangeEnd > $start;
1925 }
1926
1927 /**
1928 * Execute a given function on each date of the period.
1929 *
1930 * @example
1931 * ```
1932 * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) {
1933 * echo $date->diffInDays('2020-12-25')." days before Christmas!\n";
1934 * });
1935 * ```
1936 */
1937 public function forEach(callable $callback): void
1938 {
1939 foreach ($this as $date) {
1940 $callback($date);
1941 }
1942 }
1943
1944 /**
1945 * Execute a given function on each date of the period and yield the result of this function.
1946 *
1947 * @example
1948 * ```
1949 * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24');
1950 * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) {
1951 * return $date->diffInDays('2020-12-25').' days before Christmas!';
1952 * })));
1953 * ```
1954 */
1955 public function map(callable $callback): Generator
1956 {
1957 foreach ($this as $date) {
1958 yield $callback($date);
1959 }
1960 }
1961
1962 /**
1963 * Determines if the instance is equal to another.
1964 * Warning: if options differ, instances will never be equal.
1965 *
1966 * @see equalTo()
1967 */
1968 public function eq(mixed $period): bool
1969 {
1970 return $this->equalTo($period);
1971 }
1972
1973 /**
1974 * Determines if the instance is equal to another.
1975 * Warning: if options differ, instances will never be equal.
1976 */
1977 public function equalTo(mixed $period): bool
1978 {
1979 if (!($period instanceof self)) {
1980 $period = self::make($period);
1981 }
1982
1983 $end = $this->getEndDate();
1984
1985 return $period !== null
1986 && $this->getDateInterval()->eq($period->getDateInterval())
1987 && $this->getStartDate()->eq($period->getStartDate())
1988 && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences())
1989 && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE));
1990 }
1991
1992 /**
1993 * Determines if the instance is not equal to another.
1994 * Warning: if options differ, instances will never be equal.
1995 *
1996 * @see notEqualTo()
1997 */
1998 public function ne(mixed $period): bool
1999 {
2000 return $this->notEqualTo($period);
2001 }
2002
2003 /**
2004 * Determines if the instance is not equal to another.
2005 * Warning: if options differ, instances will never be equal.
2006 */
2007 public function notEqualTo(mixed $period): bool
2008 {
2009 return !$this->eq($period);
2010 }
2011
2012 /**
2013 * Determines if the start date is before another given date.
2014 * (Rather start/end are included by options is ignored.)
2015 */
2016 public function startsBefore(mixed $date = null): bool
2017 {
2018 return $this->getStartDate()->lessThan($this->resolveCarbon($date));
2019 }
2020
2021 /**
2022 * Determines if the start date is before or the same as a given date.
2023 * (Rather start/end are included by options is ignored.)
2024 */
2025 public function startsBeforeOrAt(mixed $date = null): bool
2026 {
2027 return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date));
2028 }
2029
2030 /**
2031 * Determines if the start date is after another given date.
2032 * (Rather start/end are included by options is ignored.)
2033 */
2034 public function startsAfter(mixed $date = null): bool
2035 {
2036 return $this->getStartDate()->greaterThan($this->resolveCarbon($date));
2037 }
2038
2039 /**
2040 * Determines if the start date is after or the same as a given date.
2041 * (Rather start/end are included by options is ignored.)
2042 */
2043 public function startsAfterOrAt(mixed $date = null): bool
2044 {
2045 return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date));
2046 }
2047
2048 /**
2049 * Determines if the start date is the same as a given date.
2050 * (Rather start/end are included by options is ignored.)
2051 */
2052 public function startsAt(mixed $date = null): bool
2053 {
2054 return $this->getStartDate()->equalTo($this->resolveCarbon($date));
2055 }
2056
2057 /**
2058 * Determines if the end date is before another given date.
2059 * (Rather start/end are included by options is ignored.)
2060 */
2061 public function endsBefore(mixed $date = null): bool
2062 {
2063 return $this->calculateEnd()->lessThan($this->resolveCarbon($date));
2064 }
2065
2066 /**
2067 * Determines if the end date is before or the same as a given date.
2068 * (Rather start/end are included by options is ignored.)
2069 */
2070 public function endsBeforeOrAt(mixed $date = null): bool
2071 {
2072 return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date));
2073 }
2074
2075 /**
2076 * Determines if the end date is after another given date.
2077 * (Rather start/end are included by options is ignored.)
2078 */
2079 public function endsAfter(mixed $date = null): bool
2080 {
2081 return $this->calculateEnd()->greaterThan($this->resolveCarbon($date));
2082 }
2083
2084 /**
2085 * Determines if the end date is after or the same as a given date.
2086 * (Rather start/end are included by options is ignored.)
2087 */
2088 public function endsAfterOrAt(mixed $date = null): bool
2089 {
2090 return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date));
2091 }
2092
2093 /**
2094 * Determines if the end date is the same as a given date.
2095 * (Rather start/end are included by options is ignored.)
2096 */
2097 public function endsAt(mixed $date = null): bool
2098 {
2099 return $this->calculateEnd()->equalTo($this->resolveCarbon($date));
2100 }
2101
2102 /**
2103 * Return true if start date is now or later.
2104 * (Rather start/end are included by options is ignored.)
2105 */
2106 public function isStarted(): bool
2107 {
2108 return $this->startsBeforeOrAt();
2109 }
2110
2111 /**
2112 * Return true if end date is now or later.
2113 * (Rather start/end are included by options is ignored.)
2114 */
2115 public function isEnded(): bool
2116 {
2117 return $this->endsBeforeOrAt();
2118 }
2119
2120 /**
2121 * Return true if now is between start date (included) and end date (excluded).
2122 * (Rather start/end are included by options is ignored.)
2123 */
2124 public function isInProgress(): bool
2125 {
2126 return $this->isStarted() && !$this->isEnded();
2127 }
2128
2129 /**
2130 * Round the current instance at the given unit with given precision if specified and the given function.
2131 */
2132 public function roundUnit(
2133 string $unit,
2134 DateInterval|float|int|string|null $precision = 1,
2135 callable|string $function = 'round',
2136 ): static {
2137 $self = $this->copyIfImmutable();
2138 $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function));
2139
2140 if ($self->endDate) {
2141 $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function));
2142 }
2143
2144 return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function));
2145 }
2146
2147 /**
2148 * Truncate the current instance at the given unit with given precision if specified.
2149 */
2150 public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static
2151 {
2152 return $this->roundUnit($unit, $precision, 'floor');
2153 }
2154
2155 /**
2156 * Ceil the current instance at the given unit with given precision if specified.
2157 */
2158 public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static
2159 {
2160 return $this->roundUnit($unit, $precision, 'ceil');
2161 }
2162
2163 /**
2164 * Round the current instance second with given precision if specified (else period interval is used).
2165 */
2166 public function round(
2167 DateInterval|float|int|string|null $precision = null,
2168 callable|string $function = 'round',
2169 ): static {
2170 return $this->roundWith(
2171 $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(),
2172 $function
2173 );
2174 }
2175
2176 /**
2177 * Round the current instance second with given precision if specified (else period interval is used).
2178 */
2179 public function floor(DateInterval|float|int|string|null $precision = null): static
2180 {
2181 return $this->round($precision, 'floor');
2182 }
2183
2184 /**
2185 * Ceil the current instance second with given precision if specified (else period interval is used).
2186 */
2187 public function ceil(DateInterval|float|int|string|null $precision = null): static
2188 {
2189 return $this->round($precision, 'ceil');
2190 }
2191
2192 /**
2193 * Specify data which should be serialized to JSON.
2194 *
2195 * @link https://php.net/manual/en/jsonserializable.jsonserialize.php
2196 *
2197 * @return CarbonInterface[]
2198 */
2199 public function jsonSerialize(): array
2200 {
2201 return $this->toArray();
2202 }
2203
2204 /**
2205 * Return true if the given date is between start and end.
2206 */
2207 public function contains(mixed $date = null): bool
2208 {
2209 $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : '');
2210 $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : '');
2211
2212 return $this->$startMethod($date) && $this->$endMethod($date);
2213 }
2214
2215 /**
2216 * Return true if the current period follows a given other period (with no overlap).
2217 * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31]
2218 * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options.
2219 */
2220 public function follows(mixed $period, mixed ...$arguments): bool
2221 {
2222 $period = $this->resolveCarbonPeriod($period, ...$arguments);
2223
2224 return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval()));
2225 }
2226
2227 /**
2228 * Return true if the given other period follows the current one (with no overlap).
2229 * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12]
2230 * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options.
2231 */
2232 public function isFollowedBy(mixed $period, mixed ...$arguments): bool
2233 {
2234 $period = $this->resolveCarbonPeriod($period, ...$arguments);
2235
2236 return $period->follows($this);
2237 }
2238
2239 /**
2240 * Return true if the given period either follows or is followed by the current one.
2241 *
2242 * @see follows()
2243 * @see isFollowedBy()
2244 */
2245 public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool
2246 {
2247 return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments);
2248 }
2249
2250 public function __debugInfo(): array
2251 {
2252 $info = $this->baseDebugInfo();
2253 unset(
2254 $info['start'],
2255 $info['end'],
2256 $info['interval'],
2257 $info['include_start_date'],
2258 $info['include_end_date'],
2259 $info['constructed'],
2260 $info["\0*\0constructed"],
2261 );
2262
2263 return $info;
2264 }
2265
2266 public function __unserialize(array $data): void
2267 {
2268 try {
2269 $values = array_combine(
2270 array_map(
2271 static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key),
2272 array_keys($data),
2273 ),
2274 $data,
2275 );
2276
2277 $this->initializeSerialization($values);
2278
2279 foreach ($values as $key => $value) {
2280 if ($value === null) {
2281 continue;
2282 }
2283
2284 $property = match ($key) {
2285 'tzName' => $this->setTimezone(...),
2286 'options' => $this->setOptions(...),
2287 'recurrences' => $this->setRecurrences(...),
2288 'current' => function (mixed $current): void {
2289 if (!($current instanceof CarbonInterface)) {
2290 $current = $this->resolveCarbon($current);
2291 }
2292
2293 $this->carbonCurrent = $current;
2294 },
2295 'start' => 'startDate',
2296 'interval' => $this->setDateInterval(...),
2297 'end' => 'endDate',
2298 'key' => null,
2299 'include_start_date' => function (bool $included): void {
2300 $this->excludeStartDate(!$included);
2301 },
2302 'include_end_date' => function (bool $included): void {
2303 $this->excludeEndDate(!$included);
2304 },
2305 default => $key,
2306 };
2307
2308 if ($property === null) {
2309 continue;
2310 }
2311
2312 if (\is_callable($property)) {
2313 $property($value);
2314
2315 continue;
2316 }
2317
2318 if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) {
2319 $value = ($value instanceof DateTime)
2320 ? Carbon::instance($value)
2321 : CarbonImmutable::instance($value);
2322 }
2323
2324 try {
2325 $this->$property = $value;
2326 } catch (Throwable) {
2327 // Must be ignored for backward-compatibility
2328 }
2329 }
2330
2331 if (\array_key_exists('carbonRecurrences', $values)) {
2332 $this->carbonRecurrences = $values['carbonRecurrences'];
2333 } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) {
2334 $this->carbonRecurrences = null;
2335 }
2336 } catch (Throwable $e) {
2337 // @codeCoverageIgnoreStart
2338 if (!method_exists(parent::class, '__unserialize')) {
2339 throw $e;
2340 }
2341
2342 parent::__unserialize($data);
2343 // @codeCoverageIgnoreEnd
2344 }
2345 }
2346
2347 /**
2348 * Update properties after removing built-in filters.
2349 */
2350 protected function updateInternalState(): void
2351 {
2352 if (!$this->hasFilter(static::END_DATE_FILTER)) {
2353 $this->endDate = null;
2354 }
2355
2356 if (!$this->hasFilter(static::RECURRENCES_FILTER)) {
2357 $this->carbonRecurrences = null;
2358 }
2359 }
2360
2361 /**
2362 * Create a filter tuple from raw parameters.
2363 *
2364 * Will create an automatic filter callback for one of Carbon's is* methods.
2365 */
2366 protected function createFilterTuple(array $parameters): array
2367 {
2368 $method = array_shift($parameters);
2369
2370 if (!$this->isCarbonPredicateMethod($method)) {
2371 return [$method, array_shift($parameters)];
2372 }
2373
2374 return [static fn ($date) => ([$date, $method])(...$parameters), $method];
2375 }
2376
2377 /**
2378 * Return whether given callable is a string pointing to one of Carbon's is* methods
2379 * and should be automatically converted to a filter callback.
2380 */
2381 protected function isCarbonPredicateMethod(callable|string $callable): bool
2382 {
2383 return \is_string($callable) && str_starts_with($callable, 'is') &&
2384 (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable));
2385 }
2386
2387 /**
2388 * Recurrences filter callback (limits number of recurrences).
2389 *
2390 * @SuppressWarnings(UnusedFormalParameter)
2391 */
2392 protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable
2393 {
2394 if ($key < $this->carbonRecurrences) {
2395 return true;
2396 }
2397
2398 return static::END_ITERATION;
2399 }
2400
2401 /**
2402 * End date filter callback.
2403 *
2404 * @return bool|static::END_ITERATION
2405 */
2406 protected function filterEndDate(CarbonInterface $current): bool|callable
2407 {
2408 if (!$this->isEndExcluded() && $current == $this->endDate) {
2409 return true;
2410 }
2411
2412 if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) {
2413 return true;
2414 }
2415
2416 return static::END_ITERATION;
2417 }
2418
2419 /**
2420 * End iteration filter callback.
2421 *
2422 * @return static::END_ITERATION
2423 */
2424 protected function endIteration(): callable
2425 {
2426 return static::END_ITERATION;
2427 }
2428
2429 /**
2430 * Handle change of the parameters.
2431 */
2432 protected function handleChangedParameters(): void
2433 {
2434 if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) {
2435 $this->dateClass = CarbonImmutable::class;
2436 } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) {
2437 $this->dateClass = Carbon::class;
2438 }
2439
2440 $this->validationResult = null;
2441 }
2442
2443 /**
2444 * Validate current date and stop iteration when necessary.
2445 *
2446 * Returns true when current date is valid, false if it is not, or static::END_ITERATION
2447 * when iteration should be stopped.
2448 *
2449 * @return bool|static::END_ITERATION
2450 */
2451 protected function validateCurrentDate(): bool|callable
2452 {
2453 if ($this->carbonCurrent === null) {
2454 $this->rewind();
2455 }
2456
2457 // Check after the first rewind to avoid repeating the initial validation.
2458 return $this->validationResult ?? ($this->validationResult = $this->checkFilters());
2459 }
2460
2461 /**
2462 * Check whether current value and key pass all the filters.
2463 *
2464 * @return bool|static::END_ITERATION
2465 */
2466 protected function checkFilters(): bool|callable
2467 {
2468 $current = $this->prepareForReturn($this->carbonCurrent);
2469
2470 foreach ($this->filters as $tuple) {
2471 $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this);
2472
2473 if ($result === static::END_ITERATION) {
2474 return static::END_ITERATION;
2475 }
2476
2477 if (!$result) {
2478 return false;
2479 }
2480 }
2481
2482 return true;
2483 }
2484
2485 /**
2486 * Prepare given date to be returned to the external logic.
2487 *
2488 * @param CarbonInterface $date
2489 *
2490 * @return CarbonInterface
2491 */
2492 protected function prepareForReturn(CarbonInterface $date)
2493 {
2494 $date = ([$this->dateClass, 'make'])($date);
2495
2496 if ($this->timezone) {
2497 return $date->setTimezone($this->timezone);
2498 }
2499
2500 return $date;
2501 }
2502
2503 /**
2504 * Keep incrementing the current date until a valid date is found or the iteration is ended.
2505 *
2506 * @throws RuntimeException
2507 */
2508 protected function incrementCurrentDateUntilValid(): void
2509 {
2510 $attempts = 0;
2511
2512 do {
2513 $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval);
2514
2515 $this->validationResult = null;
2516
2517 if (++$attempts > static::NEXT_MAX_ATTEMPTS) {
2518 throw new UnreachableException('Could not find next valid date.');
2519 }
2520 } while ($this->validateCurrentDate() === false);
2521 }
2522
2523 /**
2524 * Call given macro.
2525 */
2526 protected function callMacro(string $name, array $parameters): mixed
2527 {
2528 $macro = static::$macros[$name];
2529
2530 if ($macro instanceof Closure) {
2531 $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class);
2532
2533 return ($boundMacro ?: $macro)(...$parameters);
2534 }
2535
2536 return $macro(...$parameters);
2537 }
2538
2539 /**
2540 * Return the Carbon instance passed through, a now instance in the same timezone
2541 * if null given or parse the input if string given.
2542 *
2543 * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date
2544 *
2545 * @return \Carbon\CarbonInterface
2546 */
2547 protected function resolveCarbon($date = null)
2548 {
2549 return $this->getStartDate()->nowWithSameTz()->carbonize($date);
2550 }
2551
2552 /**
2553 * Resolve passed arguments or DatePeriod to a CarbonPeriod object.
2554 */
2555 protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self
2556 {
2557 if ($period instanceof self) {
2558 return $period;
2559 }
2560
2561 return $period instanceof DatePeriod
2562 ? static::instance($period)
2563 : static::create($period, ...$arguments);
2564 }
2565
2566 private function orderCouple($first, $second): array
2567 {
2568 return $first > $second ? [$second, $first] : [$first, $second];
2569 }
2570
2571 private function makeDateTime($value): ?DateTimeInterface
2572 {
2573 if ($value instanceof DateTimeInterface) {
2574 return $value;
2575 }
2576
2577 if ($value instanceof WeekDay || $value instanceof Month) {
2578 $dateClass = $this->dateClass;
2579
2580 return new $dateClass($value, $this->timezoneSetting);
2581 }
2582
2583 if (\is_string($value)) {
2584 $value = trim($value);
2585
2586 if (!preg_match('/^P[\dT]/', $value) &&
2587 !preg_match('/^R\d/', $value) &&
2588 preg_match('/[a-z\d]/i', $value)
2589 ) {
2590 $dateClass = $this->dateClass;
2591
2592 return $dateClass::parse($value, $this->timezoneSetting);
2593 }
2594 }
2595
2596 return null;
2597 }
2598
2599 private function isInfiniteDate($date): bool
2600 {
2601 return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime());
2602 }
2603
2604 private function rawDate($date): ?DateTimeInterface
2605 {
2606 if ($date === false || $date === null) {
2607 return null;
2608 }
2609
2610 if ($date instanceof CarbonInterface) {
2611 return $date->isMutable()
2612 ? $date->toDateTime()
2613 : $date->toDateTimeImmutable();
2614 }
2615
2616 if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) {
2617 return $date;
2618 }
2619
2620 $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class;
2621
2622 return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone());
2623 }
2624
2625 private static function setDefaultParameters(array &$parameters, array $defaults): void
2626 {
2627 foreach ($defaults as [$index, $name, $value]) {
2628 if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) {
2629 $parameters[$index] = $value;
2630 }
2631 }
2632 }
2633
2634 private function setFromAssociativeArray(array $parameters): void
2635 {
2636 if (isset($parameters['start'])) {
2637 $this->setStartDate($parameters['start']);
2638 }
2639
2640 if (isset($parameters['start'])) {
2641 $this->setStartDate($parameters['start']);
2642 }
2643
2644 if (isset($parameters['end'])) {
2645 $this->setEndDate($parameters['end']);
2646 }
2647
2648 if (isset($parameters['recurrences'])) {
2649 $this->setRecurrences($parameters['recurrences']);
2650 }
2651
2652 if (isset($parameters['interval'])) {
2653 $this->setDateInterval($parameters['interval']);
2654 }
2655
2656 if (isset($parameters['options'])) {
2657 $this->setOptions($parameters['options']);
2658 }
2659 }
2660
2661 private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array
2662 {
2663 $this->setTimezone($timezone);
2664
2665 if (\is_string($originalArguments['start'] ?? null)) {
2666 $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']);
2667 }
2668
2669 if (\is_string($originalArguments['end'] ?? null)) {
2670 $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']);
2671 }
2672
2673 return $sortedArguments;
2674 }
2675
2676 private function initializeSerialization(array $values): void
2677 {
2678 $serializationBase = [
2679 'start' => $values['start'] ?? $values['startDate'] ?? null,
2680 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null,
2681 'end' => $values['end'] ?? $values['endDate'] ?? null,
2682 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null,
2683 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)),
2684 'include_start_date' => $values['include_start_date'] ?? true,
2685 'include_end_date' => $values['include_end_date'] ?? false,
2686 ];
2687
2688 foreach (['start', 'current', 'end'] as $dateProperty) {
2689 if ($serializationBase[$dateProperty] instanceof Carbon) {
2690 $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime();
2691 } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) {
2692 $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable();
2693 }
2694 }
2695
2696 if ($serializationBase['interval'] instanceof CarbonInterval) {
2697 $serializationBase['interval'] = $serializationBase['interval']->toDateInterval();
2698 }
2699
2700 // @codeCoverageIgnoreStart
2701 if (method_exists(parent::class, '__unserialize')) {
2702 parent::__unserialize($serializationBase);
2703
2704 return;
2705 }
2706
2707 $excludeStart = !($values['include_start_date'] ?? true);
2708 $includeEnd = $values['include_end_date'] ?? true;
2709
2710 parent::__construct(
2711 $serializationBase['start'],
2712 $serializationBase['interval'],
2713 $serializationBase['end'] ?? $serializationBase['recurrences'],
2714 ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0),
2715 );
2716 // @codeCoverageIgnoreEnd
2717 }
2718 }