Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Traits/Localization.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\CarbonInterface;
17 use Carbon\Exceptions\InvalidTypeException;
18 use Carbon\Exceptions\NotLocaleAwareException;
19 use Carbon\Language;
20 use Carbon\Translator;
21 use Carbon\TranslatorStrongTypeInterface;
22 use Closure;
23 use Symfony\Component\Translation\TranslatorBagInterface;
24 use Symfony\Contracts\Translation\LocaleAwareInterface;
25 use Symfony\Contracts\Translation\TranslatorInterface;
26
27 /**
28 * Trait Localization.
29 *
30 * Embed default and locale translators and translation base methods.
31 */
32 trait Localization
33 {
34 use StaticLocalization;
35
36 /**
37 * Specific translator of the current instance.
38 */
39 protected ?TranslatorInterface $localTranslator = null;
40
41 /**
42 * Return true if the current instance has its own translator.
43 */
44 public function hasLocalTranslator(): bool
45 {
46 return isset($this->localTranslator);
47 }
48
49 /**
50 * Get the translator of the current instance or the default if none set.
51 */
52 public function getLocalTranslator(): TranslatorInterface
53 {
54 return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator());
55 }
56
57 /**
58 * Set the translator for the current instance.
59 */
60 public function setLocalTranslator(TranslatorInterface $translator): self
61 {
62 $this->localTranslator = $translator;
63
64 return $this;
65 }
66
67 /**
68 * Returns raw translation message for a given key.
69 *
70 * @param TranslatorInterface|null $translator the translator to use
71 * @param string $key key to find
72 * @param string|null $locale current locale used if null
73 * @param string|null $default default value if translation returns the key
74 *
75 * @return string|Closure|null
76 */
77 public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null)
78 {
79 if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) {
80 throw new InvalidTypeException(
81 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '.
82 (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.',
83 );
84 }
85
86 if (!$locale && $translator instanceof LocaleAwareInterface) {
87 $locale = $translator->getLocale();
88 }
89
90 $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key);
91
92 return $result === $key ? $default : $result;
93 }
94
95 /**
96 * Returns raw translation message for a given key.
97 *
98 * @param string $key key to find
99 * @param string|null $locale current locale used if null
100 * @param string|null $default default value if translation returns the key
101 * @param TranslatorInterface $translator an optional translator to use
102 *
103 * @return string
104 */
105 public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null)
106 {
107 return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default);
108 }
109
110 /**
111 * Translate using translation string or callback available.
112 *
113 * @param TranslatorInterface $translator an optional translator to use
114 * @param string $key key to find
115 * @param array $parameters replacement parameters
116 * @param int|float|null $number number if plural
117 *
118 * @return string
119 */
120 public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string
121 {
122 $message = static::getTranslationMessageWith($translator, $key, null, $key);
123 if ($message instanceof Closure) {
124 return (string) $message(...array_values($parameters));
125 }
126
127 if ($number !== null) {
128 $parameters['%count%'] = $number;
129 }
130 if (isset($parameters['%count%'])) {
131 $parameters[':count'] = $parameters['%count%'];
132 }
133
134 return (string) $translator->trans($key, $parameters);
135 }
136
137 /**
138 * Translate using translation string or callback available.
139 *
140 * @param string $key key to find
141 * @param array $parameters replacement parameters
142 * @param string|int|float|null $number number if plural
143 * @param TranslatorInterface|null $translator an optional translator to use
144 * @param bool $altNumbers pass true to use alternative numbers
145 *
146 * @return string
147 */
148 public function translate(
149 string $key,
150 array $parameters = [],
151 string|int|float|null $number = null,
152 ?TranslatorInterface $translator = null,
153 bool $altNumbers = false,
154 ): string {
155 $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number);
156
157 if ($number !== null && $altNumbers) {
158 return str_replace((string) $number, $this->translateNumber((int) $number), $translation);
159 }
160
161 return $translation;
162 }
163
164 /**
165 * Returns the alternative number for a given integer if available in the current locale.
166 *
167 * @param int $number
168 *
169 * @return string
170 */
171 public function translateNumber(int $number): string
172 {
173 $translateKey = "alt_numbers.$number";
174 $symbol = $this->translate($translateKey);
175
176 if ($symbol !== $translateKey) {
177 return $symbol;
178 }
179
180 if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') {
181 $start = '';
182 foreach ([10000, 1000, 100] as $exp) {
183 $key = "alt_numbers_pow.$exp";
184 if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) {
185 $unit = floor($number / $exp);
186 $number -= $unit * $exp;
187 $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow;
188 }
189 }
190 $result = '';
191 while ($number) {
192 $chunk = $number % 100;
193 $result = $this->translate("alt_numbers.$chunk").$result;
194 $number = floor($number / 100);
195 }
196
197 return "$start$result";
198 }
199
200 if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') {
201 $result = '';
202 while ($number) {
203 $chunk = $number % 10;
204 $result = $this->translate("alt_numbers.$chunk").$result;
205 $number = floor($number / 10);
206 }
207
208 return $result;
209 }
210
211 return (string) $number;
212 }
213
214 /**
215 * Translate a time string from a locale to an other.
216 *
217 * @param string $timeString date/time/duration string to translate (may also contain English)
218 * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default)
219 * @param string|null $to output locale of the result returned (`"en"` by default)
220 * @param int $mode specify what to translate with options:
221 * - CarbonInterface::TRANSLATE_ALL (default)
222 * - CarbonInterface::TRANSLATE_MONTHS
223 * - CarbonInterface::TRANSLATE_DAYS
224 * - CarbonInterface::TRANSLATE_UNITS
225 * - CarbonInterface::TRANSLATE_MERIDIEM
226 * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS
227 *
228 * @return string
229 */
230 public static function translateTimeString(
231 string $timeString,
232 ?string $from = null,
233 ?string $to = null,
234 int $mode = CarbonInterface::TRANSLATE_ALL,
235 ): string {
236 // Fallback source and destination locales
237 $from = $from ?: static::getLocale();
238 $to = $to ?: CarbonInterface::DEFAULT_LOCALE;
239
240 if ($from === $to) {
241 return $timeString;
242 }
243
244 // Standardize apostrophe
245 $timeString = strtr($timeString, ['’' => "'"]);
246
247 $fromTranslations = [];
248 $toTranslations = [];
249
250 foreach (['from', 'to'] as $key) {
251 $language = $$key;
252 $translator = Translator::get($language);
253 $translations = $translator->getMessages();
254
255 if (!isset($translations[$language])) {
256 return $timeString;
257 }
258
259 $translationKey = $key.'Translations';
260 $messages = $translations[$language];
261 $months = $messages['months'] ?? [];
262 $weekdays = $messages['weekdays'] ?? [];
263 $meridiem = $messages['meridiem'] ?? ['AM', 'PM'];
264
265 if (isset($messages['ordinal_words'])) {
266 $timeString = self::replaceOrdinalWords(
267 $timeString,
268 $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words']
269 );
270 }
271
272 if ($key === 'from') {
273 foreach (['months', 'weekdays'] as $variable) {
274 $list = $messages[$variable.'_standalone'] ?? null;
275
276 if ($list) {
277 foreach ($$variable as $index => &$name) {
278 $name .= '|'.$list[$index];
279 }
280 }
281 }
282 }
283
284 $$translationKey = array_merge(
285 $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [],
286 $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [],
287 $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [],
288 $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [],
289 $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([
290 'diff_now',
291 'diff_today',
292 'diff_yesterday',
293 'diff_tomorrow',
294 'diff_before_yesterday',
295 'diff_after_tomorrow',
296 ], $messages, $key) : [],
297 $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([
298 'year',
299 'month',
300 'week',
301 'day',
302 'hour',
303 'minute',
304 'second',
305 ], $messages, $key) : [],
306 $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) {
307 if (\is_array($meridiem)) {
308 return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1];
309 }
310
311 return $meridiem($hour, 0, false);
312 }, range(0, 23)) : [],
313 );
314 }
315
316 return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) {
317 [$chunk] = $match;
318
319 foreach ($fromTranslations as $index => $word) {
320 if (preg_match("/^$word\$/iu", $chunk)) {
321 return $toTranslations[$index] ?? '';
322 }
323 }
324
325 return $chunk; // @codeCoverageIgnore
326 }, " $timeString "), 1, -1);
327 }
328
329 /**
330 * Translate a time string from the current locale (`$date->locale()`) to another one.
331 *
332 * @param string $timeString time string to translate
333 * @param string|null $to output locale of the result returned ("en" by default)
334 *
335 * @return string
336 */
337 public function translateTimeStringTo(string $timeString, ?string $to = null): string
338 {
339 return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to);
340 }
341
342 /**
343 * Get/set the locale for the current instance.
344 *
345 * @param string|null $locale
346 * @param string ...$fallbackLocales
347 *
348 * @return $this|string
349 */
350 public function locale(?string $locale = null, string ...$fallbackLocales): static|string
351 {
352 if ($locale === null) {
353 return $this->getTranslatorLocale();
354 }
355
356 if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) {
357 $translator = Translator::get($locale);
358
359 if (!empty($fallbackLocales)) {
360 $translator->setFallbackLocales($fallbackLocales);
361
362 foreach ($fallbackLocales as $fallbackLocale) {
363 $messages = Translator::get($fallbackLocale)->getMessages();
364
365 if (isset($messages[$fallbackLocale])) {
366 $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]);
367 }
368 }
369 }
370
371 $this->localTranslator = $translator;
372 }
373
374 return $this;
375 }
376
377 /**
378 * Get the current translator locale.
379 *
380 * @return string
381 */
382 public static function getLocale(): string
383 {
384 return static::getLocaleAwareTranslator()->getLocale();
385 }
386
387 /**
388 * Set the current translator locale and indicate if the source locale file exists.
389 * Pass 'auto' as locale to use the closest language to the current LC_TIME locale.
390 *
391 * @param string $locale locale ex. en
392 */
393 public static function setLocale(string $locale): void
394 {
395 static::getLocaleAwareTranslator()->setLocale($locale);
396 }
397
398 /**
399 * Set the fallback locale.
400 *
401 * @see https://symfony.com/doc/current/components/translation.html#fallback-locales
402 *
403 * @param string $locale
404 */
405 public static function setFallbackLocale(string $locale): void
406 {
407 $translator = static::getTranslator();
408
409 if (method_exists($translator, 'setFallbackLocales')) {
410 $translator->setFallbackLocales([$locale]);
411
412 if ($translator instanceof Translator) {
413 $preferredLocale = $translator->getLocale();
414 $fallbackMessages = [];
415 $preferredMessages = $translator->getMessages($preferredLocale);
416
417 foreach (Translator::get($locale)->getMessages()[$locale] ?? [] as $key => $value) {
418 if (
419 preg_match('/^(?:a_)?(.+)_(?:standalone|ago|from_now|before|after|short|min)$/', $key, $match)
420 && isset($preferredMessages[$match[1]])
421 ) {
422 continue;
423 }
424
425 $fallbackMessages[$key] = $value;
426 }
427
428 $translator->setMessages($preferredLocale, array_replace_recursive(
429 $translator->getMessages()[$locale] ?? [],
430 $fallbackMessages,
431 $preferredMessages,
432 ));
433 }
434 }
435 }
436
437 /**
438 * Get the fallback locale.
439 *
440 * @see https://symfony.com/doc/current/components/translation.html#fallback-locales
441 */
442 public static function getFallbackLocale(): ?string
443 {
444 $translator = static::getTranslator();
445
446 if (method_exists($translator, 'getFallbackLocales')) {
447 return $translator->getFallbackLocales()[0] ?? null;
448 }
449
450 return null;
451 }
452
453 /**
454 * Set the current locale to the given, execute the passed function, reset the locale to previous one,
455 * then return the result of the closure (or null if the closure was void).
456 *
457 * @param string $locale locale ex. en
458 * @param callable $func
459 *
460 * @return mixed
461 */
462 public static function executeWithLocale(string $locale, callable $func): mixed
463 {
464 $currentLocale = static::getLocale();
465 static::setLocale($locale);
466 $newLocale = static::getLocale();
467 $result = $func(
468 $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en'
469 ? false
470 : $newLocale,
471 static::getTranslator(),
472 );
473 static::setLocale($currentLocale);
474
475 return $result;
476 }
477
478 /**
479 * Returns true if the given locale is internally supported and has short-units support.
480 * Support is considered enabled if either year, day or hour has a short variant translated.
481 *
482 * @param string $locale locale ex. en
483 *
484 * @return bool
485 */
486 public static function localeHasShortUnits(string $locale): bool
487 {
488 return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) {
489 return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || (
490 ($y = static::translateWith($translator, 'd')) !== 'd' &&
491 $y !== static::translateWith($translator, 'day')
492 ) || (
493 ($y = static::translateWith($translator, 'h')) !== 'h' &&
494 $y !== static::translateWith($translator, 'hour')
495 );
496 });
497 }
498
499 /**
500 * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after).
501 * Support is considered enabled if the 4 sentences are translated in the given locale.
502 *
503 * @param string $locale locale ex. en
504 *
505 * @return bool
506 */
507 public static function localeHasDiffSyntax(string $locale): bool
508 {
509 return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) {
510 if (!$newLocale) {
511 return false;
512 }
513
514 foreach (['ago', 'from_now', 'before', 'after'] as $key) {
515 if ($translator instanceof TranslatorBagInterface &&
516 self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure
517 ) {
518 continue;
519 }
520
521 if ($translator->trans($key) === $key) {
522 return false;
523 }
524 }
525
526 return true;
527 });
528 }
529
530 /**
531 * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow).
532 * Support is considered enabled if the 3 words are translated in the given locale.
533 *
534 * @param string $locale locale ex. en
535 *
536 * @return bool
537 */
538 public static function localeHasDiffOneDayWords(string $locale): bool
539 {
540 return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) {
541 return $newLocale &&
542 $translator->trans('diff_now') !== 'diff_now' &&
543 $translator->trans('diff_yesterday') !== 'diff_yesterday' &&
544 $translator->trans('diff_tomorrow') !== 'diff_tomorrow';
545 });
546 }
547
548 /**
549 * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow).
550 * Support is considered enabled if the 2 words are translated in the given locale.
551 *
552 * @param string $locale locale ex. en
553 *
554 * @return bool
555 */
556 public static function localeHasDiffTwoDayWords(string $locale): bool
557 {
558 return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) {
559 return $newLocale &&
560 $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' &&
561 $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow';
562 });
563 }
564
565 /**
566 * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X).
567 * Support is considered enabled if the 4 sentences are translated in the given locale.
568 *
569 * @param string $locale locale ex. en
570 *
571 * @return bool
572 */
573 public static function localeHasPeriodSyntax($locale)
574 {
575 return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) {
576 return $newLocale &&
577 $translator->trans('period_recurrences') !== 'period_recurrences' &&
578 $translator->trans('period_interval') !== 'period_interval' &&
579 $translator->trans('period_start_date') !== 'period_start_date' &&
580 $translator->trans('period_end_date') !== 'period_end_date';
581 });
582 }
583
584 /**
585 * Returns the list of internally available locales and already loaded custom locales.
586 * (It will ignore custom translator dynamic loading.)
587 *
588 * @return array
589 */
590 public static function getAvailableLocales(): array
591 {
592 $translator = static::getLocaleAwareTranslator();
593
594 return $translator instanceof Translator
595 ? $translator->getAvailableLocales()
596 : [$translator->getLocale()];
597 }
598
599 /**
600 * Returns list of Language object for each available locale. This object allow you to get the ISO name, native
601 * name, region and variant of the locale.
602 *
603 * @return Language[]
604 */
605 public static function getAvailableLocalesInfo(): array
606 {
607 $languages = [];
608
609 foreach (static::getAvailableLocales() as $id) {
610 $languages[$id] = new Language($id);
611 }
612
613 return $languages;
614 }
615
616 /**
617 * Get the locale of a given translator.
618 *
619 * If null or omitted, current local translator is used.
620 * If no local translator is in use, current global translator is used.
621 */
622 protected function getTranslatorLocale($translator = null): ?string
623 {
624 if (\func_num_args() === 0) {
625 $translator = $this->getLocalTranslator();
626 }
627
628 $translator = static::getLocaleAwareTranslator($translator);
629
630 return $translator?->getLocale();
631 }
632
633 /**
634 * Throw an error if passed object is not LocaleAwareInterface.
635 *
636 * @param LocaleAwareInterface|null $translator
637 *
638 * @return LocaleAwareInterface|null
639 */
640 protected static function getLocaleAwareTranslator($translator = null)
641 {
642 if (\func_num_args() === 0) {
643 $translator = static::getTranslator();
644 }
645
646 if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) {
647 throw new NotLocaleAwareException($translator); // @codeCoverageIgnore
648 }
649
650 return $translator;
651 }
652
653 /**
654 * @param mixed $translator
655 * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue
656 *
657 * @return mixed
658 */
659 private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages')
660 {
661 return $translator instanceof TranslatorStrongTypeInterface
662 ? $translator->getFromCatalogue($catalogue, $id, $domain)
663 : $catalogue->get($id, $domain); // @codeCoverageIgnore
664 }
665
666 /**
667 * Return the word cleaned from its translation codes.
668 *
669 * @param string $word
670 *
671 * @return string
672 */
673 private static function cleanWordFromTranslationString($word)
674 {
675 $word = str_replace([':count', '%count', ':time'], '', $word);
676 $word = strtr($word, ['’' => "'"]);
677 $word = preg_replace(
678 '/\{(?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?}|[\[\]](?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?[\[\]]/',
679 '',
680 $word,
681 );
682
683 return trim($word);
684 }
685
686 /**
687 * Translate a list of words.
688 *
689 * @param string[] $keys keys to translate.
690 * @param string[] $messages messages bag handling translations.
691 * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern).
692 *
693 * @return string[]
694 */
695 private static function translateWordsByKeys($keys, $messages, $key): array
696 {
697 return array_map(function ($wordKey) use ($messages, $key) {
698 $message = $key === 'from' && isset($messages[$wordKey.'_regexp'])
699 ? $messages[$wordKey.'_regexp']
700 : ($messages[$wordKey] ?? null);
701
702 if (!$message) {
703 return '>>DO NOT REPLACE<<';
704 }
705
706 $parts = explode('|', $message);
707
708 return $key === 'to'
709 ? self::cleanWordFromTranslationString(end($parts))
710 : '(?:'.implode('|', array_map(static::cleanWordFromTranslationString(...), $parts)).')';
711 }, $keys);
712 }
713
714 /**
715 * Get an array of translations based on the current date.
716 *
717 * @param callable $translation
718 * @param int $length
719 * @param string $timeString
720 *
721 * @return string[]
722 */
723 private static function getTranslationArray($translation, $length, $timeString): array
724 {
725 $filler = '>>DO NOT REPLACE<<';
726
727 if (\is_array($translation)) {
728 return array_pad($translation, $length, $filler);
729 }
730
731 $list = [];
732 $date = static::now();
733
734 for ($i = 0; $i < $length; $i++) {
735 $list[] = $translation($date, $timeString, $i) ?? $filler;
736 }
737
738 return $list;
739 }
740
741 private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string
742 {
743 return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) {
744 return $ordinalWords[mb_strtolower($match[0])] ?? $match[0];
745 }, $timeString);
746 }
747 }