AsciiSlugger.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\String\Slugger;
  11. use Symfony\Component\Emoji\EmojiTransliterator;
  12. use Symfony\Component\String\AbstractUnicodeString;
  13. use Symfony\Component\String\UnicodeString;
  14. use Symfony\Contracts\Translation\LocaleAwareInterface;
  15. if (!interface_exists(LocaleAwareInterface::class)) {
  16. throw new \LogicException('You cannot use the "Symfony\Component\String\Slugger\AsciiSlugger" as the "symfony/translation-contracts" package is not installed. Try running "composer require symfony/translation-contracts".');
  17. }
  18. /**
  19. * @author Titouan Galopin <galopintitouan@gmail.com>
  20. */
  21. class AsciiSlugger implements SluggerInterface, LocaleAwareInterface
  22. {
  23. private const LOCALE_TO_TRANSLITERATOR_ID = [
  24. 'am' => 'Amharic-Latin',
  25. 'ar' => 'Arabic-Latin',
  26. 'az' => 'Azerbaijani-Latin',
  27. 'be' => 'Belarusian-Latin',
  28. 'bg' => 'Bulgarian-Latin',
  29. 'bn' => 'Bengali-Latin',
  30. 'de' => 'de-ASCII',
  31. 'el' => 'Greek-Latin',
  32. 'fa' => 'Persian-Latin',
  33. 'he' => 'Hebrew-Latin',
  34. 'hy' => 'Armenian-Latin',
  35. 'ka' => 'Georgian-Latin',
  36. 'kk' => 'Kazakh-Latin',
  37. 'ky' => 'Kirghiz-Latin',
  38. 'ko' => 'Korean-Latin',
  39. 'mk' => 'Macedonian-Latin',
  40. 'mn' => 'Mongolian-Latin',
  41. 'or' => 'Oriya-Latin',
  42. 'ps' => 'Pashto-Latin',
  43. 'ru' => 'Russian-Latin',
  44. 'sr' => 'Serbian-Latin',
  45. 'sr_Cyrl' => 'Serbian-Latin',
  46. 'th' => 'Thai-Latin',
  47. 'tk' => 'Turkmen-Latin',
  48. 'uk' => 'Ukrainian-Latin',
  49. 'uz' => 'Uzbek-Latin',
  50. 'zh' => 'Han-Latin',
  51. ];
  52. private \Closure|array $symbolsMap = [
  53. 'en' => ['@' => 'at', '&' => 'and'],
  54. ];
  55. private bool|string $emoji = false;
  56. /**
  57. * Cache of transliterators per locale.
  58. *
  59. * @var \Transliterator[]
  60. */
  61. private array $transliterators = [];
  62. public function __construct(
  63. private ?string $defaultLocale = null,
  64. array|\Closure|null $symbolsMap = null,
  65. ) {
  66. $this->symbolsMap = $symbolsMap ?? $this->symbolsMap;
  67. }
  68. public function setLocale(string $locale): void
  69. {
  70. $this->defaultLocale = $locale;
  71. }
  72. public function getLocale(): string
  73. {
  74. return $this->defaultLocale;
  75. }
  76. /**
  77. * @param bool|string $emoji true will use the same locale,
  78. * false will disable emoji,
  79. * and a string to use a specific locale
  80. */
  81. public function withEmoji(bool|string $emoji = true): static
  82. {
  83. if (false !== $emoji && !class_exists(EmojiTransliterator::class)) {
  84. throw new \LogicException(\sprintf('You cannot use the "%s()" method as the "symfony/emoji" package is not installed. Try running "composer require symfony/emoji".', __METHOD__));
  85. }
  86. $new = clone $this;
  87. $new->emoji = $emoji;
  88. return $new;
  89. }
  90. public function slug(string $string, string $separator = '-', ?string $locale = null): AbstractUnicodeString
  91. {
  92. $locale ??= $this->defaultLocale;
  93. $transliterator = [];
  94. if ($locale && ('de' === $locale || str_starts_with($locale, 'de_'))) {
  95. // Use the shortcut for German in UnicodeString::ascii() if possible (faster and no requirement on intl)
  96. $transliterator = ['de-ASCII'];
  97. } elseif (\function_exists('transliterator_transliterate') && $locale) {
  98. $transliterator = (array) $this->createTransliterator($locale);
  99. }
  100. if ($emojiTransliterator = $this->createEmojiTransliterator($locale)) {
  101. $transliterator[] = $emojiTransliterator;
  102. }
  103. if ($this->symbolsMap instanceof \Closure) {
  104. // If the symbols map is passed as a closure, there is no need to fallback to the parent locale
  105. // as the closure can just provide substitutions for all locales of interest.
  106. $symbolsMap = $this->symbolsMap;
  107. array_unshift($transliterator, static fn ($s) => $symbolsMap($s, $locale));
  108. }
  109. $unicodeString = (new UnicodeString($string))->ascii($transliterator);
  110. if (\is_array($this->symbolsMap)) {
  111. $map = null;
  112. if (isset($this->symbolsMap[$locale])) {
  113. $map = $this->symbolsMap[$locale];
  114. } else {
  115. $parent = self::getParentLocale($locale);
  116. if ($parent && isset($this->symbolsMap[$parent])) {
  117. $map = $this->symbolsMap[$parent];
  118. }
  119. }
  120. if ($map) {
  121. foreach ($map as $char => $replace) {
  122. $unicodeString = $unicodeString->replace($char, ' '.$replace.' ');
  123. }
  124. }
  125. }
  126. return $unicodeString
  127. ->replaceMatches('/[^A-Za-z0-9]++/', $separator)
  128. ->trim($separator)
  129. ;
  130. }
  131. private function createTransliterator(string $locale): ?\Transliterator
  132. {
  133. if (\array_key_exists($locale, $this->transliterators)) {
  134. return $this->transliterators[$locale];
  135. }
  136. // Exact locale supported, cache and return
  137. if ($id = self::LOCALE_TO_TRANSLITERATOR_ID[$locale] ?? null) {
  138. return $this->transliterators[$locale] = \Transliterator::create($id.'/BGN') ?? \Transliterator::create($id);
  139. }
  140. // Locale not supported and no parent, fallback to any-latin
  141. if (!$parent = self::getParentLocale($locale)) {
  142. return $this->transliterators[$locale] = null;
  143. }
  144. // Try to use the parent locale (ie. try "de" for "de_AT") and cache both locales
  145. if ($id = self::LOCALE_TO_TRANSLITERATOR_ID[$parent] ?? null) {
  146. $transliterator = \Transliterator::create($id.'/BGN') ?? \Transliterator::create($id);
  147. }
  148. return $this->transliterators[$locale] = $this->transliterators[$parent] = $transliterator ?? null;
  149. }
  150. private function createEmojiTransliterator(?string $locale): ?EmojiTransliterator
  151. {
  152. if (\is_string($this->emoji)) {
  153. $locale = $this->emoji;
  154. } elseif (!$this->emoji) {
  155. return null;
  156. }
  157. while (null !== $locale) {
  158. try {
  159. return EmojiTransliterator::create("emoji-$locale");
  160. } catch (\IntlException) {
  161. $locale = self::getParentLocale($locale);
  162. }
  163. }
  164. return null;
  165. }
  166. private static function getParentLocale(?string $locale): ?string
  167. {
  168. if (!$locale) {
  169. return null;
  170. }
  171. if (false === $str = strrchr($locale, '_')) {
  172. // no parent locale
  173. return null;
  174. }
  175. return substr($locale, 0, -\strlen($str));
  176. }
  177. }