Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Traits/Units.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\Traits;
15
16 use Carbon\CarbonConverterInterface;
17 use Carbon\CarbonInterface;
18 use Carbon\CarbonInterval;
19 use Carbon\Exceptions\InvalidFormatException;
20 use Carbon\Exceptions\InvalidIntervalException;
21 use Carbon\Exceptions\UnitException;
22 use Carbon\Exceptions\UnsupportedUnitException;
23 use Carbon\Unit;
24 use Closure;
25 use DateInterval;
26 use DateMalformedStringException;
27 use ReturnTypeWillChange;
28
29 /**
30 * Trait Units.
31 *
32 * Add, subtract and set units.
33 */
34 trait Units
35 {
36 /**
37 * @deprecated Prefer to use add addUTCUnit() which more accurately defines what it's doing.
38 *
39 * Add seconds to the instance using timestamp. Positive $value travels
40 * forward while negative $value travels into the past.
41 *
42 * @param string $unit
43 * @param int|float|null $value
44 *
45 * @return static
46 */
47 public function addRealUnit(string $unit, $value = 1): static
48 {
49 return $this->addUTCUnit($unit, $value);
50 }
51
52 /**
53 * Add seconds to the instance using timestamp. Positive $value travels
54 * forward while negative $value travels into the past.
55 *
56 * @param string $unit
57 * @param int|float|null $value
58 *
59 * @return static
60 */
61 public function addUTCUnit(string $unit, $value = 1): static
62 {
63 $value ??= 0;
64
65 switch ($unit) {
66 // @call addUTCUnit
67 case 'micro':
68
69 // @call addUTCUnit
70 case 'microsecond':
71 /* @var CarbonInterface $this */
72 $diff = $this->microsecond + $value;
73 $time = $this->getTimestamp();
74 $seconds = (int) floor($diff / static::MICROSECONDS_PER_SECOND);
75 $time += $seconds;
76 $diff -= $seconds * static::MICROSECONDS_PER_SECOND;
77 $microtime = str_pad((string) $diff, 6, '0', STR_PAD_LEFT);
78 $timezone = $this->tz;
79
80 return $this->tz('UTC')->modify("@$time.$microtime")->setTimezone($timezone);
81
82 // @call addUTCUnit
83 case 'milli':
84 // @call addUTCUnit
85 case 'millisecond':
86 return $this->addUTCUnit('microsecond', $value * static::MICROSECONDS_PER_MILLISECOND);
87
88 // @call addUTCUnit
89 case 'second':
90 break;
91
92 // @call addUTCUnit
93 case 'minute':
94 $value *= static::SECONDS_PER_MINUTE;
95
96 break;
97
98 // @call addUTCUnit
99 case 'hour':
100 $value *= static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
101
102 break;
103
104 // @call addUTCUnit
105 case 'day':
106 $value *= static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
107
108 break;
109
110 // @call addUTCUnit
111 case 'week':
112 $value *= static::DAYS_PER_WEEK * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
113
114 break;
115
116 // @call addUTCUnit
117 case 'month':
118 $value *= 30 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
119
120 break;
121
122 // @call addUTCUnit
123 case 'quarter':
124 $value *= static::MONTHS_PER_QUARTER * 30 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
125
126 break;
127
128 // @call addUTCUnit
129 case 'year':
130 $value *= 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
131
132 break;
133
134 // @call addUTCUnit
135 case 'decade':
136 $value *= static::YEARS_PER_DECADE * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
137
138 break;
139
140 // @call addUTCUnit
141 case 'century':
142 $value *= static::YEARS_PER_CENTURY * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
143
144 break;
145
146 // @call addUTCUnit
147 case 'millennium':
148 $value *= static::YEARS_PER_MILLENNIUM * 365 * static::HOURS_PER_DAY * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE;
149
150 break;
151
152 default:
153 if ($this->isLocalStrictModeEnabled()) {
154 throw new UnitException("Invalid unit for real timestamp add/sub: '$unit'");
155 }
156
157 return $this;
158 }
159
160 $seconds = (int) $value;
161 $microseconds = (int) round(
162 (abs($value) - abs($seconds)) * ($value < 0 ? -1 : 1) * static::MICROSECONDS_PER_SECOND,
163 );
164 $date = $this->setTimestamp($this->getTimestamp() + $seconds);
165
166 return $microseconds ? $date->addUTCUnit('microsecond', $microseconds) : $date;
167 }
168
169 /**
170 * @deprecated Prefer to use add subUTCUnit() which more accurately defines what it's doing.
171 *
172 * Subtract seconds to the instance using timestamp. Positive $value travels
173 * into the past while negative $value travels forward.
174 *
175 * @param string $unit
176 * @param int $value
177 *
178 * @return static
179 */
180 public function subRealUnit($unit, $value = 1): static
181 {
182 return $this->addUTCUnit($unit, -$value);
183 }
184
185 /**
186 * Subtract seconds to the instance using timestamp. Positive $value travels
187 * into the past while negative $value travels forward.
188 *
189 * @param string $unit
190 * @param int $value
191 *
192 * @return static
193 */
194 public function subUTCUnit($unit, $value = 1): static
195 {
196 return $this->addUTCUnit($unit, -$value);
197 }
198
199 /**
200 * Returns true if a property can be changed via setter.
201 *
202 * @param string $unit
203 *
204 * @return bool
205 */
206 public static function isModifiableUnit($unit): bool
207 {
208 static $modifiableUnits = [
209 // @call addUnit
210 'millennium',
211 // @call addUnit
212 'century',
213 // @call addUnit
214 'decade',
215 // @call addUnit
216 'quarter',
217 // @call addUnit
218 'week',
219 // @call addUnit
220 'weekday',
221 ];
222
223 return \in_array($unit, $modifiableUnits, true) || \in_array($unit, static::$units, true);
224 }
225
226 /**
227 * Call native PHP DateTime/DateTimeImmutable add() method.
228 *
229 * @param DateInterval $interval
230 *
231 * @return static
232 */
233 public function rawAdd(DateInterval $interval): static
234 {
235 return parent::add($interval);
236 }
237
238 /**
239 * Add given units or interval to the current instance.
240 *
241 * @example $date->add('hour', 3)
242 * @example $date->add(15, 'days')
243 * @example $date->add(CarbonInterval::days(4))
244 *
245 * @param Unit|int|string|DateInterval|Closure|CarbonConverterInterface $unit
246 * @param Unit|int|float|string $value
247 * @param bool|null $overflow
248 *
249 * @return static
250 */
251 #[ReturnTypeWillChange]
252 public function add($unit, $value = 1, ?bool $overflow = null): static
253 {
254 $unit = Unit::toNameIfUnit($unit);
255 $value = Unit::toNameIfUnit($value);
256
257 if (\is_string($unit) && \func_num_args() === 1) {
258 $unit = CarbonInterval::make($unit, [], true);
259 }
260
261 if ($unit instanceof CarbonConverterInterface) {
262 $unit = Closure::fromCallable([$unit, 'convertDate']);
263 }
264
265 if ($unit instanceof Closure) {
266 $result = $this->resolveCarbon($unit($this, false));
267
268 if ($this !== $result && $this->isMutable()) {
269 return $this->modify($result->rawFormat('Y-m-d H:i:s.u e O'));
270 }
271
272 return $result;
273 }
274
275 if ($unit instanceof DateInterval) {
276 return parent::add($unit);
277 }
278
279 if (is_numeric($unit)) {
280 [$value, $unit] = [$unit, $value];
281 }
282
283 return $this->addUnit((string) $unit, $value, $overflow);
284 }
285
286 /**
287 * Add given units to the current instance.
288 */
289 public function addUnit(Unit|string $unit, $value = 1, ?bool $overflow = null): static
290 {
291 $unit = Unit::toName($unit);
292
293 $originalArgs = \func_get_args();
294
295 $date = $this;
296
297 if (!is_numeric($value) || !(float) $value) {
298 return $date->isMutable() ? $date : $date->copy();
299 }
300
301 $unit = self::singularUnit($unit);
302 $metaUnits = [
303 'millennium' => [static::YEARS_PER_MILLENNIUM, 'year'],
304 'century' => [static::YEARS_PER_CENTURY, 'year'],
305 'decade' => [static::YEARS_PER_DECADE, 'year'],
306 'quarter' => [static::MONTHS_PER_QUARTER, 'month'],
307 ];
308
309 if (isset($metaUnits[$unit])) {
310 [$factor, $unit] = $metaUnits[$unit];
311 $value *= $factor;
312 }
313
314 if ($unit === 'weekday') {
315 $weekendDays = $this->transmitFactory(static fn () => static::getWeekendDays());
316
317 if ($weekendDays !== [static::SATURDAY, static::SUNDAY]) {
318 $absoluteValue = abs($value);
319 $sign = $value / max(1, $absoluteValue);
320 $weekDaysCount = static::DAYS_PER_WEEK - min(static::DAYS_PER_WEEK - 1, \count(array_unique($weekendDays)));
321 $weeks = floor($absoluteValue / $weekDaysCount);
322
323 for ($diff = $absoluteValue % $weekDaysCount; $diff; $diff--) {
324 /** @var static $date */
325 $date = $date->addDays($sign);
326
327 while (\in_array($date->dayOfWeek, $weekendDays, true)) {
328 $date = $date->addDays($sign);
329 }
330 }
331
332 $value = $weeks * $sign;
333 $unit = 'week';
334 }
335
336 $timeString = $date->toTimeString();
337 } elseif ($canOverflow = (\in_array($unit, [
338 'month',
339 'year',
340 ]) && ($overflow === false || (
341 $overflow === null &&
342 ($ucUnit = ucfirst($unit).'s') &&
343 !($this->{'local'.$ucUnit.'Overflow'} ?? static::{'shouldOverflow'.$ucUnit}())
344 )))) {
345 $day = $date->day;
346 }
347
348 if ($unit === 'milli' || $unit === 'millisecond') {
349 $unit = 'microsecond';
350 $value *= static::MICROSECONDS_PER_MILLISECOND;
351 }
352
353 $previousException = null;
354
355 try {
356 $date = self::rawAddUnit($date, $unit, $value);
357
358 if (isset($timeString)) {
359 $date = $date?->setTimeFromTimeString($timeString);
360 } elseif (isset($canOverflow, $day) && $canOverflow && $day !== $date?->day) {
361 $date = $date?->modify('last day of previous month');
362 }
363 } catch (DateMalformedStringException|InvalidFormatException|UnsupportedUnitException $exception) {
364 $date = null;
365 $previousException = $exception;
366 }
367
368 return $date ?? throw new UnitException(
369 'Unable to add unit '.var_export($originalArgs, true),
370 previous: $previousException,
371 );
372 }
373
374 /**
375 * Subtract given units to the current instance.
376 */
377 public function subUnit(Unit|string $unit, $value = 1, ?bool $overflow = null): static
378 {
379 return $this->addUnit($unit, -$value, $overflow);
380 }
381
382 /**
383 * Call native PHP DateTime/DateTimeImmutable sub() method.
384 */
385 public function rawSub(DateInterval $interval): static
386 {
387 return parent::sub($interval);
388 }
389
390 /**
391 * Subtract given units or interval to the current instance.
392 *
393 * @example $date->sub('hour', 3)
394 * @example $date->sub(15, 'days')
395 * @example $date->sub(CarbonInterval::days(4))
396 *
397 * @param Unit|int|string|DateInterval|Closure|CarbonConverterInterface $unit
398 * @param Unit|int|float|string $value
399 * @param bool|null $overflow
400 *
401 * @return static
402 */
403 #[ReturnTypeWillChange]
404 public function sub($unit, $value = 1, ?bool $overflow = null): static
405 {
406 $unit = Unit::toNameIfUnit($unit);
407 $value = Unit::toNameIfUnit($value);
408
409 if (\is_string($unit) && \func_num_args() === 1) {
410 $unit = CarbonInterval::make($unit, [], true);
411 }
412
413 if ($unit instanceof CarbonConverterInterface) {
414 $unit = Closure::fromCallable([$unit, 'convertDate']);
415 }
416
417 if ($unit instanceof Closure) {
418 $result = $this->resolveCarbon($unit($this, true));
419
420 if ($this !== $result && $this->isMutable()) {
421 return $this->modify($result->rawFormat('Y-m-d H:i:s.u e O'));
422 }
423
424 return $result;
425 }
426
427 if ($unit instanceof DateInterval) {
428 return parent::sub($unit);
429 }
430
431 if (is_numeric($unit)) {
432 [$value, $unit] = [$unit, $value];
433 }
434
435 return $this->addUnit((string) $unit, -(float) $value, $overflow);
436 }
437
438 /**
439 * Subtract given units or interval to the current instance.
440 *
441 * @see sub()
442 *
443 * @param Unit|int|string|DateInterval $unit
444 * @param Unit|int|float|string $value
445 * @param bool|null $overflow
446 *
447 * @return static
448 */
449 public function subtract($unit, $value = 1, ?bool $overflow = null): static
450 {
451 if (\is_string($unit) && \func_num_args() === 1) {
452 $unit = CarbonInterval::make($unit, [], true);
453 }
454
455 return $this->sub($unit, $value, $overflow);
456 }
457
458 private static function rawAddUnit(self $date, string $unit, int|float $value): ?static
459 {
460 try {
461 return $date->rawAdd(
462 CarbonInterval::fromString(abs($value)." $unit")->invert($value < 0),
463 );
464 } catch (InvalidIntervalException $exception) {
465 try {
466 return $date->modify("$value $unit");
467 } catch (InvalidFormatException) {
468 throw new UnsupportedUnitException($unit, previous: $exception);
469 }
470 }
471 }
472 }