Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Traits/Creator.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\Carbon;
17 use Carbon\CarbonImmutable;
18 use Carbon\CarbonInterface;
19 use Carbon\Exceptions\InvalidDateException;
20 use Carbon\Exceptions\InvalidFormatException;
21 use Carbon\Exceptions\InvalidTimeZoneException;
22 use Carbon\Exceptions\OutOfRangeException;
23 use Carbon\Exceptions\UnitException;
24 use Carbon\Month;
25 use Carbon\Translator;
26 use Carbon\WeekDay;
27 use Closure;
28 use DateMalformedStringException;
29 use DateTimeImmutable;
30 use DateTimeInterface;
31 use DateTimeZone;
32 use Exception;
33 use ReturnTypeWillChange;
34 use Symfony\Contracts\Translation\TranslatorInterface;
35
36 /**
37 * Trait Creator.
38 *
39 * Static creators.
40 *
41 * Depends on the following methods:
42 *
43 * @method static Carbon|CarbonImmutable getTestNow()
44 */
45 trait Creator
46 {
47 use ObjectInitialisation;
48 use LocalFactory;
49
50 /**
51 * The errors that can occur.
52 */
53 protected static array|bool $lastErrors = false;
54
55 /**
56 * Create a new Carbon instance.
57 *
58 * Please see the testing aids section (specifically static::setTestNow())
59 * for more on the possibility of this constructor returning a test instance.
60 *
61 * @throws InvalidFormatException
62 */
63 public function __construct(
64 DateTimeInterface|WeekDay|Month|string|int|float|null $time = null,
65 DateTimeZone|string|int|null $timezone = null,
66 ) {
67 $this->initLocalFactory();
68
69 if ($time instanceof Month) {
70 $time = $time->name.' 1';
71 } elseif ($time instanceof WeekDay) {
72 $time = $time->name;
73 } elseif ($time instanceof DateTimeInterface) {
74 $time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u');
75 }
76
77 if (\is_string($time) && str_starts_with($time, '@')) {
78 $time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP');
79 } elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) {
80 $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP');
81 }
82
83 // If the class has a test now set, and we are trying to create a now()
84 // instance then override as required
85 $isNow = \in_array($time, [null, '', 'now'], true);
86 $timezone = static::safeCreateDateTimeZone($timezone) ?? null;
87
88 if (
89 ($this->clock || (
90 method_exists(static::class, 'hasTestNow') &&
91 method_exists(static::class, 'getTestNow') &&
92 static::hasTestNow()
93 )) &&
94 ($isNow || static::hasRelativeKeywords($time))
95 ) {
96 $this->mockConstructorParameters($time, $timezone);
97 }
98
99 try {
100 parent::__construct($time ?? 'now', $timezone);
101 } catch (Exception $exception) {
102 throw new InvalidFormatException($exception->getMessage(), 0, $exception);
103 }
104
105 $this->constructedObjectId = spl_object_hash($this);
106
107 self::setLastErrors(parent::getLastErrors());
108 }
109
110 /**
111 * Get timezone from a datetime instance.
112 */
113 private function constructTimezoneFromDateTime(
114 DateTimeInterface $date,
115 DateTimeZone|string|int|null &$timezone,
116 ): DateTimeInterface {
117 if ($timezone !== null) {
118 $safeTz = static::safeCreateDateTimeZone($timezone);
119
120 if ($safeTz) {
121 $date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz);
122 }
123
124 return $date;
125 }
126
127 $timezone = $date->getTimezone();
128
129 return $date;
130 }
131
132 /**
133 * Update constructedObjectId on cloned.
134 */
135 public function __clone(): void
136 {
137 $this->constructedObjectId = spl_object_hash($this);
138 }
139
140 /**
141 * Create a Carbon instance from a DateTime one.
142 */
143 public static function instance(DateTimeInterface $date): static
144 {
145 if ($date instanceof static) {
146 return clone $date;
147 }
148
149 $instance = parent::createFromFormat('U.u', $date->format('U.u'))
150 ->setTimezone($date->getTimezone());
151
152 if ($date instanceof CarbonInterface) {
153 $settings = $date->getSettings();
154
155 if (!$date->hasLocalTranslator()) {
156 unset($settings['locale']);
157 }
158
159 $instance->settings($settings);
160 }
161
162 return $instance;
163 }
164
165 /**
166 * Create a carbon instance from a string.
167 *
168 * This is an alias for the constructor that allows better fluent syntax
169 * as it allows you to do Carbon::parse('Monday next week')->fn() rather
170 * than (new Carbon('Monday next week'))->fn().
171 *
172 * @throws InvalidFormatException
173 */
174 public static function rawParse(
175 DateTimeInterface|WeekDay|Month|string|int|float|null $time,
176 DateTimeZone|string|int|null $timezone = null,
177 ): static {
178 if ($time instanceof DateTimeInterface) {
179 return static::instance($time);
180 }
181
182 try {
183 return new static($time, $timezone);
184 } catch (Exception $exception) {
185 // @codeCoverageIgnoreStart
186 try {
187 $date = @static::now($timezone)->change($time);
188 } catch (DateMalformedStringException|InvalidFormatException) {
189 $date = null;
190 }
191 // @codeCoverageIgnoreEnd
192
193 return $date
194 ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception);
195 }
196 }
197
198 /**
199 * Create a carbon instance from a string.
200 *
201 * This is an alias for the constructor that allows better fluent syntax
202 * as it allows you to do Carbon::parse('Monday next week')->fn() rather
203 * than (new Carbon('Monday next week'))->fn().
204 *
205 * @throws InvalidFormatException
206 */
207 public static function parse(
208 DateTimeInterface|WeekDay|Month|string|int|float|null $time,
209 DateTimeZone|string|int|null $timezone = null,
210 ): static {
211 $function = static::$parseFunction;
212
213 if (!$function) {
214 return static::rawParse($time, $timezone);
215 }
216
217 if (\is_string($function) && method_exists(static::class, $function)) {
218 $function = [static::class, $function];
219 }
220
221 return $function(...\func_get_args());
222 }
223
224 /**
225 * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.).
226 *
227 * @param string $time date/time string in the given language (may also contain English).
228 * @param string|null $locale if locale is null or not specified, current global locale will be
229 * used instead.
230 * @param DateTimeZone|string|int|null $timezone optional timezone for the new instance.
231 *
232 * @throws InvalidFormatException
233 */
234 public static function parseFromLocale(
235 string $time,
236 ?string $locale = null,
237 DateTimeZone|string|int|null $timezone = null,
238 ): static {
239 return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone);
240 }
241
242 /**
243 * Get a Carbon instance for the current date and time.
244 */
245 public static function now(DateTimeZone|string|int|null $timezone = null): static
246 {
247 return new static(null, $timezone);
248 }
249
250 /**
251 * Create a Carbon instance for today.
252 */
253 public static function today(DateTimeZone|string|int|null $timezone = null): static
254 {
255 return static::rawParse('today', $timezone);
256 }
257
258 /**
259 * Create a Carbon instance for tomorrow.
260 */
261 public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static
262 {
263 return static::rawParse('tomorrow', $timezone);
264 }
265
266 /**
267 * Create a Carbon instance for yesterday.
268 */
269 public static function yesterday(DateTimeZone|string|int|null $timezone = null): static
270 {
271 return static::rawParse('yesterday', $timezone);
272 }
273
274 private static function assertBetween($unit, $value, $min, $max): void
275 {
276 if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) {
277 throw new OutOfRangeException($unit, $min, $max, $value);
278 }
279 }
280
281 private static function createNowInstance($timezone)
282 {
283 if (!static::hasTestNow()) {
284 return static::now($timezone);
285 }
286
287 $now = static::getTestNow();
288
289 if ($now instanceof Closure) {
290 return $now(static::now($timezone));
291 }
292
293 $now = $now->avoidMutation();
294
295 return $timezone === null ? $now : $now->setTimezone($timezone);
296 }
297
298 /**
299 * Create a new Carbon instance from a specific date and time.
300 *
301 * If any of $year, $month or $day are set to null their now() values will
302 * be used.
303 *
304 * If $hour is null it will be set to its now() value and the default
305 * values for $minute and $second will be their now() values.
306 *
307 * If $hour is not null then the default values for $minute and $second
308 * will be 0.
309 *
310 * @param DateTimeInterface|string|int|null $year
311 * @param int|null $month
312 * @param int|null $day
313 * @param int|null $hour
314 * @param int|null $minute
315 * @param int|null $second
316 * @param DateTimeZone|string|int|null $timezone
317 *
318 * @throws InvalidFormatException
319 *
320 * @return static|null
321 */
322 public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static
323 {
324 $month = self::monthToInt($month);
325
326 if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) {
327 return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null));
328 }
329
330 $defaults = null;
331 $getDefault = function ($unit) use ($timezone, &$defaults) {
332 if ($defaults === null) {
333 $now = self::createNowInstance($timezone);
334
335 $defaults = array_combine([
336 'year',
337 'month',
338 'day',
339 'hour',
340 'minute',
341 'second',
342 ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u')));
343 }
344
345 return $defaults[$unit];
346 };
347
348 $year = $year ?? $getDefault('year');
349 $month = $month ?? $getDefault('month');
350 $day = $day ?? $getDefault('day');
351 $hour = $hour ?? $getDefault('hour');
352 $minute = $minute ?? $getDefault('minute');
353 $second = (float) ($second ?? $getDefault('second'));
354
355 self::assertBetween('month', $month, 0, 99);
356 self::assertBetween('day', $day, 0, 99);
357 self::assertBetween('hour', $hour, 0, 99);
358 self::assertBetween('minute', $minute, 0, 99);
359 self::assertBetween('second', $second, 0, 99);
360
361 $fixYear = null;
362
363 if ($year < 0) {
364 $fixYear = $year;
365 $year = 0;
366 } elseif ($year > 9999) {
367 $fixYear = $year - 9999;
368 $year = 9999;
369 }
370
371 $second = ($second < 10 ? '0' : '').number_format($second, 6);
372 $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone);
373
374 if ($instance && $fixYear !== null) {
375 $instance = $instance->addYears($fixYear);
376 }
377
378 return $instance ?? null;
379 }
380
381 /**
382 * Create a new safe Carbon instance from a specific date and time.
383 *
384 * If any of $year, $month or $day are set to null their now() values will
385 * be used.
386 *
387 * If $hour is null it will be set to its now() value and the default
388 * values for $minute and $second will be their now() values.
389 *
390 * If $hour is not null then the default values for $minute and $second
391 * will be 0.
392 *
393 * If one of the set values is not valid, an InvalidDateException
394 * will be thrown.
395 *
396 * @param int|null $year
397 * @param int|null $month
398 * @param int|null $day
399 * @param int|null $hour
400 * @param int|null $minute
401 * @param int|null $second
402 * @param DateTimeZone|string|int|null $timezone
403 *
404 * @throws InvalidDateException
405 *
406 * @return static|null
407 */
408 public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static
409 {
410 $month = self::monthToInt($month);
411 $fields = static::getRangesByUnit();
412
413 foreach ($fields as $field => $range) {
414 if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) {
415 if (static::isStrictModeEnabled()) {
416 throw new InvalidDateException($field, $$field);
417 }
418
419 return null;
420 }
421 }
422
423 $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone);
424
425 foreach (array_reverse($fields) as $field => $range) {
426 if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) {
427 if (static::isStrictModeEnabled()) {
428 throw new InvalidDateException($field, $$field);
429 }
430
431 return null;
432 }
433 }
434
435 return $instance;
436 }
437
438 /**
439 * Create a new Carbon instance from a specific date and time using strict validation.
440 *
441 * @see create()
442 *
443 * @param int|null $year
444 * @param int|null $month
445 * @param int|null $day
446 * @param int|null $hour
447 * @param int|null $minute
448 * @param int|null $second
449 * @param DateTimeZone|string|int|null $timezone
450 *
451 * @throws InvalidFormatException
452 *
453 * @return static
454 */
455 public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static
456 {
457 $initialStrictMode = static::isStrictModeEnabled();
458 static::useStrictMode(true);
459
460 try {
461 $date = static::create($year, $month, $day, $hour, $minute, $second, $timezone);
462 } finally {
463 static::useStrictMode($initialStrictMode);
464 }
465
466 return $date;
467 }
468
469 /**
470 * Create a Carbon instance from just a date. The time portion is set to now.
471 *
472 * @param int|null $year
473 * @param int|null $month
474 * @param int|null $day
475 * @param DateTimeZone|string|int|null $timezone
476 *
477 * @throws InvalidFormatException
478 *
479 * @return static
480 */
481 public static function createFromDate($year = null, $month = null, $day = null, $timezone = null)
482 {
483 return static::create($year, $month, $day, null, null, null, $timezone);
484 }
485
486 /**
487 * Create a Carbon instance from just a date. The time portion is set to midnight.
488 *
489 * @param int|null $year
490 * @param int|null $month
491 * @param int|null $day
492 * @param DateTimeZone|string|int|null $timezone
493 *
494 * @throws InvalidFormatException
495 *
496 * @return static
497 */
498 public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null)
499 {
500 return static::create($year, $month, $day, 0, 0, 0, $timezone);
501 }
502
503 /**
504 * Create a Carbon instance from just a time. The date portion is set to today.
505 *
506 * @param int|null $hour
507 * @param int|null $minute
508 * @param int|null $second
509 * @param DateTimeZone|string|int|null $timezone
510 *
511 * @throws InvalidFormatException
512 *
513 * @return static
514 */
515 public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static
516 {
517 return static::create(null, null, null, $hour, $minute, $second, $timezone);
518 }
519
520 /**
521 * Create a Carbon instance from a time string. The date portion is set to today.
522 *
523 * @throws InvalidFormatException
524 */
525 public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static
526 {
527 return static::today($timezone)->setTimeFromTimeString($time);
528 }
529
530 private static function createFromFormatAndTimezone(
531 string $format,
532 string $time,
533 DateTimeZone|string|int|null $originalTimezone,
534 ): ?DateTimeInterface {
535 if ($originalTimezone === null) {
536 return parent::createFromFormat($format, $time) ?: null;
537 }
538
539 $timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone;
540
541 $timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone);
542
543 return parent::createFromFormat($format, $time, $timezone) ?: null;
544 }
545
546 private static function getOffsetTimezone(int $offset): string
547 {
548 $minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE);
549
550 return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException(
551 "Invalid offset timezone $offset",
552 );
553 }
554
555 /**
556 * Create a Carbon instance from a specific format.
557 *
558 * @param string $format Datetime format
559 * @param string $time
560 * @param DateTimeZone|string|int|null $timezone
561 *
562 * @throws InvalidFormatException
563 *
564 * @return static|null
565 */
566 public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static
567 {
568 // Work-around for https://bugs.php.net/bug.php?id=80141
569 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format);
570
571 if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) &&
572 preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) &&
573 $aMatches[1][1] < $hMatches[1][1] &&
574 preg_match('/(am|pm|AM|PM)/', $time)
575 ) {
576 $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format);
577 $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time);
578 }
579
580 if ($timezone === false) {
581 $timezone = null;
582 }
583
584 // First attempt to create an instance, so that error messages are based on the unmodified format.
585 $date = self::createFromFormatAndTimezone($format, $time, $timezone);
586 $lastErrors = parent::getLastErrors();
587 /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */
588 $mock = static::getMockedTestNow($timezone);
589
590 if ($mock && $date instanceof DateTimeInterface) {
591 // Set timezone from mock if custom timezone was neither given directly nor as a part of format.
592 // First let's skip the part that will be ignored by the parser.
593 $nonEscaped = '(?<!\\\\)(\\\\{2})*';
594
595 $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format);
596
597 if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) {
598 $timezone = clone $mock->getTimezone();
599 }
600
601 $mock = $mock->copy();
602
603 // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag.
604 if (!preg_match("/{$nonEscaped}[!|]/", $format)) {
605 if (preg_match('/[HhGgisvuB]/', $format)) {
606 $mock = $mock->setTime(0, 0);
607 }
608
609 $format = static::MOCK_DATETIME_FORMAT.' '.$format;
610 $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time;
611 }
612
613 // Regenerate date from the modified format to base result on the mocked instance instead of now.
614 $date = self::createFromFormatAndTimezone($format, $time, $timezone);
615 }
616
617 if ($date instanceof DateTimeInterface) {
618 $instance = static::instance($date);
619 $instance::setLastErrors($lastErrors);
620
621 return $instance;
622 }
623
624 if (static::isStrictModeEnabled()) {
625 throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors']));
626 }
627
628 return null;
629 }
630
631 /**
632 * Create a Carbon instance from a specific format.
633 *
634 * @param string $format Datetime format
635 * @param string $time
636 * @param DateTimeZone|string|int|null $timezone
637 *
638 * @throws InvalidFormatException
639 *
640 * @return static|null
641 */
642 #[ReturnTypeWillChange]
643 public static function createFromFormat($format, $time, $timezone = null): ?static
644 {
645 $function = static::$createFromFormatFunction;
646
647 // format is a single numeric unit
648 if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) {
649 $time = (string) $time;
650 }
651
652 if (!\is_string($time)) {
653 @trigger_error(
654 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version',
655 \E_USER_DEPRECATED,
656 );
657 $time = (string) $time;
658 }
659
660 if (!$function) {
661 return static::rawCreateFromFormat($format, $time, $timezone);
662 }
663
664 if (\is_string($function) && method_exists(static::class, $function)) {
665 $function = [static::class, $function];
666 }
667
668 return $function(...\func_get_args());
669 }
670
671 /**
672 * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()).
673 *
674 * @param string $format Datetime format
675 * @param string $time
676 * @param DateTimeZone|string|int|null $timezone optional timezone
677 * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use)
678 * @param TranslatorInterface|null $translator optional custom translator to use for macro-formats
679 *
680 * @throws InvalidFormatException
681 *
682 * @return static|null
683 */
684 public static function createFromIsoFormat(
685 string $format,
686 string $time,
687 $timezone = null,
688 ?string $locale = CarbonInterface::DEFAULT_LOCALE,
689 ?TranslatorInterface $translator = null
690 ): ?static {
691 $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) {
692 [$code] = $match;
693
694 static $formats = null;
695
696 if ($formats === null) {
697 $translator ??= Translator::get($locale);
698
699 $formats = [
700 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale),
701 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale),
702 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale),
703 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale),
704 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale),
705 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale),
706 ];
707 }
708
709 return $formats[$code] ?? preg_replace_callback(
710 '/MMMM|MM|DD|dddd/',
711 static fn (array $code) => mb_substr($code[0], 1),
712 $formats[strtoupper($code)] ?? '',
713 );
714 }, $format);
715
716 $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) {
717 [$code] = $match;
718
719 static $replacements = null;
720
721 if ($replacements === null) {
722 $replacements = [
723 'OD' => 'd',
724 'OM' => 'M',
725 'OY' => 'Y',
726 'OH' => 'G',
727 'Oh' => 'g',
728 'Om' => 'i',
729 'Os' => 's',
730 'D' => 'd',
731 'DD' => 'd',
732 'Do' => 'd',
733 'd' => '!',
734 'dd' => '!',
735 'ddd' => 'D',
736 'dddd' => 'D',
737 'DDD' => 'z',
738 'DDDD' => 'z',
739 'DDDo' => 'z',
740 'e' => '!',
741 'E' => '!',
742 'H' => 'G',
743 'HH' => 'H',
744 'h' => 'g',
745 'hh' => 'h',
746 'k' => 'G',
747 'kk' => 'G',
748 'hmm' => 'gi',
749 'hmmss' => 'gis',
750 'Hmm' => 'Gi',
751 'Hmmss' => 'Gis',
752 'm' => 'i',
753 'mm' => 'i',
754 'a' => 'a',
755 'A' => 'a',
756 's' => 's',
757 'ss' => 's',
758 'S' => '*',
759 'SS' => '*',
760 'SSS' => '*',
761 'SSSS' => '*',
762 'SSSSS' => '*',
763 'SSSSSS' => 'u',
764 'SSSSSSS' => 'u*',
765 'SSSSSSSS' => 'u*',
766 'SSSSSSSSS' => 'u*',
767 'M' => 'm',
768 'MM' => 'm',
769 'MMM' => 'M',
770 'MMMM' => 'M',
771 'Mo' => 'm',
772 'Q' => '!',
773 'Qo' => '!',
774 'G' => '!',
775 'GG' => '!',
776 'GGG' => '!',
777 'GGGG' => '!',
778 'GGGGG' => '!',
779 'g' => '!',
780 'gg' => '!',
781 'ggg' => '!',
782 'gggg' => '!',
783 'ggggg' => '!',
784 'W' => '!',
785 'WW' => '!',
786 'Wo' => '!',
787 'w' => '!',
788 'ww' => '!',
789 'wo' => '!',
790 'x' => 'U???',
791 'X' => 'U',
792 'Y' => 'Y',
793 'YY' => 'y',
794 'YYYY' => 'Y',
795 'YYYYY' => 'Y',
796 'YYYYYY' => 'Y',
797 'z' => 'e',
798 'zz' => 'e',
799 'Z' => 'e',
800 'ZZ' => 'e',
801 ];
802 }
803
804 $format = $replacements[$code] ?? '?';
805
806 if ($format === '!') {
807 throw new InvalidFormatException("Format $code not supported for creation.");
808 }
809
810 return $format;
811 }, $format);
812
813 return static::rawCreateFromFormat($format, $time, $timezone);
814 }
815
816 /**
817 * Create a Carbon instance from a specific format and a string in a given language.
818 *
819 * @param string $format Datetime format
820 * @param string $locale
821 * @param string $time
822 * @param DateTimeZone|string|int|null $timezone
823 *
824 * @throws InvalidFormatException
825 *
826 * @return static|null
827 */
828 public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static
829 {
830 $format = preg_replace_callback(
831 '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/',
832 static function (array $match) use ($locale): string {
833 $word = str_replace('\\', '', $match[0]);
834 $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE);
835
836 return $word === $translatedWord
837 ? $match[0]
838 : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord);
839 },
840 $format
841 );
842
843 return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone);
844 }
845
846 /**
847 * Create a Carbon instance from a specific ISO format and a string in a given language.
848 *
849 * @param string $format Datetime ISO format
850 * @param string $locale
851 * @param string $time
852 * @param DateTimeZone|string|int|null $timezone
853 *
854 * @throws InvalidFormatException
855 *
856 * @return static|null
857 */
858 public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?static
859 {
860 $time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM);
861
862 return static::createFromIsoFormat($format, $time, $timezone, $locale);
863 }
864
865 /**
866 * Make a Carbon instance from given variable if possible.
867 *
868 * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals
869 * and recurrences). Throw an exception for invalid format, but otherwise return null.
870 *
871 * @param mixed $var
872 *
873 * @throws InvalidFormatException
874 *
875 * @return static|null
876 */
877 public static function make($var, DateTimeZone|string|null $timezone = null): ?static
878 {
879 if ($var instanceof DateTimeInterface) {
880 return static::instance($var);
881 }
882
883 $date = null;
884
885 if (\is_string($var)) {
886 $var = trim($var);
887
888 if (!preg_match('/^P[\dT]/', $var) &&
889 !preg_match('/^R\d/', $var) &&
890 preg_match('/[a-z\d]/i', $var)
891 ) {
892 $date = static::parse($var, $timezone);
893 }
894 }
895
896 return $date;
897 }
898
899 /**
900 * Set last errors.
901 *
902 * @param array|bool $lastErrors
903 *
904 * @return void
905 */
906 private static function setLastErrors($lastErrors): void
907 {
908 static::$lastErrors = $lastErrors;
909 }
910
911 /**
912 * {@inheritdoc}
913 */
914 public static function getLastErrors(): array|false
915 {
916 return static::$lastErrors;
917 }
918
919 private static function monthToInt(mixed $value, string $unit = 'month'): mixed
920 {
921 if ($value instanceof Month) {
922 if ($unit !== 'month') {
923 throw new UnitException("Month enum cannot be used to set $unit");
924 }
925
926 return Month::int($value);
927 }
928
929 return $value;
930 }
931 }