Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/CarbonInterval.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\BadFluentConstructorException;
18 use Carbon\Exceptions\BadFluentSetterException;
19 use Carbon\Exceptions\InvalidCastException;
20 use Carbon\Exceptions\InvalidFormatException;
21 use Carbon\Exceptions\InvalidIntervalException;
22 use Carbon\Exceptions\OutOfRangeException;
23 use Carbon\Exceptions\ParseErrorException;
24 use Carbon\Exceptions\UnitNotConfiguredException;
25 use Carbon\Exceptions\UnknownGetterException;
26 use Carbon\Exceptions\UnknownSetterException;
27 use Carbon\Exceptions\UnknownUnitException;
28 use Carbon\Traits\IntervalRounding;
29 use Carbon\Traits\IntervalStep;
30 use Carbon\Traits\LocalFactory;
31 use Carbon\Traits\MagicParameter;
32 use Carbon\Traits\Mixin;
33 use Carbon\Traits\Options;
34 use Carbon\Traits\ToStringFormat;
35 use Closure;
36 use DateInterval;
37 use DateTime;
38 use DateTimeInterface;
39 use DateTimeZone;
40 use Exception;
41 use InvalidArgumentException;
42 use ReflectionException;
43 use ReturnTypeWillChange;
44 use RuntimeException;
45 use Symfony\Contracts\Translation\TranslatorInterface;
46 use Throwable;
47
48 /**
49 * A simple API extension for DateInterval.
50 * The implementation provides helpers to handle weeks but only days are saved.
51 * Weeks are calculated based on the total days of the current instance.
52 *
53 * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2)
54 * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6)
55 * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2)
56 * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17)
57 * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20)
58 * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5)
59 * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34)
60 * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567)
61 * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890)
62 * @property int $microExcludeMilli Remaining microseconds without the milliseconds.
63 * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7).
64 * @property int $daysExcludeWeeks alias of dayzExcludeWeeks
65 * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5)
66 * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357)
67 * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548)
68 * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833)
69 * @property-read float $totalDayz Alias for totalDays.
70 * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083)
71 * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5)
72 * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890)
73 * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890)
74 * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890)
75 * @property-read string $locale locale of the current instance
76 *
77 * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance.
78 * @method static CarbonInterval year($years = 1) Alias for years()
79 * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance.
80 * @method static CarbonInterval month($months = 1) Alias for months()
81 * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance.
82 * @method static CarbonInterval week($weeks = 1) Alias for weeks()
83 * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance.
84 * @method static CarbonInterval dayz($days = 1) Alias for days()
85 * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance.
86 * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks()
87 * @method static CarbonInterval day($days = 1) Alias for days()
88 * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance.
89 * @method static CarbonInterval hour($hours = 1) Alias for hours()
90 * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance.
91 * @method static CarbonInterval minute($minutes = 1) Alias for minutes()
92 * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance.
93 * @method static CarbonInterval second($seconds = 1) Alias for seconds()
94 * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance.
95 * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds()
96 * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance.
97 * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds()
98 * @method $this addYears(int $years) Add given number of years to the current interval
99 * @method $this subYears(int $years) Subtract given number of years to the current interval
100 * @method $this addMonths(int $months) Add given number of months to the current interval
101 * @method $this subMonths(int $months) Subtract given number of months to the current interval
102 * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval
103 * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval
104 * @method $this addDays(int|float $days) Add given number of days to the current interval
105 * @method $this subDays(int|float $days) Subtract given number of days to the current interval
106 * @method $this addHours(int|float $hours) Add given number of hours to the current interval
107 * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval
108 * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval
109 * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval
110 * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval
111 * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval
112 * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval
113 * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval
114 * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval
115 * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval
116 * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function.
117 * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function.
118 * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision.
119 * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision.
120 * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision.
121 * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision.
122 * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function.
123 * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function.
124 * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision.
125 * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision.
126 * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision.
127 * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision.
128 * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
129 * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
130 * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision.
131 * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision.
132 * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision.
133 * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision.
134 * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
135 * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function.
136 * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision.
137 * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision.
138 * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision.
139 * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision.
140 * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function.
141 * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function.
142 * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision.
143 * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision.
144 * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision.
145 * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision.
146 * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function.
147 * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function.
148 * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision.
149 * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision.
150 * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision.
151 * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision.
152 * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function.
153 * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function.
154 * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision.
155 * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision.
156 * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision.
157 * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision.
158 * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function.
159 * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function.
160 * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision.
161 * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision.
162 * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision.
163 * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision.
164 * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function.
165 * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function.
166 * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision.
167 * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision.
168 * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision.
169 * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision.
170 * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function.
171 * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function.
172 * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision.
173 * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision.
174 * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision.
175 * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision.
176 * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function.
177 * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function.
178 * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision.
179 * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision.
180 * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision.
181 * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision.
182 * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function.
183 * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function.
184 * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision.
185 * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision.
186 * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision.
187 * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision.
188 * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function.
189 * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function.
190 * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision.
191 * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision.
192 * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision.
193 * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision.
194 */
195 class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue
196 {
197 use LocalFactory;
198 use IntervalRounding;
199 use IntervalStep;
200 use MagicParameter;
201 use Mixin {
202 Mixin::mixin as baseMixin;
203 }
204 use Options;
205 use ToStringFormat;
206
207 /**
208 * Unlimited parts for forHumans() method.
209 *
210 * INF constant can be used instead.
211 */
212 public const NO_LIMIT = -1;
213
214 public const POSITIVE = 1;
215 public const NEGATIVE = -1;
216
217 /**
218 * Interval spec period designators
219 */
220 public const PERIOD_PREFIX = 'P';
221 public const PERIOD_YEARS = 'Y';
222 public const PERIOD_MONTHS = 'M';
223 public const PERIOD_DAYS = 'D';
224 public const PERIOD_TIME_PREFIX = 'T';
225 public const PERIOD_HOURS = 'H';
226 public const PERIOD_MINUTES = 'M';
227 public const PERIOD_SECONDS = 'S';
228
229 public const SPECIAL_TRANSLATIONS = [
230 1 => [
231 'option' => CarbonInterface::ONE_DAY_WORDS,
232 'future' => 'diff_tomorrow',
233 'past' => 'diff_yesterday',
234 ],
235 2 => [
236 'option' => CarbonInterface::TWO_DAY_WORDS,
237 'future' => 'diff_after_tomorrow',
238 'past' => 'diff_before_yesterday',
239 ],
240 ];
241
242 protected static ?array $cascadeFactors = null;
243
244 protected static array $formats = [
245 'y' => 'y',
246 'Y' => 'y',
247 'o' => 'y',
248 'm' => 'm',
249 'n' => 'm',
250 'W' => 'weeks',
251 'd' => 'd',
252 'j' => 'd',
253 'z' => 'd',
254 'h' => 'h',
255 'g' => 'h',
256 'H' => 'h',
257 'G' => 'h',
258 'i' => 'i',
259 's' => 's',
260 'u' => 'micro',
261 'v' => 'milli',
262 ];
263
264 private static ?array $flipCascadeFactors = null;
265
266 private static bool $floatSettersEnabled = false;
267
268 /**
269 * The registered macros.
270 */
271 protected static array $macros = [];
272
273 /**
274 * Timezone handler for settings() method.
275 */
276 protected DateTimeZone|string|int|null $timezoneSetting = null;
277
278 /**
279 * The input used to create the interval.
280 */
281 protected mixed $originalInput = null;
282
283 /**
284 * Start date if interval was created from a difference between 2 dates.
285 */
286 protected ?CarbonInterface $startDate = null;
287
288 /**
289 * End date if interval was created from a difference between 2 dates.
290 */
291 protected ?CarbonInterface $endDate = null;
292
293 /**
294 * End date if interval was created from a difference between 2 dates.
295 */
296 protected ?DateInterval $rawInterval = null;
297
298 /**
299 * Flag if the interval was made from a diff with absolute flag on.
300 */
301 protected bool $absolute = false;
302
303 protected ?array $initialValues = null;
304
305 /**
306 * Set the instance's timezone from a string or object.
307 */
308 public function setTimezone(DateTimeZone|string|int $timezone): static
309 {
310 $this->timezoneSetting = $timezone;
311 $this->checkStartAndEnd();
312
313 if ($this->startDate) {
314 $this->startDate = $this->startDate
315 ->avoidMutation()
316 ->setTimezone($timezone);
317 $this->rawInterval = null;
318 }
319
320 if ($this->endDate) {
321 $this->endDate = $this->endDate
322 ->avoidMutation()
323 ->setTimezone($timezone);
324 $this->rawInterval = null;
325 }
326
327 return $this;
328 }
329
330 /**
331 * Set the instance's timezone from a string or object and add/subtract the offset difference.
332 */
333 public function shiftTimezone(DateTimeZone|string|int $timezone): static
334 {
335 $this->timezoneSetting = $timezone;
336 $this->checkStartAndEnd();
337
338 if ($this->startDate) {
339 $this->startDate = $this->startDate
340 ->avoidMutation()
341 ->shiftTimezone($timezone);
342 $this->rawInterval = null;
343 }
344
345 if ($this->endDate) {
346 $this->endDate = $this->endDate
347 ->avoidMutation()
348 ->shiftTimezone($timezone);
349 $this->rawInterval = null;
350 }
351
352 return $this;
353 }
354
355 /**
356 * Mapping of units and factors for cascading.
357 *
358 * Should only be modified by changing the factors or referenced constants.
359 */
360 public static function getCascadeFactors(): array
361 {
362 return static::$cascadeFactors ?: static::getDefaultCascadeFactors();
363 }
364
365 protected static function getDefaultCascadeFactors(): array
366 {
367 return [
368 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'],
369 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'],
370 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'],
371 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'],
372 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'],
373 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'],
374 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'],
375 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'],
376 ];
377 }
378
379 /**
380 * Set default cascading factors for ->cascade() method.
381 *
382 * @param array $cascadeFactors
383 */
384 public static function setCascadeFactors(array $cascadeFactors)
385 {
386 self::$flipCascadeFactors = null;
387 static::$cascadeFactors = $cascadeFactors;
388 }
389
390 /**
391 * This option allow you to opt-in for the Carbon 3 behavior where float
392 * values will no longer be cast to integer (so truncated).
393 *
394 * ⚠️ This settings will be applied globally, which mean your whole application
395 * code including the third-party dependencies that also may use Carbon will
396 * adopt the new behavior.
397 */
398 public static function enableFloatSetters(bool $floatSettersEnabled = true): void
399 {
400 self::$floatSettersEnabled = $floatSettersEnabled;
401 }
402
403 ///////////////////////////////////////////////////////////////////
404 //////////////////////////// CONSTRUCTORS /////////////////////////
405 ///////////////////////////////////////////////////////////////////
406
407 /**
408 * Create a new CarbonInterval instance.
409 *
410 * @param Closure|DateInterval|string|int|null $years
411 * @param int|float|null $months
412 * @param int|float|null $weeks
413 * @param int|float|null $days
414 * @param int|float|null $hours
415 * @param int|float|null $minutes
416 * @param int|float|null $seconds
417 * @param int|float|null $microseconds
418 *
419 * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval.
420 */
421 public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null)
422 {
423 $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args();
424
425 if ($years instanceof Closure) {
426 $this->step = $years;
427 $years = null;
428 }
429
430 if ($years instanceof DateInterval) {
431 parent::__construct(static::getDateIntervalSpec($years));
432 $this->f = $years->f;
433 self::copyNegativeUnits($years, $this);
434
435 return;
436 }
437
438 $spec = $years;
439 $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec));
440
441 if (!$isStringSpec || (float) $years) {
442 $spec = static::PERIOD_PREFIX;
443
444 $spec .= $years > 0 ? $years.static::PERIOD_YEARS : '';
445 $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : '';
446
447 $specDays = 0;
448 $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0;
449 $specDays += $days > 0 ? $days : 0;
450
451 $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : '';
452
453 if ($hours > 0 || $minutes > 0 || $seconds > 0) {
454 $spec .= static::PERIOD_TIME_PREFIX;
455 $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : '';
456 $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : '';
457 $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : '';
458 }
459
460 if ($spec === static::PERIOD_PREFIX) {
461 // Allow the zero interval.
462 $spec .= '0'.static::PERIOD_YEARS;
463 }
464 }
465
466 try {
467 parent::__construct($spec);
468 } catch (Throwable $exception) {
469 try {
470 parent::__construct('PT0S');
471
472 if ($isStringSpec) {
473 if (!preg_match('/^P
474 (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)?
475 (?:(?<month>[+-]?\d*(?:\.\d+)?)M)?
476 (?:(?<week>[+-]?\d*(?:\.\d+)?)W)?
477 (?:(?<day>[+-]?\d*(?:\.\d+)?)D)?
478 (?:T
479 (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)?
480 (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)?
481 (?:(?<second>[+-]?\d*(?:\.\d+)?)S)?
482 )?
483 $/x', $spec, $match)) {
484 throw new InvalidArgumentException("Invalid duration: $spec");
485 }
486
487 $years = (float) ($match['year'] ?? 0);
488 $this->assertSafeForInteger('year', $years);
489 $months = (float) ($match['month'] ?? 0);
490 $this->assertSafeForInteger('month', $months);
491 $weeks = (float) ($match['week'] ?? 0);
492 $this->assertSafeForInteger('week', $weeks);
493 $days = (float) ($match['day'] ?? 0);
494 $this->assertSafeForInteger('day', $days);
495 $hours = (float) ($match['hour'] ?? 0);
496 $this->assertSafeForInteger('hour', $hours);
497 $minutes = (float) ($match['minute'] ?? 0);
498 $this->assertSafeForInteger('minute', $minutes);
499 $seconds = (float) ($match['second'] ?? 0);
500 $this->assertSafeForInteger('second', $seconds);
501 $microseconds = (int) str_pad(
502 substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6),
503 6,
504 '0',
505 );
506 }
507
508 $totalDays = (($weeks * static::getDaysPerWeek()) + $days);
509 $this->assertSafeForInteger('days total (including weeks)', $totalDays);
510
511 $this->y = (int) $years;
512 $this->m = (int) $months;
513 $this->d = (int) $totalDays;
514 $this->h = (int) $hours;
515 $this->i = (int) $minutes;
516 $this->s = (int) $seconds;
517 $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND);
518 $this->f = $secondFloatPart;
519 $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND);
520 $intervalSeconds = $seconds - $secondFloatPart;
521
522 if (
523 ((float) $this->y) !== $years ||
524 ((float) $this->m) !== $months ||
525 ((float) $this->d) !== $totalDays ||
526 ((float) $this->h) !== $hours ||
527 ((float) $this->i) !== $minutes ||
528 ((float) $this->s) !== $intervalSeconds ||
529 $intervalMicroseconds !== ((int) $microseconds)
530 ) {
531 $this->add(static::fromString(
532 ($years - $this->y).' years '.
533 ($months - $this->m).' months '.
534 ($totalDays - $this->d).' days '.
535 ($hours - $this->h).' hours '.
536 ($minutes - $this->i).' minutes '.
537 number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '.
538 ($microseconds - $intervalMicroseconds).' microseconds ',
539 ));
540 }
541 } catch (Throwable $secondException) {
542 throw $secondException instanceof OutOfRangeException ? $secondException : $exception;
543 }
544 }
545
546 if ($microseconds !== null) {
547 $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND;
548 }
549
550 foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) {
551 if ($$unit < 0) {
552 $this->set($unit, $$unit);
553 }
554 }
555 }
556
557 /**
558 * Returns the factor for a given source-to-target couple.
559 *
560 * @param string $source
561 * @param string $target
562 *
563 * @return int|float|null
564 */
565 public static function getFactor($source, $target)
566 {
567 $source = self::standardizeUnit($source);
568 $target = self::standardizeUnit($target);
569 $factors = self::getFlipCascadeFactors();
570
571 if (isset($factors[$source])) {
572 [$to, $factor] = $factors[$source];
573
574 if ($to === $target) {
575 return $factor;
576 }
577
578 return $factor * static::getFactor($to, $target);
579 }
580
581 return null;
582 }
583
584 /**
585 * Returns the factor for a given source-to-target couple if set,
586 * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK.
587 *
588 * @param string $source
589 * @param string $target
590 *
591 * @return int|float|null
592 */
593 public static function getFactorWithDefault($source, $target)
594 {
595 $factor = self::getFactor($source, $target);
596
597 if ($factor) {
598 return $factor;
599 }
600
601 static $defaults = [
602 'month' => ['year' => Carbon::MONTHS_PER_YEAR],
603 'week' => ['month' => Carbon::WEEKS_PER_MONTH],
604 'day' => ['week' => Carbon::DAYS_PER_WEEK],
605 'hour' => ['day' => Carbon::HOURS_PER_DAY],
606 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR],
607 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE],
608 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND],
609 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND],
610 ];
611
612 return $defaults[$source][$target] ?? null;
613 }
614
615 /**
616 * Returns current config for days per week.
617 *
618 * @return int|float
619 */
620 public static function getDaysPerWeek()
621 {
622 return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK;
623 }
624
625 /**
626 * Returns current config for hours per day.
627 *
628 * @return int|float
629 */
630 public static function getHoursPerDay()
631 {
632 return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY;
633 }
634
635 /**
636 * Returns current config for minutes per hour.
637 *
638 * @return int|float
639 */
640 public static function getMinutesPerHour()
641 {
642 return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR;
643 }
644
645 /**
646 * Returns current config for seconds per minute.
647 *
648 * @return int|float
649 */
650 public static function getSecondsPerMinute()
651 {
652 return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE;
653 }
654
655 /**
656 * Returns current config for microseconds per second.
657 *
658 * @return int|float
659 */
660 public static function getMillisecondsPerSecond()
661 {
662 return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND;
663 }
664
665 /**
666 * Returns current config for microseconds per second.
667 *
668 * @return int|float
669 */
670 public static function getMicrosecondsPerMillisecond()
671 {
672 return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND;
673 }
674
675 /**
676 * Create a new CarbonInterval instance from specific values.
677 * This is an alias for the constructor that allows better fluent
678 * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than
679 * (new CarbonInterval(1))->fn().
680 *
681 * @param int $years
682 * @param int $months
683 * @param int $weeks
684 * @param int $days
685 * @param int $hours
686 * @param int $minutes
687 * @param int $seconds
688 * @param int $microseconds
689 *
690 * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval.
691 *
692 * @return static
693 */
694 public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null)
695 {
696 return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds);
697 }
698
699 /**
700 * Parse a string into a new CarbonInterval object according to the specified format.
701 *
702 * @example
703 * ```
704 * echo Carboninterval::createFromFormat('H:i', '1:30');
705 * ```
706 *
707 * @param string $format Format of the $interval input string
708 * @param string|null $interval Input string to convert into an interval
709 *
710 * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval.
711 *
712 * @return static
713 */
714 public static function createFromFormat(string $format, ?string $interval): static
715 {
716 $instance = new static(0);
717 $length = mb_strlen($format);
718
719 if (preg_match('/s([,.])([uv])$/', $format, $match)) {
720 $interval = explode($match[1], $interval);
721 $index = \count($interval) - 1;
722 $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0');
723 $interval = implode($match[1], $interval);
724 }
725
726 $interval ??= '';
727
728 for ($index = 0; $index < $length; $index++) {
729 $expected = mb_substr($format, $index, 1);
730 $nextCharacter = mb_substr($interval, 0, 1);
731 $unit = static::$formats[$expected] ?? null;
732
733 if ($unit) {
734 if (!preg_match('/^-?\d+/', $interval, $match)) {
735 throw new ParseErrorException('number', $nextCharacter);
736 }
737
738 $interval = mb_substr($interval, mb_strlen($match[0]));
739 self::incrementUnit($instance, $unit, (int) ($match[0]));
740
741 continue;
742 }
743
744 if ($nextCharacter !== $expected) {
745 throw new ParseErrorException(
746 "'$expected'",
747 $nextCharacter,
748 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n".
749 'See https://php.net/manual/en/function.date.php for their meaning',
750 );
751 }
752
753 $interval = mb_substr($interval, 1);
754 }
755
756 if ($interval !== '') {
757 throw new ParseErrorException(
758 'end of string',
759 $interval,
760 );
761 }
762
763 return $instance;
764 }
765
766 /**
767 * Return the original source used to create the current interval.
768 *
769 * @return array|int|string|DateInterval|mixed|null
770 */
771 public function original()
772 {
773 return $this->originalInput;
774 }
775
776 /**
777 * Return the start date if interval was created from a difference between 2 dates.
778 *
779 * @return CarbonInterface|null
780 */
781 public function start(): ?CarbonInterface
782 {
783 $this->checkStartAndEnd();
784
785 return $this->startDate;
786 }
787
788 /**
789 * Return the end date if interval was created from a difference between 2 dates.
790 *
791 * @return CarbonInterface|null
792 */
793 public function end(): ?CarbonInterface
794 {
795 $this->checkStartAndEnd();
796
797 return $this->endDate;
798 }
799
800 /**
801 * Get rid of the original input, start date and end date that may be kept in memory.
802 *
803 * @return $this
804 */
805 public function optimize(): static
806 {
807 $this->originalInput = null;
808 $this->startDate = null;
809 $this->endDate = null;
810 $this->rawInterval = null;
811 $this->absolute = false;
812
813 return $this;
814 }
815
816 /**
817 * Get a copy of the instance.
818 *
819 * @return static
820 */
821 public function copy(): static
822 {
823 $date = new static(0);
824 $date->copyProperties($this);
825 $date->step = $this->step;
826
827 return $date;
828 }
829
830 /**
831 * Get a copy of the instance.
832 *
833 * @return static
834 */
835 public function clone(): static
836 {
837 return $this->copy();
838 }
839
840 /**
841 * Provide static helpers to create instances. Allows CarbonInterval::years(3).
842 *
843 * Note: This is done using the magic method to allow static and instance methods to
844 * have the same names.
845 *
846 * @param string $method magic method name called
847 * @param array $parameters parameters list
848 *
849 * @return static|mixed|null
850 */
851 public static function __callStatic(string $method, array $parameters)
852 {
853 try {
854 $interval = new static(0);
855 $localStrictModeEnabled = $interval->localStrictModeEnabled;
856 $interval->localStrictModeEnabled = true;
857
858 $result = static::hasMacro($method)
859 ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) {
860 return $interval->callMacro($method, $parameters);
861 })
862 : $interval->$method(...$parameters);
863
864 $interval->localStrictModeEnabled = $localStrictModeEnabled;
865
866 return $result;
867 } catch (BadFluentSetterException $exception) {
868 if (Carbon::isStrictModeEnabled()) {
869 throw new BadFluentConstructorException($method, 0, $exception);
870 }
871
872 return null;
873 }
874 }
875
876 /**
877 * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance.
878 *
879 * @param array $dump data as exported by var_export()
880 *
881 * @return static
882 */
883 #[ReturnTypeWillChange]
884 public static function __set_state($dump)
885 {
886 /** @noinspection PhpVoidFunctionResultUsedInspection */
887 /** @var DateInterval $dateInterval */
888 $dateInterval = parent::__set_state($dump);
889
890 return static::instance($dateInterval);
891 }
892
893 /**
894 * Return the current context from inside a macro callee or a new one if static.
895 *
896 * @return static
897 */
898 protected static function this(): static
899 {
900 return end(static::$macroContextStack) ?: new static(0);
901 }
902
903 /**
904 * Creates a CarbonInterval from string.
905 *
906 * Format:
907 *
908 * Suffix | Unit | Example | DateInterval expression
909 * -------|---------|---------|------------------------
910 * y | years | 1y | P1Y
911 * mo | months | 3mo | P3M
912 * w | weeks | 2w | P2W
913 * d | days | 28d | P28D
914 * h | hours | 4h | PT4H
915 * m | minutes | 12m | PT12M
916 * s | seconds | 59s | PT59S
917 *
918 * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds.
919 *
920 * Special cases:
921 * - An empty string will return a zero interval
922 * - Fractions are allowed for weeks, days, hours and minutes and will be converted
923 * and rounded to the next smaller value (caution: 0.5w = 4d)
924 *
925 * @param string $intervalDefinition
926 *
927 * @throws InvalidIntervalException
928 *
929 * @return static
930 */
931 public static function fromString(string $intervalDefinition): static
932 {
933 if (empty($intervalDefinition)) {
934 return self::withOriginal(new static(0), $intervalDefinition);
935 }
936
937 $years = 0;
938 $months = 0;
939 $weeks = 0;
940 $days = 0;
941 $hours = 0;
942 $minutes = 0;
943 $seconds = 0;
944 $milliseconds = 0;
945 $microseconds = 0;
946
947 $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i';
948 preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER);
949
950 while ([$part, $value, $unit] = array_shift($parts)) {
951 $intValue = (int) $value;
952 $fraction = (float) $value - $intValue;
953
954 // Fix calculation precision
955 switch (round($fraction, 6)) {
956 case 1:
957 $fraction = 0;
958 $intValue++;
959
960 break;
961 case 0:
962 $fraction = 0;
963
964 break;
965 }
966
967 switch ($unit === 'µs' ? 'µs' : strtolower($unit)) {
968 case 'millennia':
969 case 'millennium':
970 $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM;
971
972 break;
973
974 case 'century':
975 case 'centuries':
976 $years += $intValue * CarbonInterface::YEARS_PER_CENTURY;
977
978 break;
979
980 case 'decade':
981 case 'decades':
982 $years += $intValue * CarbonInterface::YEARS_PER_DECADE;
983
984 break;
985
986 case 'year':
987 case 'years':
988 case 'y':
989 case 'yr':
990 case 'yrs':
991 $years += $intValue;
992
993 break;
994
995 case 'quarter':
996 case 'quarters':
997 $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER;
998
999 break;
1000
1001 case 'month':
1002 case 'months':
1003 case 'mo':
1004 case 'mos':
1005 $months += $intValue;
1006
1007 break;
1008
1009 case 'week':
1010 case 'weeks':
1011 case 'w':
1012 $weeks += $intValue;
1013
1014 if ($fraction) {
1015 $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd'];
1016 }
1017
1018 break;
1019
1020 case 'day':
1021 case 'days':
1022 case 'd':
1023 $days += $intValue;
1024
1025 if ($fraction) {
1026 $parts[] = [null, $fraction * static::getHoursPerDay(), 'h'];
1027 }
1028
1029 break;
1030
1031 case 'hour':
1032 case 'hours':
1033 case 'h':
1034 $hours += $intValue;
1035
1036 if ($fraction) {
1037 $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm'];
1038 }
1039
1040 break;
1041
1042 case 'minute':
1043 case 'minutes':
1044 case 'm':
1045 $minutes += $intValue;
1046
1047 if ($fraction) {
1048 $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's'];
1049 }
1050
1051 break;
1052
1053 case 'second':
1054 case 'seconds':
1055 case 's':
1056 $seconds += $intValue;
1057
1058 if ($fraction) {
1059 $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms'];
1060 }
1061
1062 break;
1063
1064 case 'millisecond':
1065 case 'milliseconds':
1066 case 'milli':
1067 case 'ms':
1068 $milliseconds += $intValue;
1069
1070 if ($fraction) {
1071 $microseconds += round($fraction * static::getMicrosecondsPerMillisecond());
1072 }
1073
1074 break;
1075
1076 case 'microsecond':
1077 case 'microseconds':
1078 case 'micro':
1079 case 'µs':
1080 $microseconds += $intValue;
1081
1082 break;
1083
1084 default:
1085 throw new InvalidIntervalException(
1086 "Invalid part $part in definition $intervalDefinition",
1087 );
1088 }
1089 }
1090
1091 return self::withOriginal(
1092 new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds),
1093 $intervalDefinition,
1094 );
1095 }
1096
1097 /**
1098 * Creates a CarbonInterval from string using a different locale.
1099 *
1100 * @param string $interval interval string in the given language (may also contain English).
1101 * @param string|null $locale if locale is null or not specified, current global locale will be used instead.
1102 *
1103 * @return static
1104 */
1105 public static function parseFromLocale(string $interval, ?string $locale = null): static
1106 {
1107 return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE));
1108 }
1109
1110 /**
1111 * Create an interval from the difference between 2 dates.
1112 *
1113 * @param \Carbon\Carbon|\DateTimeInterface|mixed $start
1114 * @param \Carbon\Carbon|\DateTimeInterface|mixed $end
1115 *
1116 * @return static
1117 */
1118 public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static
1119 {
1120 $start = $start instanceof CarbonInterface ? $start : Carbon::make($start);
1121 $end = $end instanceof CarbonInterface ? $end : Carbon::make($end);
1122 $rawInterval = $start->diffAsDateInterval($end, $absolute);
1123 $interval = static::instance($rawInterval, $skip);
1124
1125 $interval->absolute = $absolute;
1126 $interval->rawInterval = $rawInterval;
1127 $interval->startDate = $start;
1128 $interval->endDate = $end;
1129 $interval->initialValues = $interval->getInnerValues();
1130
1131 return $interval;
1132 }
1133
1134 /**
1135 * Invert the interval if it's inverted.
1136 *
1137 * @param bool $absolute do nothing if set to false
1138 *
1139 * @return $this
1140 */
1141 public function abs(bool $absolute = false): static
1142 {
1143 if ($absolute && $this->invert) {
1144 $this->invert();
1145 }
1146
1147 return $this;
1148 }
1149
1150 /**
1151 * @alias abs
1152 *
1153 * Invert the interval if it's inverted.
1154 *
1155 * @param bool $absolute do nothing if set to false
1156 *
1157 * @return $this
1158 */
1159 public function absolute(bool $absolute = true): static
1160 {
1161 return $this->abs($absolute);
1162 }
1163
1164 /**
1165 * Cast the current instance into the given class.
1166 *
1167 * @template T of DateInterval
1168 *
1169 * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object.
1170 *
1171 * @return T
1172 */
1173 public function cast(string $className): mixed
1174 {
1175 return self::castIntervalToClass($this, $className);
1176 }
1177
1178 /**
1179 * Create a CarbonInterval instance from a DateInterval one. Can not instance
1180 * DateInterval objects created from DateTime::diff() as you can't externally
1181 * set the $days field.
1182 *
1183 * @param DateInterval $interval
1184 * @param bool $skipCopy set to true to return the passed object
1185 * (without copying it) if it's already of the
1186 * current class
1187 *
1188 * @return static
1189 */
1190 public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static
1191 {
1192 if ($skipCopy && $interval instanceof static) {
1193 return $interval;
1194 }
1195
1196 return self::castIntervalToClass($interval, static::class, $skip);
1197 }
1198
1199 /**
1200 * Make a CarbonInterval instance from given variable if possible.
1201 *
1202 * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates
1203 * and recurrences). Throw an exception for invalid format, but otherwise return null.
1204 *
1205 * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit
1206 * @param Unit|string|null $unit if specified, $interval must be an integer
1207 * @param bool $skipCopy set to true to return the passed object
1208 * (without copying it) if it's already of the
1209 * current class
1210 *
1211 * @return static|null
1212 */
1213 public static function make($interval, $unit = null, bool $skipCopy = false): ?self
1214 {
1215 if ($interval instanceof Unit) {
1216 $interval = $interval->interval();
1217 }
1218
1219 if ($unit instanceof Unit) {
1220 $unit = $unit->value;
1221 }
1222
1223 if ($unit) {
1224 $interval = "$interval $unit";
1225 }
1226
1227 if ($interval instanceof DateInterval) {
1228 return static::instance($interval, [], $skipCopy);
1229 }
1230
1231 if ($interval instanceof Closure) {
1232 return self::withOriginal(new static($interval), $interval);
1233 }
1234
1235 if (!\is_string($interval)) {
1236 return null;
1237 }
1238
1239 return static::makeFromString($interval);
1240 }
1241
1242 protected static function makeFromString(string $interval): ?self
1243 {
1244 $interval = preg_replace('/\s+/', ' ', trim($interval));
1245
1246 if (preg_match('/^P[T\d]/', $interval)) {
1247 return new static($interval);
1248 }
1249
1250 if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) {
1251 return static::fromString($interval);
1252 }
1253
1254 $intervalInstance = static::createFromDateString($interval);
1255
1256 return $intervalInstance->isEmpty() ? null : $intervalInstance;
1257 }
1258
1259 protected function resolveInterval($interval): ?self
1260 {
1261 if (!($interval instanceof self)) {
1262 return self::make($interval);
1263 }
1264
1265 return $interval;
1266 }
1267
1268 /**
1269 * Sets up a DateInterval from the relative parts of the string.
1270 *
1271 * @param string $datetime
1272 *
1273 * @return static
1274 *
1275 * @link https://php.net/manual/en/dateinterval.createfromdatestring.php
1276 */
1277 public static function createFromDateString(string $datetime): static
1278 {
1279 $string = strtr($datetime, [
1280 ',' => ' ',
1281 ' and ' => ' ',
1282 ]);
1283 $previousException = null;
1284
1285 try {
1286 $interval = parent::createFromDateString($string);
1287 } catch (Throwable $exception) {
1288 $interval = null;
1289 $previousException = $exception;
1290 }
1291
1292 $interval ?: throw new InvalidFormatException(
1293 'Could not create interval from: '.var_export($datetime, true),
1294 previous: $previousException,
1295 );
1296
1297 if (!($interval instanceof static)) {
1298 $interval = static::instance($interval);
1299 }
1300
1301 return self::withOriginal($interval, $datetime);
1302 }
1303
1304 ///////////////////////////////////////////////////////////////////
1305 ///////////////////////// GETTERS AND SETTERS /////////////////////
1306 ///////////////////////////////////////////////////////////////////
1307
1308 /**
1309 * Get a part of the CarbonInterval object.
1310 */
1311 public function get(Unit|string $name): int|float|string|null
1312 {
1313 $name = Unit::toName($name);
1314
1315 if (str_starts_with($name, 'total')) {
1316 return $this->total(substr($name, 5));
1317 }
1318
1319 $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z'));
1320
1321 return match ($resolvedUnit) {
1322 'tzname', 'tz_name' => match (true) {
1323 ($this->timezoneSetting === null) => null,
1324 \is_string($this->timezoneSetting) => $this->timezoneSetting,
1325 ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(),
1326 default => CarbonTimeZone::instance($this->timezoneSetting)->getName(),
1327 },
1328 'year' => $this->y,
1329 'month' => $this->m,
1330 'day' => $this->d,
1331 'hour' => $this->h,
1332 'minute' => $this->i,
1333 'second' => $this->s,
1334 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) /
1335 Carbon::MICROSECONDS_PER_MILLISECOND),
1336 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND),
1337 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) %
1338 Carbon::MICROSECONDS_PER_MILLISECOND,
1339 'week' => (int) ($this->d / (int) static::getDaysPerWeek()),
1340 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(),
1341 'locale' => $this->getTranslatorLocale(),
1342 default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)),
1343 };
1344 }
1345
1346 /**
1347 * Get a part of the CarbonInterval object.
1348 */
1349 public function __get(string $name): int|float|string|null
1350 {
1351 return $this->get($name);
1352 }
1353
1354 /**
1355 * Set a part of the CarbonInterval object.
1356 *
1357 * @param Unit|string|array $name
1358 * @param int $value
1359 *
1360 * @throws UnknownSetterException
1361 *
1362 * @return $this
1363 */
1364 public function set($name, $value = null): static
1365 {
1366 $properties = \is_array($name) ? $name : [$name => $value];
1367
1368 foreach ($properties as $key => $value) {
1369 switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) {
1370 case 'year':
1371 $this->checkIntegerValue($key, $value);
1372 $this->y = $value;
1373 $this->handleDecimalPart('year', $value, $this->y);
1374
1375 break;
1376
1377 case 'month':
1378 $this->checkIntegerValue($key, $value);
1379 $this->m = $value;
1380 $this->handleDecimalPart('month', $value, $this->m);
1381
1382 break;
1383
1384 case 'week':
1385 $this->checkIntegerValue($key, $value);
1386 $days = $value * (int) static::getDaysPerWeek();
1387 $this->assertSafeForInteger('days total (including weeks)', $days);
1388 $this->d = $days;
1389 $this->handleDecimalPart('day', $days, $this->d);
1390
1391 break;
1392
1393 case 'day':
1394 if ($value === false) {
1395 break;
1396 }
1397
1398 $this->checkIntegerValue($key, $value);
1399 $this->d = $value;
1400 $this->handleDecimalPart('day', $value, $this->d);
1401
1402 break;
1403
1404 case 'daysexcludeweek':
1405 case 'dayzexcludeweek':
1406 $this->checkIntegerValue($key, $value);
1407 $days = $this->weeks * (int) static::getDaysPerWeek() + $value;
1408 $this->assertSafeForInteger('days total (including weeks)', $days);
1409 $this->d = $days;
1410 $this->handleDecimalPart('day', $days, $this->d);
1411
1412 break;
1413
1414 case 'hour':
1415 $this->checkIntegerValue($key, $value);
1416 $this->h = $value;
1417 $this->handleDecimalPart('hour', $value, $this->h);
1418
1419 break;
1420
1421 case 'minute':
1422 $this->checkIntegerValue($key, $value);
1423 $this->i = $value;
1424 $this->handleDecimalPart('minute', $value, $this->i);
1425
1426 break;
1427
1428 case 'second':
1429 $this->checkIntegerValue($key, $value);
1430 $this->s = $value;
1431 $this->handleDecimalPart('second', $value, $this->s);
1432
1433 break;
1434
1435 case 'milli':
1436 case 'millisecond':
1437 $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND;
1438
1439 break;
1440
1441 case 'micro':
1442 case 'microsecond':
1443 $this->f = $value / Carbon::MICROSECONDS_PER_SECOND;
1444
1445 break;
1446
1447 default:
1448 if (str_starts_with($key, ' * ')) {
1449 return $this->setSetting(substr($key, 3), $value);
1450 }
1451
1452 if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) {
1453 throw new UnknownSetterException($key);
1454 }
1455
1456 $this->$key = $value;
1457 }
1458 }
1459
1460 return $this;
1461 }
1462
1463 /**
1464 * Set a part of the CarbonInterval object.
1465 *
1466 * @param string $name
1467 * @param int $value
1468 *
1469 * @throws UnknownSetterException
1470 */
1471 public function __set(string $name, $value)
1472 {
1473 $this->set($name, $value);
1474 }
1475
1476 /**
1477 * Allow setting of weeks and days to be cumulative.
1478 *
1479 * @param int $weeks Number of weeks to set
1480 * @param int $days Number of days to set
1481 *
1482 * @return static
1483 */
1484 public function weeksAndDays(int $weeks, int $days): static
1485 {
1486 $this->dayz = ($weeks * static::getDaysPerWeek()) + $days;
1487
1488 return $this;
1489 }
1490
1491 /**
1492 * Returns true if the interval is empty for each unit.
1493 *
1494 * @return bool
1495 */
1496 public function isEmpty(): bool
1497 {
1498 return $this->years === 0 &&
1499 $this->months === 0 &&
1500 $this->dayz === 0 &&
1501 !$this->days &&
1502 $this->hours === 0 &&
1503 $this->minutes === 0 &&
1504 $this->seconds === 0 &&
1505 $this->microseconds === 0;
1506 }
1507
1508 /**
1509 * Register a custom macro.
1510 *
1511 * Pass null macro to remove it.
1512 *
1513 * @example
1514 * ```
1515 * CarbonInterval::macro('twice', function () {
1516 * return $this->times(2);
1517 * });
1518 * echo CarbonInterval::hours(2)->twice();
1519 * ```
1520 *
1521 * @param-closure-this static $macro
1522 */
1523 public static function macro(string $name, ?callable $macro): void
1524 {
1525 static::$macros[$name] = $macro;
1526 }
1527
1528 /**
1529 * Register macros from a mixin object.
1530 *
1531 * @example
1532 * ```
1533 * CarbonInterval::mixin(new class {
1534 * public function daysToHours() {
1535 * return function () {
1536 * $this->hours += $this->days;
1537 * $this->days = 0;
1538 *
1539 * return $this;
1540 * };
1541 * }
1542 * public function hoursToDays() {
1543 * return function () {
1544 * $this->days += $this->hours;
1545 * $this->hours = 0;
1546 *
1547 * return $this;
1548 * };
1549 * }
1550 * });
1551 * echo CarbonInterval::hours(5)->hoursToDays() . "\n";
1552 * echo CarbonInterval::days(5)->daysToHours() . "\n";
1553 * ```
1554 *
1555 * @param object|string $mixin
1556 *
1557 * @throws ReflectionException
1558 *
1559 * @return void
1560 */
1561 public static function mixin($mixin): void
1562 {
1563 static::baseMixin($mixin);
1564 }
1565
1566 /**
1567 * Check if macro is registered.
1568 *
1569 * @param string $name
1570 *
1571 * @return bool
1572 */
1573 public static function hasMacro(string $name): bool
1574 {
1575 return isset(static::$macros[$name]);
1576 }
1577
1578 /**
1579 * Call given macro.
1580 *
1581 * @param string $name
1582 * @param array $parameters
1583 *
1584 * @return mixed
1585 */
1586 protected function callMacro(string $name, array $parameters)
1587 {
1588 $macro = static::$macros[$name];
1589
1590 if ($macro instanceof Closure) {
1591 $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class);
1592
1593 return ($boundMacro ?: $macro)(...$parameters);
1594 }
1595
1596 return $macro(...$parameters);
1597 }
1598
1599 /**
1600 * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day().
1601 *
1602 * Note: This is done using the magic method to allow static and instance methods to
1603 * have the same names.
1604 *
1605 * @param string $method magic method name called
1606 * @param array $parameters parameters list
1607 *
1608 * @throws BadFluentSetterException|Throwable
1609 *
1610 * @return static|int|float|string
1611 */
1612 public function __call(string $method, array $parameters)
1613 {
1614 if (static::hasMacro($method)) {
1615 return static::bindMacroContext($this, function () use (&$method, &$parameters) {
1616 return $this->callMacro($method, $parameters);
1617 });
1618 }
1619
1620 $roundedValue = $this->callRoundMethod($method, $parameters);
1621
1622 if ($roundedValue !== null) {
1623 return $roundedValue;
1624 }
1625
1626 if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) {
1627 $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0);
1628
1629 return $this->{$match['method']}($value, $match['unit']);
1630 }
1631
1632 $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1);
1633
1634 try {
1635 $this->set($method, $value);
1636 } catch (UnknownSetterException $exception) {
1637 if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) {
1638 throw new BadFluentSetterException($method, 0, $exception);
1639 }
1640 }
1641
1642 return $this;
1643 }
1644
1645 protected function getForHumansInitialVariables($syntax, $short): array
1646 {
1647 if (\is_array($syntax)) {
1648 return $syntax;
1649 }
1650
1651 if (\is_int($short)) {
1652 return [
1653 'parts' => $short,
1654 'short' => false,
1655 ];
1656 }
1657
1658 if (\is_bool($syntax)) {
1659 return [
1660 'short' => $syntax,
1661 'syntax' => CarbonInterface::DIFF_ABSOLUTE,
1662 ];
1663 }
1664
1665 return [];
1666 }
1667
1668 /**
1669 * @param mixed $syntax
1670 * @param mixed $short
1671 * @param mixed $parts
1672 * @param mixed $options
1673 *
1674 * @return array
1675 */
1676 protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array
1677 {
1678 $optionalSpace = ' ';
1679 $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' ';
1680 /** @var bool|string $join */
1681 $join = $default === '' ? '' : ' ';
1682 /** @var bool|array|string $altNumbers */
1683 $altNumbers = false;
1684 $aUnit = false;
1685 $minimumUnit = 's';
1686 $skip = [];
1687 extract($this->getForHumansInitialVariables($syntax, $short));
1688 $skip = array_map(
1689 static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit,
1690 (array) $skip,
1691 );
1692 $skip = array_map(
1693 'strtolower',
1694 array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''),
1695 );
1696
1697 $syntax ??= CarbonInterface::DIFF_ABSOLUTE;
1698
1699 if ($parts === self::NO_LIMIT) {
1700 $parts = INF;
1701 }
1702
1703 $options ??= static::getHumanDiffOptions();
1704
1705 if ($join === false) {
1706 $join = ' ';
1707 } elseif ($join === true) {
1708 $join = [
1709 $default,
1710 $this->getTranslationMessage('list.1') ?? $default,
1711 ];
1712 }
1713
1714 if ($altNumbers && $altNumbers !== true) {
1715 $language = new Language($this->locale);
1716 $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true);
1717 }
1718
1719 if (\is_array($join)) {
1720 [$default, $last] = $join;
1721
1722 if ($default !== ' ') {
1723 $optionalSpace = '';
1724 }
1725
1726 $join = function ($list) use ($default, $last) {
1727 if (\count($list) < 2) {
1728 return implode('', $list);
1729 }
1730
1731 $end = array_pop($list);
1732
1733 return implode($default, $list).$last.$end;
1734 };
1735 }
1736
1737 if (\is_string($join)) {
1738 if ($join !== ' ') {
1739 $optionalSpace = '';
1740 }
1741
1742 $glue = $join;
1743 $join = static fn ($list) => implode($glue, $list);
1744 }
1745
1746 $interpolations = [
1747 ':optional-space' => $optionalSpace,
1748 ];
1749
1750 $translator ??= isset($locale) ? Translator::get($locale) : null;
1751
1752 return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator];
1753 }
1754
1755 protected static function getRoundingMethodFromOptions(int $options): ?string
1756 {
1757 if ($options & CarbonInterface::ROUND) {
1758 return 'round';
1759 }
1760
1761 if ($options & CarbonInterface::CEIL) {
1762 return 'ceil';
1763 }
1764
1765 if ($options & CarbonInterface::FLOOR) {
1766 return 'floor';
1767 }
1768
1769 return null;
1770 }
1771
1772 /**
1773 * Returns interval values as an array where key are the unit names and values the counts.
1774 *
1775 * @return int[]
1776 */
1777 public function toArray(): array
1778 {
1779 return [
1780 'years' => $this->years,
1781 'months' => $this->months,
1782 'weeks' => $this->weeks,
1783 'days' => $this->daysExcludeWeeks,
1784 'hours' => $this->hours,
1785 'minutes' => $this->minutes,
1786 'seconds' => $this->seconds,
1787 'microseconds' => $this->microseconds,
1788 ];
1789 }
1790
1791 /**
1792 * Returns interval non-zero values as an array where key are the unit names and values the counts.
1793 *
1794 * @return int[]
1795 */
1796 public function getNonZeroValues(): array
1797 {
1798 return array_filter($this->toArray(), 'intval');
1799 }
1800
1801 /**
1802 * Returns interval values as an array where key are the unit names and values the counts
1803 * from the biggest non-zero one the the smallest non-zero one.
1804 *
1805 * @return int[]
1806 */
1807 public function getValuesSequence(): array
1808 {
1809 $nonZeroValues = $this->getNonZeroValues();
1810
1811 if ($nonZeroValues === []) {
1812 return [];
1813 }
1814
1815 $keys = array_keys($nonZeroValues);
1816 $firstKey = $keys[0];
1817 $lastKey = $keys[\count($keys) - 1];
1818 $values = [];
1819 $record = false;
1820
1821 foreach ($this->toArray() as $unit => $count) {
1822 if ($unit === $firstKey) {
1823 $record = true;
1824 }
1825
1826 if ($record) {
1827 $values[$unit] = $count;
1828 }
1829
1830 if ($unit === $lastKey) {
1831 $record = false;
1832 }
1833 }
1834
1835 return $values;
1836 }
1837
1838 /**
1839 * Get the current interval in a human readable format in the current locale.
1840 *
1841 * @example
1842 * ```
1843 * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n";
1844 * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n";
1845 * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n";
1846 * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n";
1847 * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n";
1848 * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n";
1849 * ```
1850 *
1851 * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain:
1852 * ⦿ 'syntax' entry (see below)
1853 * ⦿ 'short' entry (see below)
1854 * ⦿ 'parts' entry (see below)
1855 * ⦿ 'options' entry (see below)
1856 * ⦿ 'skip' entry, list of units to skip (array of strings or a single string,
1857 * ` it can be the unit name (singular or plural) or its shortcut
1858 * ` (y, m, w, d, h, min, s, ms, µs).
1859 * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true
1860 * ⦿ 'altNumbers' entry, use alternative numbers if available
1861 * ` (from the current language if true is passed, from the given language(s)
1862 * ` if array or string is passed)
1863 * ⦿ 'join' entry determines how to join multiple parts of the string
1864 * ` - if $join is a string, it's used as a joiner glue
1865 * ` - if $join is a callable/closure, it get the list of string and should return a string
1866 * ` - if $join is an array, the first item will be the default glue, and the second item
1867 * ` will be used instead of the glue for the last item
1868 * ` - if $join is true, it will be guessed from the locale ('list' translation file entry)
1869 * ` - if $join is missing, a space will be used as glue
1870 * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or
1871 * ` short form of the units, e.g. 'hour' or 'h' (default value: s)
1872 * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set)
1873 * ⦿ 'translator' a custom translator to use to translator the output.
1874 * if int passed, it adds modifiers:
1875 * Possible values:
1876 * - CarbonInterface::DIFF_ABSOLUTE no modifiers
1877 * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier
1878 * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier
1879 * Default value: CarbonInterface::DIFF_ABSOLUTE
1880 * @param bool $short displays short format of time units
1881 * @param int $parts maximum number of parts to display (default value: -1: no limits)
1882 * @param int $options human diff options
1883 *
1884 * @throws Exception
1885 *
1886 * @return string
1887 */
1888 public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string
1889 {
1890 /* @var TranslatorInterface|null $translator */
1891 [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this
1892 ->getForHumansParameters($syntax, $short, $parts, $options);
1893
1894 $interval = [];
1895
1896 $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE);
1897 $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE;
1898 $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW;
1899 $count = 1;
1900 $unit = $short ? 's' : 'second';
1901 $isFuture = $this->invert === 1;
1902 $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before');
1903 $declensionMode = null;
1904
1905 $translator ??= $this->getLocalTranslator();
1906
1907 $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) {
1908 if (!$absolute) {
1909 $declensionMode = $declensionMode ?? $this->translate($transId.'_mode');
1910
1911 if ($this->needsDeclension($declensionMode, $index, $parts)) {
1912 // Some languages have special pluralization for past and future tense.
1913 $key = $unit.'_'.$transId;
1914 $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers);
1915
1916 if ($result !== $key) {
1917 return $result;
1918 }
1919 }
1920 }
1921
1922 $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers);
1923
1924 if ($result !== $unit) {
1925 return $result;
1926 }
1927
1928 return null;
1929 };
1930
1931 $intervalValues = $this;
1932 $method = static::getRoundingMethodFromOptions($options);
1933
1934 if ($method) {
1935 $previousCount = INF;
1936
1937 while (
1938 \count($intervalValues->getNonZeroValues()) > $parts &&
1939 ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1
1940 ) {
1941 $index = min($count, $previousCount - 1) - 2;
1942
1943 if ($index < 0) {
1944 break;
1945 }
1946
1947 $intervalValues = $this->copy()->roundUnit(
1948 $keys[$index],
1949 1,
1950 $method,
1951 );
1952 $previousCount = $count;
1953 }
1954 }
1955
1956 $diffIntervalArray = [
1957 ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'],
1958 ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'],
1959 ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'],
1960 ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'],
1961 ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'],
1962 ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'],
1963 ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'],
1964 ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'],
1965 ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'],
1966 ];
1967
1968 if (!empty($skip)) {
1969 foreach ($diffIntervalArray as $index => &$unitData) {
1970 $nextIndex = $index + 1;
1971
1972 if ($unitData['value'] &&
1973 isset($diffIntervalArray[$nextIndex]) &&
1974 \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip))
1975 ) {
1976 $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] *
1977 self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']);
1978 $unitData['value'] = 0;
1979 }
1980 }
1981 }
1982
1983 $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) {
1984 $count = $unitData['value'];
1985
1986 if ($short) {
1987 $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts);
1988
1989 if ($result !== null) {
1990 return $result;
1991 }
1992 } elseif ($aUnit) {
1993 $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts);
1994
1995 if ($result !== null) {
1996 return $result;
1997 }
1998 }
1999
2000 if (!$absolute) {
2001 return $handleDeclensions($unitData['unit'], $count, $index, $parts);
2002 }
2003
2004 return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers);
2005 };
2006
2007 $fallbackUnit = ['second', 's'];
2008
2009 foreach ($diffIntervalArray as $diffIntervalData) {
2010 if ($diffIntervalData['value'] > 0) {
2011 $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit'];
2012 $count = $diffIntervalData['value'];
2013 $interval[] = [$short, $diffIntervalData];
2014 } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) {
2015 break;
2016 }
2017
2018 // break the loop after we get the required number of parts in array
2019 if (\count($interval) >= $parts) {
2020 break;
2021 }
2022
2023 // break the loop after we have reached the minimum unit
2024 if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) {
2025 $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']];
2026
2027 break;
2028 }
2029 }
2030
2031 $actualParts = \count($interval);
2032
2033 foreach ($interval as $index => &$item) {
2034 $item = $transChoice($item[0], $item[1], $index, $actualParts);
2035 }
2036
2037 if (\count($interval) === 0) {
2038 if ($relativeToNow && $options & CarbonInterface::JUST_NOW) {
2039 $key = 'diff_now';
2040 $translation = $this->translate($key, $interpolations, null, $translator);
2041
2042 if ($translation !== $key) {
2043 return $translation;
2044 }
2045 }
2046
2047 $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0;
2048 $unit = $fallbackUnit[$short ? 1 : 0];
2049 $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers);
2050 }
2051
2052 // join the interval parts by a space
2053 $time = $join($interval);
2054
2055 unset($diffIntervalArray, $interval);
2056
2057 if ($absolute) {
2058 return $time;
2059 }
2060
2061 $isFuture = $this->invert === 1;
2062
2063 $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before');
2064
2065 if ($parts === 1) {
2066 if ($relativeToNow && $unit === 'day') {
2067 $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null;
2068
2069 if ($specialTranslations && $options & $specialTranslations['option']) {
2070 $key = $specialTranslations[$isFuture ? 'future' : 'past'];
2071 $translation = $this->translate($key, $interpolations, null, $translator);
2072
2073 if ($translation !== $key) {
2074 return $translation;
2075 }
2076 }
2077 }
2078
2079 $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null;
2080
2081 $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time;
2082 }
2083
2084 $time = [':time' => $time];
2085
2086 return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator);
2087 }
2088
2089 public function format(string $format): string
2090 {
2091 $output = parent::format($format);
2092
2093 if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) {
2094 return $output;
2095 }
2096
2097 $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate);
2098
2099 return str_replace('(unknown)', $this->rawInterval->format('%a'), $output);
2100 }
2101
2102 /**
2103 * Format the instance as a string using the forHumans() function.
2104 *
2105 * @throws Exception
2106 *
2107 * @return string
2108 */
2109 public function __toString(): string
2110 {
2111 $format = $this->localToStringFormat
2112 ?? $this->getFactory()->getSettings()['toStringFormat']
2113 ?? null;
2114
2115 if (!$format) {
2116 return $this->forHumans();
2117 }
2118
2119 if ($format instanceof Closure) {
2120 return $format($this);
2121 }
2122
2123 return $this->format($format);
2124 }
2125
2126 /**
2127 * Return native DateInterval PHP object matching the current instance.
2128 *
2129 * @example
2130 * ```
2131 * var_dump(CarbonInterval::hours(2)->toDateInterval());
2132 * ```
2133 *
2134 * @return DateInterval
2135 */
2136 public function toDateInterval(): DateInterval
2137 {
2138 return self::castIntervalToClass($this, DateInterval::class);
2139 }
2140
2141 /**
2142 * Convert the interval to a CarbonPeriod.
2143 *
2144 * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings.
2145 *
2146 * @return CarbonPeriod
2147 */
2148 public function toPeriod(...$params): CarbonPeriod
2149 {
2150 if ($this->timezoneSetting) {
2151 $timeZone = \is_string($this->timezoneSetting)
2152 ? new DateTimeZone($this->timezoneSetting)
2153 : $this->timezoneSetting;
2154
2155 if ($timeZone instanceof DateTimeZone) {
2156 array_unshift($params, $timeZone);
2157 }
2158 }
2159
2160 $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class;
2161
2162 return $class::create($this, ...$params);
2163 }
2164
2165 /**
2166 * Decompose the current interval into
2167 *
2168 * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit
2169 * @param Unit|string|null $unit if specified, $interval must be an integer
2170 *
2171 * @return CarbonPeriod
2172 */
2173 public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod
2174 {
2175 $this->checkStartAndEnd();
2176 $start = $this->startDate ?? CarbonImmutable::make('now');
2177 $end = $this->endDate ?? $start->copy()->add($this);
2178
2179 try {
2180 $step = static::make($interval, $unit);
2181 } catch (InvalidFormatException $exception) {
2182 if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) {
2183 throw $exception;
2184 }
2185
2186 $step = static::make(1, $interval);
2187 }
2188
2189 $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class;
2190
2191 return $class::create($step, $start, $end);
2192 }
2193
2194 /**
2195 * Invert the interval.
2196 *
2197 * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used
2198 * as the new value of the ->invert property.
2199 *
2200 * @return $this
2201 */
2202 public function invert($inverted = null): static
2203 {
2204 $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0;
2205
2206 return $this;
2207 }
2208
2209 protected function solveNegativeInterval(): static
2210 {
2211 if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) {
2212 $this->years *= self::NEGATIVE;
2213 $this->months *= self::NEGATIVE;
2214 $this->dayz *= self::NEGATIVE;
2215 $this->hours *= self::NEGATIVE;
2216 $this->minutes *= self::NEGATIVE;
2217 $this->seconds *= self::NEGATIVE;
2218 $this->microseconds *= self::NEGATIVE;
2219 $this->invert();
2220 }
2221
2222 return $this;
2223 }
2224
2225 /**
2226 * Add the passed interval to the current instance.
2227 *
2228 * @param string|DateInterval $unit
2229 * @param int|float $value
2230 *
2231 * @return $this
2232 */
2233 public function add($unit, $value = 1): static
2234 {
2235 if (is_numeric($unit)) {
2236 [$value, $unit] = [$unit, $value];
2237 }
2238
2239 if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) {
2240 $unit = "$value $unit";
2241 $value = 1;
2242 }
2243
2244 $interval = static::make($unit);
2245
2246 if (!$interval) {
2247 throw new InvalidIntervalException('This type of data cannot be added/subtracted.');
2248 }
2249
2250 if ($value !== 1) {
2251 $interval->times($value);
2252 }
2253
2254 $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE;
2255 $this->years += $interval->y * $sign;
2256 $this->months += $interval->m * $sign;
2257 $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign;
2258 $this->hours += $interval->h * $sign;
2259 $this->minutes += $interval->i * $sign;
2260 $this->seconds += $interval->s * $sign;
2261 $this->microseconds += $interval->microseconds * $sign;
2262
2263 $this->solveNegativeInterval();
2264
2265 return $this;
2266 }
2267
2268 /**
2269 * Subtract the passed interval to the current instance.
2270 *
2271 * @param string|DateInterval $unit
2272 * @param int|float $value
2273 *
2274 * @return $this
2275 */
2276 public function sub($unit, $value = 1): static
2277 {
2278 if (is_numeric($unit)) {
2279 [$value, $unit] = [$unit, $value];
2280 }
2281
2282 return $this->add($unit, -(float) $value);
2283 }
2284
2285 /**
2286 * Subtract the passed interval to the current instance.
2287 *
2288 * @param string|DateInterval $unit
2289 * @param int|float $value
2290 *
2291 * @return $this
2292 */
2293 public function subtract($unit, $value = 1): static
2294 {
2295 return $this->sub($unit, $value);
2296 }
2297
2298 /**
2299 * Add given parameters to the current interval.
2300 *
2301 * @param int $years
2302 * @param int $months
2303 * @param int|float $weeks
2304 * @param int|float $days
2305 * @param int|float $hours
2306 * @param int|float $minutes
2307 * @param int|float $seconds
2308 * @param int|float $microseconds
2309 *
2310 * @return $this
2311 */
2312 public function plus(
2313 $years = 0,
2314 $months = 0,
2315 $weeks = 0,
2316 $days = 0,
2317 $hours = 0,
2318 $minutes = 0,
2319 $seconds = 0,
2320 $microseconds = 0
2321 ): static {
2322 return $this->add("
2323 $years years $months months $weeks weeks $days days
2324 $hours hours $minutes minutes $seconds seconds $microseconds microseconds
2325 ");
2326 }
2327
2328 /**
2329 * Add given parameters to the current interval.
2330 *
2331 * @param int $years
2332 * @param int $months
2333 * @param int|float $weeks
2334 * @param int|float $days
2335 * @param int|float $hours
2336 * @param int|float $minutes
2337 * @param int|float $seconds
2338 * @param int|float $microseconds
2339 *
2340 * @return $this
2341 */
2342 public function minus(
2343 $years = 0,
2344 $months = 0,
2345 $weeks = 0,
2346 $days = 0,
2347 $hours = 0,
2348 $minutes = 0,
2349 $seconds = 0,
2350 $microseconds = 0
2351 ): static {
2352 return $this->sub("
2353 $years years $months months $weeks weeks $days days
2354 $hours hours $minutes minutes $seconds seconds $microseconds microseconds
2355 ");
2356 }
2357
2358 /**
2359 * Multiply current instance given number of times. times() is naive, it multiplies each unit
2360 * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded
2361 * separately for each unit.
2362 *
2363 * Use times() when you want a fast and approximated calculation that does not cascade units.
2364 *
2365 * For a precise and cascaded calculation,
2366 *
2367 * @see multiply()
2368 *
2369 * @param float|int $factor
2370 *
2371 * @return $this
2372 */
2373 public function times($factor): static
2374 {
2375 if ($factor < 0) {
2376 $this->invert = $this->invert ? 0 : 1;
2377 $factor = -$factor;
2378 }
2379
2380 $this->years = (int) round($this->years * $factor);
2381 $this->months = (int) round($this->months * $factor);
2382 $this->dayz = (int) round($this->dayz * $factor);
2383 $this->hours = (int) round($this->hours * $factor);
2384 $this->minutes = (int) round($this->minutes * $factor);
2385 $this->seconds = (int) round($this->seconds * $factor);
2386 $this->microseconds = (int) round($this->microseconds * $factor);
2387
2388 return $this;
2389 }
2390
2391 /**
2392 * Divide current instance by a given divider. shares() is naive, it divides each unit separately
2393 * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours
2394 * and 7 minutes.
2395 *
2396 * Use shares() when you want a fast and approximated calculation that does not cascade units.
2397 *
2398 * For a precise and cascaded calculation,
2399 *
2400 * @see divide()
2401 *
2402 * @param float|int $divider
2403 *
2404 * @return $this
2405 */
2406 public function shares($divider): static
2407 {
2408 return $this->times(1 / $divider);
2409 }
2410
2411 protected function copyProperties(self $interval, $ignoreSign = false): static
2412 {
2413 $this->years = $interval->years;
2414 $this->months = $interval->months;
2415 $this->dayz = $interval->dayz;
2416 $this->hours = $interval->hours;
2417 $this->minutes = $interval->minutes;
2418 $this->seconds = $interval->seconds;
2419 $this->microseconds = $interval->microseconds;
2420
2421 if (!$ignoreSign) {
2422 $this->invert = $interval->invert;
2423 }
2424
2425 return $this;
2426 }
2427
2428 /**
2429 * Multiply and cascade current instance by a given factor.
2430 *
2431 * @param float|int $factor
2432 *
2433 * @return $this
2434 */
2435 public function multiply($factor): static
2436 {
2437 if ($factor < 0) {
2438 $this->invert = $this->invert ? 0 : 1;
2439 $factor = -$factor;
2440 }
2441
2442 $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision
2443
2444 if ($yearPart) {
2445 $this->years -= $yearPart / $factor;
2446 }
2447
2448 return $this->copyProperties(
2449 static::create($yearPart)
2450 ->microseconds(abs($this->totalMicroseconds) * $factor)
2451 ->cascade(),
2452 true,
2453 );
2454 }
2455
2456 /**
2457 * Divide and cascade current instance by a given divider.
2458 *
2459 * @param float|int $divider
2460 *
2461 * @return $this
2462 */
2463 public function divide($divider): static
2464 {
2465 return $this->multiply(1 / $divider);
2466 }
2467
2468 /**
2469 * Get the interval_spec string of a date interval.
2470 *
2471 * @param DateInterval $interval
2472 *
2473 * @return string
2474 */
2475 public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string
2476 {
2477 $date = array_filter([
2478 static::PERIOD_YEARS => abs($interval->y),
2479 static::PERIOD_MONTHS => abs($interval->m),
2480 static::PERIOD_DAYS => abs($interval->d),
2481 ]);
2482
2483 $skip = array_map([Unit::class, 'toNameIfUnit'], $skip);
2484
2485 if (
2486 $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH &&
2487 (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) &&
2488 (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip)))
2489 ) {
2490 $date = [
2491 static::PERIOD_DAYS => abs($interval->days),
2492 ];
2493 }
2494
2495 $seconds = abs($interval->s);
2496 if ($microseconds && $interval->f > 0) {
2497 $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000);
2498 }
2499
2500 $time = array_filter([
2501 static::PERIOD_HOURS => abs($interval->h),
2502 static::PERIOD_MINUTES => abs($interval->i),
2503 static::PERIOD_SECONDS => $seconds,
2504 ]);
2505
2506 $specString = static::PERIOD_PREFIX;
2507
2508 foreach ($date as $key => $value) {
2509 $specString .= $value.$key;
2510 }
2511
2512 if (\count($time) > 0) {
2513 $specString .= static::PERIOD_TIME_PREFIX;
2514 foreach ($time as $key => $value) {
2515 $specString .= $value.$key;
2516 }
2517 }
2518
2519 return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString;
2520 }
2521
2522 /**
2523 * Get the interval_spec string.
2524 *
2525 * @return string
2526 */
2527 public function spec(bool $microseconds = false): string
2528 {
2529 return static::getDateIntervalSpec($this, $microseconds);
2530 }
2531
2532 /**
2533 * Comparing 2 date intervals.
2534 *
2535 * @param DateInterval $first
2536 * @param DateInterval $second
2537 *
2538 * @return int 0, 1 or -1
2539 */
2540 public static function compareDateIntervals(DateInterval $first, DateInterval $second): int
2541 {
2542 $current = Carbon::now();
2543 $passed = $current->avoidMutation()->add($second);
2544 $current->add($first);
2545
2546 return $current <=> $passed;
2547 }
2548
2549 /**
2550 * Comparing with passed interval.
2551 *
2552 * @param DateInterval $interval
2553 *
2554 * @return int 0, 1 or -1
2555 */
2556 public function compare(DateInterval $interval): int
2557 {
2558 return static::compareDateIntervals($this, $interval);
2559 }
2560
2561 /**
2562 * Convert overflowed values into bigger units.
2563 *
2564 * @return $this
2565 */
2566 public function cascade(): static
2567 {
2568 return $this->doCascade(false);
2569 }
2570
2571 public function hasNegativeValues(): bool
2572 {
2573 foreach ($this->toArray() as $value) {
2574 if ($value < 0) {
2575 return true;
2576 }
2577 }
2578
2579 return false;
2580 }
2581
2582 public function hasPositiveValues(): bool
2583 {
2584 foreach ($this->toArray() as $value) {
2585 if ($value > 0) {
2586 return true;
2587 }
2588 }
2589
2590 return false;
2591 }
2592
2593 /**
2594 * Get amount of given unit equivalent to the interval.
2595 *
2596 * @param string $unit
2597 *
2598 * @throws UnknownUnitException|UnitNotConfiguredException
2599 *
2600 * @return float
2601 */
2602 public function total(string $unit): float
2603 {
2604 $realUnit = $unit = strtolower($unit);
2605
2606 if (\in_array($unit, ['days', 'weeks'])) {
2607 $realUnit = 'dayz';
2608 } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) {
2609 throw new UnknownUnitException($unit);
2610 }
2611
2612 $this->checkStartAndEnd();
2613
2614 if ($this->startDate && $this->endDate) {
2615 $diff = $this->startDate->diffInUnit($unit, $this->endDate);
2616
2617 return $this->absolute ? abs($diff) : $diff;
2618 }
2619
2620 $result = 0;
2621 $cumulativeFactor = 0;
2622 $unitFound = false;
2623 $factors = self::getFlipCascadeFactors();
2624 $daysPerWeek = (int) static::getDaysPerWeek();
2625
2626 $values = [
2627 'years' => $this->years,
2628 'months' => $this->months,
2629 'weeks' => (int) ($this->d / $daysPerWeek),
2630 'dayz' => fmod($this->d, $daysPerWeek),
2631 'hours' => $this->hours,
2632 'minutes' => $this->minutes,
2633 'seconds' => $this->seconds,
2634 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND),
2635 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND,
2636 ];
2637
2638 if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') {
2639 $values['dayz'] += $values['weeks'] * $daysPerWeek;
2640 $values['weeks'] = 0;
2641 }
2642
2643 foreach ($factors as $source => [$target, $factor]) {
2644 if ($source === $realUnit) {
2645 $unitFound = true;
2646 $value = $values[$source];
2647 $result += $value;
2648 $cumulativeFactor = 1;
2649 }
2650
2651 if ($factor === false) {
2652 if ($unitFound) {
2653 break;
2654 }
2655
2656 $result = 0;
2657 $cumulativeFactor = 0;
2658
2659 continue;
2660 }
2661
2662 if ($target === $realUnit) {
2663 $unitFound = true;
2664 }
2665
2666 if ($cumulativeFactor) {
2667 $cumulativeFactor *= $factor;
2668 $result += $values[$target] * $cumulativeFactor;
2669
2670 continue;
2671 }
2672
2673 $value = $values[$source];
2674
2675 $result = ($result + $value) / $factor;
2676 }
2677
2678 if (isset($target) && !$cumulativeFactor) {
2679 $result += $values[$target];
2680 }
2681
2682 if (!$unitFound) {
2683 throw new UnitNotConfiguredException($unit);
2684 }
2685
2686 if ($this->invert) {
2687 $result *= self::NEGATIVE;
2688 }
2689
2690 if ($unit === 'weeks') {
2691 $result /= $daysPerWeek;
2692 }
2693
2694 // Cast as int numbers with no decimal part
2695 return fmod($result, 1) === 0.0 ? (int) $result : $result;
2696 }
2697
2698 /**
2699 * Determines if the instance is equal to another
2700 *
2701 * @param CarbonInterval|DateInterval|mixed $interval
2702 *
2703 * @see equalTo()
2704 *
2705 * @return bool
2706 */
2707 public function eq($interval): bool
2708 {
2709 return $this->equalTo($interval);
2710 }
2711
2712 /**
2713 * Determines if the instance is equal to another
2714 *
2715 * @param CarbonInterval|DateInterval|mixed $interval
2716 *
2717 * @return bool
2718 */
2719 public function equalTo($interval): bool
2720 {
2721 $interval = $this->resolveInterval($interval);
2722
2723 if ($interval === null) {
2724 return false;
2725 }
2726
2727 $step = $this->getStep();
2728
2729 if ($step) {
2730 return $step === $interval->getStep();
2731 }
2732
2733 if ($this->isEmpty()) {
2734 return $interval->isEmpty();
2735 }
2736
2737 $cascadedInterval = $this->copy()->cascade();
2738 $comparedInterval = $interval->copy()->cascade();
2739
2740 return $cascadedInterval->invert === $comparedInterval->invert &&
2741 $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues();
2742 }
2743
2744 /**
2745 * Determines if the instance is not equal to another
2746 *
2747 * @param CarbonInterval|DateInterval|mixed $interval
2748 *
2749 * @see notEqualTo()
2750 *
2751 * @return bool
2752 */
2753 public function ne($interval): bool
2754 {
2755 return $this->notEqualTo($interval);
2756 }
2757
2758 /**
2759 * Determines if the instance is not equal to another
2760 *
2761 * @param CarbonInterval|DateInterval|mixed $interval
2762 *
2763 * @return bool
2764 */
2765 public function notEqualTo($interval): bool
2766 {
2767 return !$this->eq($interval);
2768 }
2769
2770 /**
2771 * Determines if the instance is greater (longer) than another
2772 *
2773 * @param CarbonInterval|DateInterval|mixed $interval
2774 *
2775 * @see greaterThan()
2776 *
2777 * @return bool
2778 */
2779 public function gt($interval): bool
2780 {
2781 return $this->greaterThan($interval);
2782 }
2783
2784 /**
2785 * Determines if the instance is greater (longer) than another
2786 *
2787 * @param CarbonInterval|DateInterval|mixed $interval
2788 *
2789 * @return bool
2790 */
2791 public function greaterThan($interval): bool
2792 {
2793 $interval = $this->resolveInterval($interval);
2794
2795 return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds;
2796 }
2797
2798 /**
2799 * Determines if the instance is greater (longer) than or equal to another
2800 *
2801 * @param CarbonInterval|DateInterval|mixed $interval
2802 *
2803 * @see greaterThanOrEqualTo()
2804 *
2805 * @return bool
2806 */
2807 public function gte($interval): bool
2808 {
2809 return $this->greaterThanOrEqualTo($interval);
2810 }
2811
2812 /**
2813 * Determines if the instance is greater (longer) than or equal to another
2814 *
2815 * @param CarbonInterval|DateInterval|mixed $interval
2816 *
2817 * @return bool
2818 */
2819 public function greaterThanOrEqualTo($interval): bool
2820 {
2821 return $this->greaterThan($interval) || $this->equalTo($interval);
2822 }
2823
2824 /**
2825 * Determines if the instance is less (shorter) than another
2826 *
2827 * @param CarbonInterval|DateInterval|mixed $interval
2828 *
2829 * @see lessThan()
2830 *
2831 * @return bool
2832 */
2833 public function lt($interval): bool
2834 {
2835 return $this->lessThan($interval);
2836 }
2837
2838 /**
2839 * Determines if the instance is less (shorter) than another
2840 *
2841 * @param CarbonInterval|DateInterval|mixed $interval
2842 *
2843 * @return bool
2844 */
2845 public function lessThan($interval): bool
2846 {
2847 $interval = $this->resolveInterval($interval);
2848
2849 return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds;
2850 }
2851
2852 /**
2853 * Determines if the instance is less (shorter) than or equal to another
2854 *
2855 * @param CarbonInterval|DateInterval|mixed $interval
2856 *
2857 * @see lessThanOrEqualTo()
2858 *
2859 * @return bool
2860 */
2861 public function lte($interval): bool
2862 {
2863 return $this->lessThanOrEqualTo($interval);
2864 }
2865
2866 /**
2867 * Determines if the instance is less (shorter) than or equal to another
2868 *
2869 * @param CarbonInterval|DateInterval|mixed $interval
2870 *
2871 * @return bool
2872 */
2873 public function lessThanOrEqualTo($interval): bool
2874 {
2875 return $this->lessThan($interval) || $this->equalTo($interval);
2876 }
2877
2878 /**
2879 * Determines if the instance is between two others.
2880 *
2881 * The third argument allow you to specify if bounds are included or not (true by default)
2882 * but for when you including/excluding bounds may produce different results in your application,
2883 * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead.
2884 *
2885 * @example
2886 * ```
2887 * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true
2888 * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false
2889 * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true
2890 * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false
2891 * ```
2892 *
2893 * @param CarbonInterval|DateInterval|mixed $interval1
2894 * @param CarbonInterval|DateInterval|mixed $interval2
2895 * @param bool $equal Indicates if an equal to comparison should be done
2896 *
2897 * @return bool
2898 */
2899 public function between($interval1, $interval2, bool $equal = true): bool
2900 {
2901 return $equal
2902 ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2)
2903 : $this->greaterThan($interval1) && $this->lessThan($interval2);
2904 }
2905
2906 /**
2907 * Determines if the instance is between two others, bounds excluded.
2908 *
2909 * @example
2910 * ```
2911 * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true
2912 * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false
2913 * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true
2914 * ```
2915 *
2916 * @param CarbonInterval|DateInterval|mixed $interval1
2917 * @param CarbonInterval|DateInterval|mixed $interval2
2918 *
2919 * @return bool
2920 */
2921 public function betweenIncluded($interval1, $interval2): bool
2922 {
2923 return $this->between($interval1, $interval2, true);
2924 }
2925
2926 /**
2927 * Determines if the instance is between two others, bounds excluded.
2928 *
2929 * @example
2930 * ```
2931 * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true
2932 * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false
2933 * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false
2934 * ```
2935 *
2936 * @param CarbonInterval|DateInterval|mixed $interval1
2937 * @param CarbonInterval|DateInterval|mixed $interval2
2938 *
2939 * @return bool
2940 */
2941 public function betweenExcluded($interval1, $interval2): bool
2942 {
2943 return $this->between($interval1, $interval2, false);
2944 }
2945
2946 /**
2947 * Determines if the instance is between two others
2948 *
2949 * @example
2950 * ```
2951 * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true
2952 * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false
2953 * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true
2954 * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false
2955 * ```
2956 *
2957 * @param CarbonInterval|DateInterval|mixed $interval1
2958 * @param CarbonInterval|DateInterval|mixed $interval2
2959 * @param bool $equal Indicates if an equal to comparison should be done
2960 *
2961 * @return bool
2962 */
2963 public function isBetween($interval1, $interval2, bool $equal = true): bool
2964 {
2965 return $this->between($interval1, $interval2, $equal);
2966 }
2967
2968 /**
2969 * Round the current instance at the given unit with given precision if specified and the given function.
2970 *
2971 * @throws Exception
2972 */
2973 public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static
2974 {
2975 if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) {
2976 $value = $function($this->total($unit) / $precision) * $precision;
2977 $inverted = $value < 0;
2978
2979 return $this->copyProperties(self::fromString(
2980 number_format(abs($value), 12, '.', '').' '.$unit
2981 )->invert($inverted)->cascade());
2982 }
2983
2984 $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC')
2985 ->roundUnit($unit, $precision, $function);
2986 $next = $base->add($this);
2987 $inverted = $next < $base;
2988
2989 if ($inverted) {
2990 $next = $base->sub($this);
2991 }
2992
2993 $this->copyProperties(
2994 $next
2995 ->roundUnit($unit, $precision, $function)
2996 ->diff($base),
2997 );
2998
2999 return $this->invert($inverted);
3000 }
3001
3002 /**
3003 * Truncate the current instance at the given unit with given precision if specified.
3004 *
3005 * @param string $unit
3006 * @param float|int|string|DateInterval|null $precision
3007 *
3008 * @throws Exception
3009 *
3010 * @return $this
3011 */
3012 public function floorUnit(string $unit, $precision = 1): static
3013 {
3014 return $this->roundUnit($unit, $precision, 'floor');
3015 }
3016
3017 /**
3018 * Ceil the current instance at the given unit with given precision if specified.
3019 *
3020 * @param string $unit
3021 * @param float|int|string|DateInterval|null $precision
3022 *
3023 * @throws Exception
3024 *
3025 * @return $this
3026 */
3027 public function ceilUnit(string $unit, $precision = 1): static
3028 {
3029 return $this->roundUnit($unit, $precision, 'ceil');
3030 }
3031
3032 /**
3033 * Round the current instance second with given precision if specified.
3034 *
3035 * @param float|int|string|DateInterval|null $precision
3036 * @param string $function
3037 *
3038 * @throws Exception
3039 *
3040 * @return $this
3041 */
3042 public function round($precision = 1, string $function = 'round'): static
3043 {
3044 return $this->roundWith($precision, $function);
3045 }
3046
3047 /**
3048 * Round the current instance second with given precision if specified.
3049 *
3050 * @throws Exception
3051 *
3052 * @return $this
3053 */
3054 public function floor(DateInterval|string|float|int $precision = 1): static
3055 {
3056 return $this->round($precision, 'floor');
3057 }
3058
3059 /**
3060 * Ceil the current instance second with given precision if specified.
3061 *
3062 * @throws Exception
3063 *
3064 * @return $this
3065 */
3066 public function ceil(DateInterval|string|float|int $precision = 1): static
3067 {
3068 return $this->round($precision, 'ceil');
3069 }
3070
3071 public function __unserialize(array $data): void
3072 {
3073 $properties = array_combine(
3074 array_map(
3075 static fn (mixed $key) => \is_string($key)
3076 ? str_replace('tzName', 'timezoneSetting', $key)
3077 : $key,
3078 array_keys($data),
3079 ),
3080 $data,
3081 );
3082
3083 if (method_exists(parent::class, '__unserialize')) {
3084 // PHP >= 8.2
3085 parent::__unserialize($properties);
3086
3087 return;
3088 }
3089
3090 // PHP <= 8.1
3091 // @codeCoverageIgnoreStart
3092 $properties = array_combine(
3093 array_map(
3094 static fn (string $property) => preg_replace('/^\0.+\0/', '', $property),
3095 array_keys($data),
3096 ),
3097 $data,
3098 );
3099 $localStrictMode = $this->localStrictModeEnabled;
3100 $this->localStrictModeEnabled = false;
3101 $days = $properties['days'] ?? false;
3102 $this->days = $days === false ? false : (int) $days;
3103 $this->y = (int) ($properties['y'] ?? 0);
3104 $this->m = (int) ($properties['m'] ?? 0);
3105 $this->d = (int) ($properties['d'] ?? 0);
3106 $this->h = (int) ($properties['h'] ?? 0);
3107 $this->i = (int) ($properties['i'] ?? 0);
3108 $this->s = (int) ($properties['s'] ?? 0);
3109 $this->f = (float) ($properties['f'] ?? 0.0);
3110 // @phpstan-ignore-next-line
3111 $this->weekday = (int) ($properties['weekday'] ?? 0);
3112 // @phpstan-ignore-next-line
3113 $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0);
3114 // @phpstan-ignore-next-line
3115 $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0);
3116 $this->invert = (int) ($properties['invert'] ?? 0);
3117 // @phpstan-ignore-next-line
3118 $this->special_type = (int) ($properties['special_type'] ?? 0);
3119 // @phpstan-ignore-next-line
3120 $this->special_amount = (int) ($properties['special_amount'] ?? 0);
3121 // @phpstan-ignore-next-line
3122 $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0);
3123 // @phpstan-ignore-next-line
3124 $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0);
3125 parent::__construct(self::getDateIntervalSpec($this));
3126
3127 foreach ($properties as $property => $value) {
3128 if ($property === 'localStrictModeEnabled') {
3129 continue;
3130 }
3131
3132 $this->$property = $value;
3133 }
3134
3135 $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode;
3136 // @codeCoverageIgnoreEnd
3137 }
3138
3139 /**
3140 * @template T
3141 *
3142 * @param T $interval
3143 * @param mixed $original
3144 *
3145 * @return T
3146 */
3147 private static function withOriginal(mixed $interval, mixed $original): mixed
3148 {
3149 if ($interval instanceof self) {
3150 $interval->originalInput = $original;
3151 }
3152
3153 return $interval;
3154 }
3155
3156 private static function standardizeUnit(string $unit): string
3157 {
3158 $unit = rtrim($unit, 'sz').'s';
3159
3160 return $unit === 'days' ? 'dayz' : $unit;
3161 }
3162
3163 private static function getFlipCascadeFactors(): array
3164 {
3165 if (!self::$flipCascadeFactors) {
3166 self::$flipCascadeFactors = [];
3167
3168 foreach (self::getCascadeFactors() as $to => [$factor, $from]) {
3169 self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor];
3170 }
3171 }
3172
3173 return self::$flipCascadeFactors;
3174 }
3175
3176 /**
3177 * @template T of DateInterval
3178 *
3179 * @param DateInterval $interval
3180 *
3181 * @psalm-param class-string<T> $className
3182 *
3183 * @return T
3184 */
3185 private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object
3186 {
3187 $mainClass = DateInterval::class;
3188
3189 if (!is_a($className, $mainClass, true)) {
3190 throw new InvalidCastException("$className is not a sub-class of $mainClass.");
3191 }
3192
3193 $microseconds = $interval->f;
3194 $instance = self::buildInstance($interval, $className, $skip);
3195
3196 if ($instance instanceof self) {
3197 $instance->originalInput = $interval;
3198 }
3199
3200 if ($microseconds) {
3201 $instance->f = $microseconds;
3202 }
3203
3204 if ($interval instanceof self && is_a($className, self::class, true)) {
3205 self::copyStep($interval, $instance);
3206 }
3207
3208 self::copyNegativeUnits($interval, $instance);
3209
3210 return self::withOriginal($instance, $interval);
3211 }
3212
3213 /**
3214 * @template T of DateInterval
3215 *
3216 * @param DateInterval $interval
3217 *
3218 * @psalm-param class-string<T> $className
3219 *
3220 * @return T
3221 */
3222 private static function buildInstance(
3223 DateInterval $interval,
3224 string $className,
3225 array $skip = [],
3226 ): object {
3227 $serialization = self::buildSerializationString($interval, $className, $skip);
3228
3229 return match ($serialization) {
3230 null => new $className(static::getDateIntervalSpec($interval, false, $skip)),
3231 default => unserialize($serialization),
3232 };
3233 }
3234
3235 /**
3236 * As demonstrated by rlanvin (https://github.com/rlanvin) in
3237 * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438
3238 *
3239 * Modifying the output of serialize() to change the class name and unserializing
3240 * the tweaked string allows creating new interval instances where the ->days
3241 * property can be set. It's not possible neither with `new` nto with `__set_state`.
3242 *
3243 * It has a non-negligible performance cost, so we'll use this method only if
3244 * $interval->days !== false.
3245 */
3246 private static function buildSerializationString(
3247 DateInterval $interval,
3248 string $className,
3249 array $skip = [],
3250 ): ?string {
3251 if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) {
3252 return null;
3253 }
3254
3255 // De-enhance CarbonInterval objects to be serializable back to DateInterval
3256 if ($interval instanceof self && !is_a($className, self::class, true)) {
3257 $interval = clone $interval;
3258 unset($interval->timezoneSetting);
3259 unset($interval->originalInput);
3260 unset($interval->startDate);
3261 unset($interval->endDate);
3262 unset($interval->rawInterval);
3263 unset($interval->absolute);
3264 unset($interval->initialValues);
3265 unset($interval->clock);
3266 unset($interval->step);
3267 unset($interval->localMonthsOverflow);
3268 unset($interval->localYearsOverflow);
3269 unset($interval->localStrictModeEnabled);
3270 unset($interval->localHumanDiffOptions);
3271 unset($interval->localToStringFormat);
3272 unset($interval->localSerializer);
3273 unset($interval->localMacros);
3274 unset($interval->localGenericMacros);
3275 unset($interval->localFormatFunction);
3276 unset($interval->localTranslator);
3277 }
3278
3279 $serialization = serialize($interval);
3280 $inputClass = $interval::class;
3281 $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":';
3282
3283 if (!str_starts_with($serialization, $expectedStart)) {
3284 return null; // @codeCoverageIgnore
3285 }
3286
3287 return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart));
3288 }
3289
3290 private static function copyStep(self $from, self $to): void
3291 {
3292 $to->setStep($from->getStep());
3293 }
3294
3295 private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void
3296 {
3297 $to->invert = $from->invert;
3298
3299 foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) {
3300 if ($from->$unit < 0) {
3301 self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE);
3302 }
3303 }
3304 }
3305
3306 private function invertCascade(array $values): static
3307 {
3308 return $this->set(array_map(function ($value) {
3309 return -$value;
3310 }, $values))->doCascade(true)->invert();
3311 }
3312
3313 private function doCascade(bool $deep): static
3314 {
3315 $originalData = $this->toArray();
3316 $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond());
3317 $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond();
3318 $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek());
3319 $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek());
3320 unset($originalData['days']);
3321 $newData = $originalData;
3322 $previous = [];
3323
3324 foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) {
3325 foreach (['source', 'target'] as $key) {
3326 if ($$key === 'dayz') {
3327 $$key = 'daysExcludeWeeks';
3328 }
3329 }
3330
3331 $value = $newData[$source];
3332 $modulo = fmod($factor + fmod($value, $factor), $factor);
3333 $newData[$source] = $modulo;
3334 $newData[$target] += ($value - $modulo) / $factor;
3335
3336 $decimalPart = fmod($newData[$source], 1);
3337
3338 if ($decimalPart !== 0.0) {
3339 $unit = $source;
3340
3341 foreach ($previous as [$subUnit, $subFactor]) {
3342 $newData[$unit] -= $decimalPart;
3343 $newData[$subUnit] += $decimalPart * $subFactor;
3344 $decimalPart = fmod($newData[$subUnit], 1);
3345
3346 if ($decimalPart === 0.0) {
3347 break;
3348 }
3349
3350 $unit = $subUnit;
3351 }
3352 }
3353
3354 array_unshift($previous, [$source, $factor]);
3355 }
3356
3357 $positive = null;
3358
3359 if (!$deep) {
3360 foreach ($newData as $value) {
3361 if ($value) {
3362 if ($positive === null) {
3363 $positive = ($value > 0);
3364
3365 continue;
3366 }
3367
3368 if (($value > 0) !== $positive) {
3369 return $this->invertCascade($originalData)
3370 ->solveNegativeInterval();
3371 }
3372 }
3373 }
3374 }
3375
3376 return $this->set($newData)
3377 ->solveNegativeInterval();
3378 }
3379
3380 private function needsDeclension(string $mode, int $index, int $parts): bool
3381 {
3382 return match ($mode) {
3383 'last' => $index === $parts - 1,
3384 default => true,
3385 };
3386 }
3387
3388 private function checkIntegerValue(string $name, mixed $value): void
3389 {
3390 if (\is_int($value)) {
3391 return;
3392 }
3393
3394 $this->assertSafeForInteger($name, $value);
3395
3396 if (\is_float($value) && (((float) (int) $value) === $value)) {
3397 return;
3398 }
3399
3400 if (!self::$floatSettersEnabled) {
3401 $type = \gettype($value);
3402 @trigger_error(
3403 "Since 2.70.0, it's deprecated to pass $type value for $name.\n".
3404 "It's truncated when stored as an integer interval unit.\n".
3405 "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n".
3406 "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n".
3407 "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n",
3408 \E_USER_DEPRECATED,
3409 );
3410 }
3411 }
3412
3413 /**
3414 * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0.
3415 */
3416 private function assertSafeForInteger(string $name, mixed $value): void
3417 {
3418 if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) {
3419 throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value);
3420 }
3421 }
3422
3423 private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void
3424 {
3425 if (self::$floatSettersEnabled) {
3426 $floatValue = (float) $value;
3427 $base = (float) $integerValue;
3428
3429 if ($floatValue === $base) {
3430 return;
3431 }
3432
3433 $units = [
3434 'y' => 'year',
3435 'm' => 'month',
3436 'd' => 'day',
3437 'h' => 'hour',
3438 'i' => 'minute',
3439 's' => 'second',
3440 ];
3441 $upper = true;
3442
3443 foreach ($units as $property => $name) {
3444 if ($name === $unit) {
3445 $upper = false;
3446
3447 continue;
3448 }
3449
3450 if (!$upper && $this->$property !== 0) {
3451 throw new RuntimeException(
3452 "You cannot set $unit to a float value as $name would be overridden, ".
3453 'set it first to 0 explicitly if you really want to erase its value'
3454 );
3455 }
3456 }
3457
3458 $this->add($unit, $floatValue - $base);
3459 }
3460 }
3461
3462 private function getInnerValues(): array
3463 {
3464 return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days];
3465 }
3466
3467 private function checkStartAndEnd(): void
3468 {
3469 if (
3470 $this->initialValues !== null
3471 && ($this->startDate !== null || $this->endDate !== null)
3472 && $this->initialValues !== $this->getInnerValues()
3473 ) {
3474 $this->absolute = false;
3475 $this->startDate = null;
3476 $this->endDate = null;
3477 $this->rawInterval = null;
3478 }
3479 }
3480
3481 /** @return $this */
3482 private function setSetting(string $setting, mixed $value): self
3483 {
3484 switch ($setting) {
3485 case 'timezoneSetting':
3486 return $value === null ? $this : $this->setTimezone($value);
3487
3488 case 'step':
3489 $this->setStep($value);
3490
3491 return $this;
3492
3493 case 'localMonthsOverflow':
3494 return $value === null ? $this : $this->settings(['monthOverflow' => $value]);
3495
3496 case 'localYearsOverflow':
3497 return $value === null ? $this : $this->settings(['yearOverflow' => $value]);
3498
3499 case 'localStrictModeEnabled':
3500 case 'localHumanDiffOptions':
3501 case 'localToStringFormat':
3502 case 'localSerializer':
3503 case 'localMacros':
3504 case 'localGenericMacros':
3505 case 'localFormatFunction':
3506 case 'localTranslator':
3507 $this->$setting = $value;
3508
3509 return $this;
3510
3511 default:
3512 // Drop unknown settings
3513 return $this;
3514 }
3515 }
3516
3517 private static function incrementUnit(DateInterval $instance, string $unit, int $value): void
3518 {
3519 if ($value === 0) {
3520 return;
3521 }
3522
3523 // @codeCoverageIgnoreStart
3524 if (PHP_VERSION_ID !== 8_03_20) {
3525 $instance->$unit += $value;
3526
3527 return;
3528 }
3529
3530 // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20
3531 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value);
3532 // @codeCoverageIgnoreEnd
3533 }
3534
3535 /** @codeCoverageIgnore */
3536 private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void
3537 {
3538 switch ($unit) {
3539 case 'y':
3540 $instance->y = $value;
3541
3542 break;
3543
3544 case 'm':
3545 $instance->m = $value;
3546
3547 break;
3548
3549 case 'd':
3550 $instance->d = $value;
3551
3552 break;
3553
3554 case 'h':
3555 $instance->h = $value;
3556
3557 break;
3558
3559 case 'i':
3560 $instance->i = $value;
3561
3562 break;
3563
3564 case 's':
3565 $instance->s = $value;
3566
3567 break;
3568
3569 default:
3570 $instance->$unit = $value;
3571 }
3572 }
3573 }