Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Factory.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 Closure;
17 use DateTimeImmutable;
18 use DateTimeInterface;
19 use DateTimeZone;
20 use InvalidArgumentException;
21 use ReflectionMethod;
22 use RuntimeException;
23 use Symfony\Contracts\Translation\TranslatorInterface;
24 use Throwable;
25
26 /**
27 * A factory to generate Carbon instances with common settings.
28 *
29 * <autodoc generated by `composer phpdoc`>
30 *
31 * @method bool canBeCreatedFromFormat(?string $date, string $format) Checks if the (date)time string is in a given format and valid to create a
32 * new instance.
33 * @method ?Carbon create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null) Create a new Carbon instance from a specific date and time.
34 * If any of $year, $month or $day are set to null their now() values will
35 * be used.
36 * If $hour is null it will be set to its now() value and the default
37 * values for $minute and $second will be their now() values.
38 * If $hour is not null then the default values for $minute and $second
39 * will be 0.
40 * @method Carbon createFromDate($year = null, $month = null, $day = null, $timezone = null) Create a Carbon instance from just a date. The time portion is set to now.
41 * @method ?Carbon createFromFormat($format, $time, $timezone = null) Create a Carbon instance from a specific format.
42 * @method ?Carbon createFromIsoFormat(string $format, string $time, $timezone = null, ?string $locale = 'en', ?TranslatorInterface $translator = null) Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()).
43 * @method ?Carbon createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null) Create a Carbon instance from a specific format and a string in a given language.
44 * @method ?Carbon createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null) Create a Carbon instance from a specific ISO format and a string in a given language.
45 * @method Carbon createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null) Create a Carbon instance from just a time. The date portion is set to today.
46 * @method Carbon createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a time string. The date portion is set to today.
47 * @method Carbon createFromTimestamp(string|int|float $timestamp, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a timestamp and set the timezone (UTC by default).
48 * Timestamp input can be given as int, float or a string containing one or more numbers.
49 * @method Carbon createFromTimestampMs(string|int|float $timestamp, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a timestamp in milliseconds.
50 * Timestamp input can be given as int, float or a string containing one or more numbers.
51 * @method Carbon createFromTimestampMsUTC($timestamp) Create a Carbon instance from a timestamp in milliseconds.
52 * Timestamp input can be given as int, float or a string containing one or more numbers.
53 * @method Carbon createFromTimestampUTC(string|int|float $timestamp) Create a Carbon instance from a timestamp keeping the timezone to UTC.
54 * Timestamp input can be given as int, float or a string containing one or more numbers.
55 * @method Carbon createMidnightDate($year = null, $month = null, $day = null, $timezone = null) Create a Carbon instance from just a date. The time portion is set to midnight.
56 * @method ?Carbon createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null) Create a new safe Carbon instance from a specific date and time.
57 * If any of $year, $month or $day are set to null their now() values will
58 * be used.
59 * If $hour is null it will be set to its now() value and the default
60 * values for $minute and $second will be their now() values.
61 * If $hour is not null then the default values for $minute and $second
62 * will be 0.
63 * If one of the set values is not valid, an InvalidDateException
64 * will be thrown.
65 * @method Carbon createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null) Create a new Carbon instance from a specific date and time using strict validation.
66 * @method mixed executeWithLocale(string $locale, callable $func) Set the current locale to the given, execute the passed function, reset the locale to previous one,
67 * then return the result of the closure (or null if the closure was void).
68 * @method Carbon fromSerialized($value, array $options = []) Create an instance from a serialized string.
69 * If $value is not from a trusted source, consider using the allowed_classes option to limit
70 * the types of objects that can be built, for instance:
71 * @method array getAvailableLocales() Returns the list of internally available locales and already loaded custom locales.
72 * (It will ignore custom translator dynamic loading.)
73 * @method Language[] getAvailableLocalesInfo() Returns list of Language object for each available locale. This object allow you to get the ISO name, native
74 * name, region and variant of the locale.
75 * @method array getDays() Get the days of the week.
76 * @method ?string getFallbackLocale() Get the fallback locale.
77 * @method array getFormatsToIsoReplacements() List of replacements from date() format to isoFormat().
78 * @method array getIsoUnits() Returns list of locale units for ISO formatting.
79 * @method array|false getLastErrors() {@inheritdoc}
80 * @method string getLocale() Get the current translator locale.
81 * @method int getMidDayAt() get midday/noon hour
82 * @method string getTimeFormatByPrecision(string $unitPrecision) Return a format from H:i to H:i:s.u according to given unit precision.
83 * @method string|Closure|null getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) Returns raw translation message for a given key.
84 * @method int getWeekEndsAt(?string $locale = null) Get the last day of week.
85 * @method int getWeekStartsAt(?string $locale = null) Get the first day of week.
86 * @method bool hasRelativeKeywords(?string $time) Determine if a time string will produce a relative date.
87 * @method Carbon instance(DateTimeInterface $date) Create a Carbon instance from a DateTime one.
88 * @method bool isImmutable() Returns true if the current class/instance is immutable.
89 * @method bool isModifiableUnit($unit) Returns true if a property can be changed via setter.
90 * @method bool isMutable() Returns true if the current class/instance is mutable.
91 * @method bool localeHasDiffOneDayWords(string $locale) Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow).
92 * Support is considered enabled if the 3 words are translated in the given locale.
93 * @method bool localeHasDiffSyntax(string $locale) Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after).
94 * Support is considered enabled if the 4 sentences are translated in the given locale.
95 * @method bool localeHasDiffTwoDayWords(string $locale) Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow).
96 * Support is considered enabled if the 2 words are translated in the given locale.
97 * @method bool localeHasPeriodSyntax($locale) Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X).
98 * Support is considered enabled if the 4 sentences are translated in the given locale.
99 * @method bool localeHasShortUnits(string $locale) Returns true if the given locale is internally supported and has short-units support.
100 * Support is considered enabled if either year, day or hour has a short variant translated.
101 * @method ?Carbon make($var, DateTimeZone|string|null $timezone = null) Make a Carbon instance from given variable if possible.
102 * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals
103 * and recurrences). Throw an exception for invalid format, but otherwise return null.
104 * @method void mixin(object|string $mixin) Mix another object into the class.
105 * @method Carbon now(DateTimeZone|string|int|null $timezone = null) Get a Carbon instance for the current date and time.
106 * @method Carbon parse(DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a string.
107 * This is an alias for the constructor that allows better fluent syntax
108 * as it allows you to do Carbon::parse('Monday next week')->fn() rather
109 * than (new Carbon('Monday next week'))->fn().
110 * @method Carbon parseFromLocale(string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.).
111 * @method string pluralUnit(string $unit) Returns standardized plural of a given singular/plural unit name (in English).
112 * @method ?Carbon rawCreateFromFormat(string $format, string $time, $timezone = null) Create a Carbon instance from a specific format.
113 * @method Carbon rawParse(DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a string.
114 * This is an alias for the constructor that allows better fluent syntax
115 * as it allows you to do Carbon::parse('Monday next week')->fn() rather
116 * than (new Carbon('Monday next week'))->fn().
117 * @method void setFallbackLocale(string $locale) Set the fallback locale.
118 * @method void setLocale(string $locale) Set the current translator locale and indicate if the source locale file exists.
119 * Pass 'auto' as locale to use the closest language to the current LC_TIME locale.
120 * @method void setMidDayAt($hour) @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
121 * You should rather consider mid-day is always 12pm, then if you need to test if it's an other
122 * hour, test it explicitly:
123 * $date->format('G') == 13
124 * or to set explicitly to a given hour:
125 * $date->setTime(13, 0, 0, 0)
126 * Set midday/noon hour
127 * @method string singularUnit(string $unit) Returns standardized singular of a given singular/plural unit name (in English).
128 * @method void sleep(int|float $seconds)
129 * @method Carbon today(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for today.
130 * @method Carbon tomorrow(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for tomorrow.
131 * @method string translateTimeString(string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL) Translate a time string from a locale to an other.
132 * @method string translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null) Translate using translation string or callback available.
133 * @method Carbon yesterday(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for yesterday.
134 *
135 * </autodoc>
136 */
137 class Factory
138 {
139 protected string $className = Carbon::class;
140
141 protected array $settings = [];
142
143 /**
144 * A test Carbon instance to be returned when now instances are created.
145 */
146 protected Closure|CarbonInterface|null $testNow = null;
147
148 /**
149 * The timezone to restore to when clearing the time mock.
150 */
151 protected ?string $testDefaultTimezone = null;
152
153 /**
154 * Is true when test-now is generated by a closure and timezone should be taken on the fly from it.
155 */
156 protected bool $useTimezoneFromTestNow = false;
157
158 /**
159 * Default translator.
160 */
161 protected TranslatorInterface $translator;
162
163 /**
164 * Days of weekend.
165 */
166 protected array $weekendDays = [
167 CarbonInterface::SATURDAY,
168 CarbonInterface::SUNDAY,
169 ];
170
171 /**
172 * Format regex patterns.
173 *
174 * @var array<string, string>
175 */
176 protected array $regexFormats = [
177 'd' => '(3[01]|[12][0-9]|0[1-9])',
178 'D' => '(Sun|Mon|Tue|Wed|Thu|Fri|Sat)',
179 'j' => '([123][0-9]|[1-9])',
180 'l' => '([a-zA-Z]{2,})',
181 'N' => '([1-7])',
182 'S' => '(st|nd|rd|th)',
183 'w' => '([0-6])',
184 'z' => '(36[0-5]|3[0-5][0-9]|[12][0-9]{2}|[1-9]?[0-9])',
185 'W' => '(5[012]|[1-4][0-9]|0?[1-9])',
186 'F' => '([a-zA-Z]{2,})',
187 'm' => '(1[012]|0[1-9])',
188 'M' => '([a-zA-Z]{3})',
189 'n' => '(1[012]|[1-9])',
190 't' => '(2[89]|3[01])',
191 'L' => '(0|1)',
192 'o' => '([1-9][0-9]{0,4})',
193 'Y' => '([1-9]?[0-9]{4})',
194 'y' => '([0-9]{2})',
195 'a' => '(am|pm)',
196 'A' => '(AM|PM)',
197 'B' => '([0-9]{3})',
198 'g' => '(1[012]|[1-9])',
199 'G' => '(2[0-3]|1?[0-9])',
200 'h' => '(1[012]|0[1-9])',
201 'H' => '(2[0-3]|[01][0-9])',
202 'i' => '([0-5][0-9])',
203 's' => '([0-5][0-9])',
204 'u' => '([0-9]{1,6})',
205 'v' => '([0-9]{1,3})',
206 'e' => '([a-zA-Z]{1,5})|([a-zA-Z]*\\/[a-zA-Z]*)',
207 'I' => '(0|1)',
208 'O' => '([+-](1[0123]|0[0-9])[0134][05])',
209 'P' => '([+-](1[0123]|0[0-9]):[0134][05])',
210 'p' => '(Z|[+-](1[0123]|0[0-9]):[0134][05])',
211 'T' => '([a-zA-Z]{1,5})',
212 'Z' => '(-?[1-5]?[0-9]{1,4})',
213 'U' => '([0-9]*)',
214
215 // The formats below are combinations of the above formats.
216 'c' => '(([1-9]?[0-9]{4})-(1[012]|0[1-9])-(3[01]|[12][0-9]|0[1-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])[+-](1[012]|0[0-9]):([0134][05]))', // Y-m-dTH:i:sP
217 'r' => '(([a-zA-Z]{3}), ([123][0-9]|0[1-9]) ([a-zA-Z]{3}) ([1-9]?[0-9]{4}) (2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]) [+-](1[012]|0[0-9])([0134][05]))', // D, d M Y H:i:s O
218 ];
219
220 /**
221 * Format modifiers (such as available in createFromFormat) regex patterns.
222 *
223 * @var array
224 */
225 protected array $regexFormatModifiers = [
226 '*' => '.+',
227 ' ' => '[ ]',
228 '#' => '[;:\\/.,()-]',
229 '?' => '([^a]|[a])',
230 '!' => '',
231 '|' => '',
232 '+' => '',
233 ];
234
235 public function __construct(array $settings = [], ?string $className = null)
236 {
237 if ($className) {
238 $this->className = $className;
239 }
240
241 $this->settings = $settings;
242 }
243
244 public function getClassName(): string
245 {
246 return $this->className;
247 }
248
249 public function setClassName(string $className): self
250 {
251 $this->className = $className;
252
253 return $this;
254 }
255
256 public function className(?string $className = null): self|string
257 {
258 return $className === null ? $this->getClassName() : $this->setClassName($className);
259 }
260
261 public function getSettings(): array
262 {
263 return $this->settings;
264 }
265
266 public function setSettings(array $settings): self
267 {
268 $this->settings = $settings;
269
270 return $this;
271 }
272
273 public function settings(?array $settings = null): self|array
274 {
275 return $settings === null ? $this->getSettings() : $this->setSettings($settings);
276 }
277
278 public function mergeSettings(array $settings): self
279 {
280 $this->settings = array_merge($this->settings, $settings);
281
282 return $this;
283 }
284
285 public function setHumanDiffOptions(int $humanDiffOptions): void
286 {
287 $this->mergeSettings([
288 'humanDiffOptions' => $humanDiffOptions,
289 ]);
290 }
291
292 public function enableHumanDiffOption($humanDiffOption): void
293 {
294 $this->setHumanDiffOptions($this->getHumanDiffOptions() | $humanDiffOption);
295 }
296
297 public function disableHumanDiffOption(int $humanDiffOption): void
298 {
299 $this->setHumanDiffOptions($this->getHumanDiffOptions() & ~$humanDiffOption);
300 }
301
302 public function getHumanDiffOptions(): int
303 {
304 return (int) ($this->getSettings()['humanDiffOptions'] ?? 0);
305 }
306
307 /**
308 * Register a custom macro.
309 *
310 * Pass null macro to remove it.
311 *
312 * @example
313 * ```
314 * $userSettings = [
315 * 'locale' => 'pt',
316 * 'timezone' => 'America/Sao_Paulo',
317 * ];
318 * $factory->macro('userFormat', function () use ($userSettings) {
319 * return $this->copy()->locale($userSettings['locale'])->tz($userSettings['timezone'])->calendar();
320 * });
321 * echo $factory->yesterday()->hours(11)->userFormat();
322 * ```
323 *
324 * @param-closure-this static $macro
325 */
326 public function macro(string $name, ?callable $macro): void
327 {
328 $macros = $this->getSettings()['macros'] ?? [];
329 $macros[$name] = $macro;
330
331 $this->mergeSettings([
332 'macros' => $macros,
333 ]);
334 }
335
336 /**
337 * Remove all macros and generic macros.
338 */
339 public function resetMacros(): void
340 {
341 $this->mergeSettings([
342 'macros' => null,
343 'genericMacros' => null,
344 ]);
345 }
346
347 /**
348 * Register a custom macro.
349 *
350 * @param callable $macro
351 * @param int $priority marco with higher priority is tried first
352 *
353 * @return void
354 */
355 public function genericMacro(callable $macro, int $priority = 0): void
356 {
357 $genericMacros = $this->getSettings()['genericMacros'] ?? [];
358
359 if (!isset($genericMacros[$priority])) {
360 $genericMacros[$priority] = [];
361 krsort($genericMacros, SORT_NUMERIC);
362 }
363
364 $genericMacros[$priority][] = $macro;
365
366 $this->mergeSettings([
367 'genericMacros' => $genericMacros,
368 ]);
369 }
370
371 /**
372 * Checks if macro is registered globally.
373 */
374 public function hasMacro(string $name): bool
375 {
376 return isset($this->getSettings()['macros'][$name]);
377 }
378
379 /**
380 * Get the raw callable macro registered globally for a given name.
381 */
382 public function getMacro(string $name): ?callable
383 {
384 return $this->getSettings()['macros'][$name] ?? null;
385 }
386
387 /**
388 * Set the default translator instance to use.
389 */
390 public function setTranslator(TranslatorInterface $translator): void
391 {
392 $this->translator = $translator;
393 }
394
395 /**
396 * Initialize the default translator instance if necessary.
397 */
398 public function getTranslator(): TranslatorInterface
399 {
400 return $this->translator ??= Translator::get();
401 }
402
403 /**
404 * Reset the format used to the default when type juggling a Carbon instance to a string
405 *
406 * @return void
407 */
408 public function resetToStringFormat(): void
409 {
410 $this->setToStringFormat(null);
411 }
412
413 /**
414 * Set the default format used when type juggling a Carbon instance to a string.
415 */
416 public function setToStringFormat(string|Closure|null $format): void
417 {
418 $this->mergeSettings([
419 'toStringFormat' => $format,
420 ]);
421 }
422
423 /**
424 * JSON serialize all Carbon instances using the given callback.
425 */
426 public function serializeUsing(string|callable|null $format): void
427 {
428 $this->mergeSettings([
429 'toJsonFormat' => $format,
430 ]);
431 }
432
433 /**
434 * Enable the strict mode (or disable with passing false).
435 */
436 public function useStrictMode(bool $strictModeEnabled = true): void
437 {
438 $this->mergeSettings([
439 'strictMode' => $strictModeEnabled,
440 ]);
441 }
442
443 /**
444 * Returns true if the strict mode is globally in use, false else.
445 * (It can be overridden in specific instances.)
446 */
447 public function isStrictModeEnabled(): bool
448 {
449 return $this->getSettings()['strictMode'] ?? true;
450 }
451
452 /**
453 * Indicates if months should be calculated with overflow.
454 */
455 public function useMonthsOverflow(bool $monthsOverflow = true): void
456 {
457 $this->mergeSettings([
458 'monthOverflow' => $monthsOverflow,
459 ]);
460 }
461
462 /**
463 * Reset the month overflow behavior.
464 */
465 public function resetMonthsOverflow(): void
466 {
467 $this->useMonthsOverflow();
468 }
469
470 /**
471 * Get the month overflow global behavior (can be overridden in specific instances).
472 */
473 public function shouldOverflowMonths(): bool
474 {
475 return $this->getSettings()['monthOverflow'] ?? true;
476 }
477
478 /**
479 * Indicates if years should be calculated with overflow.
480 */
481 public function useYearsOverflow(bool $yearsOverflow = true): void
482 {
483 $this->mergeSettings([
484 'yearOverflow' => $yearsOverflow,
485 ]);
486 }
487
488 /**
489 * Reset the month overflow behavior.
490 */
491 public function resetYearsOverflow(): void
492 {
493 $this->useYearsOverflow();
494 }
495
496 /**
497 * Get the month overflow global behavior (can be overridden in specific instances).
498 */
499 public function shouldOverflowYears(): bool
500 {
501 return $this->getSettings()['yearOverflow'] ?? true;
502 }
503
504 /**
505 * Get weekend days
506 *
507 * @return array
508 */
509 public function getWeekendDays(): array
510 {
511 return $this->weekendDays;
512 }
513
514 /**
515 * Set weekend days
516 */
517 public function setWeekendDays(array $days): void
518 {
519 $this->weekendDays = $days;
520 }
521
522 /**
523 * Checks if the (date)time string is in a given format.
524 *
525 * @example
526 * ```
527 * Carbon::hasFormat('11:12:45', 'h:i:s'); // true
528 * Carbon::hasFormat('13:12:45', 'h:i:s'); // false
529 * ```
530 */
531 public function hasFormat(string $date, string $format): bool
532 {
533 // createFromFormat() is known to handle edge cases silently.
534 // E.g. "1975-5-1" (Y-n-j) will still be parsed correctly when "Y-m-d" is supplied as the format.
535 // To ensure we're really testing against our desired format, perform an additional regex validation.
536
537 return $this->matchFormatPattern($date, preg_quote($format, '/'), $this->regexFormats);
538 }
539
540 /**
541 * Checks if the (date)time string is in a given format.
542 *
543 * @example
544 * ```
545 * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true
546 * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false
547 * ```
548 */
549 public function hasFormatWithModifiers(string $date, string $format): bool
550 {
551 return $this->matchFormatPattern($date, $format, array_merge($this->regexFormats, $this->regexFormatModifiers));
552 }
553
554 /**
555 * Set a Carbon instance (real or mock) to be returned when a "now"
556 * instance is created. The provided instance will be returned
557 * specifically under the following conditions:
558 * - A call to the static now() method, ex. Carbon::now()
559 * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null)
560 * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now')
561 * - When a string containing the desired time is passed to Carbon::parse().
562 *
563 * Note the timezone parameter was left out of the examples above and
564 * has no affect as the mock value will be returned regardless of its value.
565 *
566 * Only the moment is mocked with setTestNow(), the timezone will still be the one passed
567 * as parameter of date_default_timezone_get() as a fallback (see setTestNowAndTimezone()).
568 *
569 * To clear the test instance call this method using the default
570 * parameter of null.
571 *
572 * /!\ Use this method for unit tests only.
573 *
574 * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance
575 */
576 public function setTestNow(mixed $testNow = null): void
577 {
578 $this->useTimezoneFromTestNow = false;
579 $this->testNow = $testNow instanceof self || $testNow instanceof Closure
580 ? $testNow
581 : $this->make($testNow);
582 }
583
584 /**
585 * Set a Carbon instance (real or mock) to be returned when a "now"
586 * instance is created. The provided instance will be returned
587 * specifically under the following conditions:
588 * - A call to the static now() method, ex. Carbon::now()
589 * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null)
590 * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now')
591 * - When a string containing the desired time is passed to Carbon::parse().
592 *
593 * It will also align default timezone (e.g. call date_default_timezone_set()) with
594 * the second argument or if null, with the timezone of the given date object.
595 *
596 * To clear the test instance call this method using the default
597 * parameter of null.
598 *
599 * /!\ Use this method for unit tests only.
600 *
601 * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance
602 */
603 public function setTestNowAndTimezone(mixed $testNow = null, $timezone = null): void
604 {
605 if ($testNow) {
606 $this->testDefaultTimezone ??= date_default_timezone_get();
607 }
608
609 $useDateInstanceTimezone = $testNow instanceof DateTimeInterface;
610
611 if ($useDateInstanceTimezone) {
612 $this->setDefaultTimezone($testNow->getTimezone()->getName(), $testNow);
613 }
614
615 $this->setTestNow($testNow);
616 $this->useTimezoneFromTestNow = ($timezone === null && $testNow instanceof Closure);
617
618 if (!$useDateInstanceTimezone) {
619 $now = $this->getMockedTestNow(\func_num_args() === 1 ? null : $timezone);
620 $this->setDefaultTimezone($now?->tzName ?? $this->testDefaultTimezone ?? 'UTC', $now);
621 }
622
623 if (!$testNow) {
624 $this->testDefaultTimezone = null;
625 }
626 }
627
628 /**
629 * Temporarily sets a static date to be used within the callback.
630 * Using setTestNow to set the date, executing the callback, then
631 * clearing the test instance.
632 *
633 * /!\ Use this method for unit tests only.
634 *
635 * @template T
636 *
637 * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance
638 * @param Closure(): T $callback
639 *
640 * @return T
641 */
642 public function withTestNow(mixed $testNow, callable $callback): mixed
643 {
644 $previousTestNow = $this->getTestNow();
645 $this->setTestNow($testNow);
646
647 try {
648 $result = $callback();
649 } finally {
650 $this->setTestNow($previousTestNow);
651 }
652
653 return $result;
654 }
655
656 /**
657 * Get the Carbon instance (real or mock) to be returned when a "now"
658 * instance is created.
659 *
660 * @return Closure|CarbonInterface|null the current instance used for testing
661 */
662 public function getTestNow(): Closure|CarbonInterface|null
663 {
664 if ($this->testNow === null) {
665 $factory = FactoryImmutable::getDefaultInstance();
666
667 if ($factory !== $this) {
668 return $factory->getTestNow();
669 }
670 }
671
672 return $this->testNow;
673 }
674
675 public function handleTestNowClosure(
676 Closure|CarbonInterface|null $testNow,
677 DateTimeZone|string|int|null $timezone = null,
678 ): ?CarbonInterface {
679 if ($testNow instanceof Closure) {
680 $callback = Callback::fromClosure($testNow);
681 $realNow = new DateTimeImmutable('now');
682 $testNow = $testNow($callback->prepareParameter($this->parse(
683 $realNow->format('Y-m-d H:i:s.u'),
684 $timezone ?? $realNow->getTimezone(),
685 )));
686
687 if ($testNow !== null && !($testNow instanceof DateTimeInterface)) {
688 $function = $callback->getReflectionFunction();
689 $type = \is_object($testNow) ? $testNow::class : \gettype($testNow);
690
691 throw new RuntimeException(
692 'The test closure defined in '.$function->getFileName().
693 ' at line '.$function->getStartLine().' returned '.$type.
694 '; expected '.CarbonInterface::class.'|null',
695 );
696 }
697
698 if (!($testNow instanceof CarbonInterface)) {
699 $timezone ??= $this->useTimezoneFromTestNow ? $testNow->getTimezone() : null;
700 $testNow = $this->__call('instance', [$testNow, $timezone]);
701 }
702 }
703
704 return $testNow;
705 }
706
707 /**
708 * Determine if there is a valid test instance set. A valid test instance
709 * is anything that is not null.
710 *
711 * @return bool true if there is a test instance, otherwise false
712 */
713 public function hasTestNow(): bool
714 {
715 return $this->getTestNow() !== null;
716 }
717
718 public function withTimeZone(DateTimeZone|string|int|null $timezone): static
719 {
720 $factory = clone $this;
721 $factory->settings['timezone'] = $timezone;
722
723 return $factory;
724 }
725
726 public function __call(string $name, array $arguments): mixed
727 {
728 $method = new ReflectionMethod($this->className, $name);
729 $settings = $this->settings;
730
731 if ($settings && isset($settings['timezone'])) {
732 $timezoneParameters = array_filter($method->getParameters(), function ($parameter) {
733 return \in_array($parameter->getName(), ['tz', 'timezone'], true);
734 });
735 $timezoneSetting = $settings['timezone'];
736
737 if (isset($arguments[0]) && \in_array($name, ['instance', 'make', 'create', 'parse'], true)) {
738 if ($arguments[0] instanceof DateTimeInterface) {
739 $settings['innerTimezone'] = $settings['timezone'];
740 } elseif (\is_string($arguments[0]) && date_parse($arguments[0])['is_localtime']) {
741 unset($settings['timezone'], $settings['innerTimezone']);
742 }
743 }
744
745 if (\count($timezoneParameters)) {
746 $index = key($timezoneParameters);
747
748 if (!isset($arguments[$index])) {
749 array_splice($arguments, key($timezoneParameters), 0, [$timezoneSetting]);
750 }
751
752 unset($settings['timezone']);
753 }
754 }
755
756 $clock = FactoryImmutable::getCurrentClock();
757 FactoryImmutable::setCurrentClock($this);
758
759 try {
760 $result = $this->className::$name(...$arguments);
761 } finally {
762 FactoryImmutable::setCurrentClock($clock);
763 }
764
765 if (isset($this->translator)) {
766 $settings['translator'] = $this->translator;
767 }
768
769 return $result instanceof CarbonInterface && !empty($settings)
770 ? $result->settings($settings)
771 : $result;
772 }
773
774 /**
775 * Get the mocked date passed in setTestNow() and if it's a Closure, execute it.
776 */
777 protected function getMockedTestNow(DateTimeZone|string|int|null $timezone): ?CarbonInterface
778 {
779 $testNow = $this->handleTestNowClosure($this->getTestNow());
780
781 if ($testNow instanceof CarbonInterface) {
782 $testNow = $testNow->avoidMutation();
783
784 if ($timezone !== null) {
785 return $testNow->setTimezone($timezone);
786 }
787 }
788
789 return $testNow;
790 }
791
792 /**
793 * Checks if the (date)time string is in a given format with
794 * given list of pattern replacements.
795 *
796 * @example
797 * ```
798 * Carbon::hasFormat('11:12:45', 'h:i:s'); // true
799 * Carbon::hasFormat('13:12:45', 'h:i:s'); // false
800 * ```
801 *
802 * @param string $date
803 * @param string $format
804 * @param array $replacements
805 *
806 * @return bool
807 */
808 private function matchFormatPattern(string $date, string $format, array $replacements): bool
809 {
810 // Preg quote, but remove escaped backslashes since we'll deal with escaped characters in the format string.
811 $regex = str_replace('\\\\', '\\', $format);
812 // Replace not-escaped letters
813 $regex = preg_replace_callback(
814 '/(?<!\\\\)((?:\\\\{2})*)(['.implode('', array_keys($replacements)).'])/',
815 static fn ($match) => $match[1].strtr($match[2], $replacements),
816 $regex,
817 );
818 // Replace escaped letters by the letter itself
819 $regex = preg_replace('/(?<!\\\\)((?:\\\\{2})*)\\\\(\w)/', '$1$2', $regex);
820 // Escape not escaped slashes
821 $regex = preg_replace('#(?<!\\\\)((?:\\\\{2})*)/#', '$1\\/', $regex);
822
823 return (bool) @preg_match('/^'.$regex.'$/', $date);
824 }
825
826 private function setDefaultTimezone(string $timezone, ?DateTimeInterface $date = null): void
827 {
828 $previous = null;
829 $success = false;
830
831 try {
832 $success = date_default_timezone_set($timezone);
833 } catch (Throwable $exception) {
834 $previous = $exception;
835 }
836
837 if (!$success) {
838 $suggestion = @CarbonTimeZone::create($timezone)->toRegionName($date);
839
840 throw new InvalidArgumentException(
841 "Timezone ID '$timezone' is invalid".
842 ($suggestion && $suggestion !== $timezone ? ", did you mean '$suggestion'?" : '.')."\n".
843 "It must be one of the IDs from DateTimeZone::listIdentifiers(),\n".
844 'For the record, hours/minutes offset are relevant only for a particular moment, '.
845 'but not as a default timezone.',
846 0,
847 $previous
848 );
849 }
850 }
851 }