AsciiSlugger.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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\Intl\Transliterator\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. /**
  53. * @var string|null
  54. */
  55. private $defaultLocale;
  56. /**
  57. * @var \Closure|mixed[]
  58. */
  59. private $symbolsMap = [
  60. 'en' => ['@' => 'at', '&' => 'and'],
  61. ];
  62. /**
  63. * @var bool|string
  64. */
  65. private $emoji = false;
  66. /**
  67. * Cache of transliterators per locale.
  68. *
  69. * @var \Transliterator[]
  70. */
  71. private $transliterators = [];
  72. /**
  73. * @param mixed[]|\Closure $symbolsMap
  74. * @param string|null $defaultLocale
  75. */
  76. public function __construct($defaultLocale = null, $symbolsMap = null)
  77. {
  78. $this->defaultLocale = $defaultLocale;
  79. $this->symbolsMap = $symbolsMap ?? $this->symbolsMap;
  80. }
  81. /**
  82. * @return void
  83. * @param string $locale
  84. */
  85. public function setLocale($locale)
  86. {
  87. $this->defaultLocale = $locale;
  88. }
  89. public function getLocale()
  90. {
  91. return $this->defaultLocale;
  92. }
  93. /**
  94. * @param bool|string $emoji true will use the same locale,
  95. * false will disable emoji,
  96. * and a string to use a specific locale
  97. * @return $this
  98. */
  99. public function withEmoji($emoji = true)
  100. {
  101. if (false !== $emoji && !class_exists(EmojiTransliterator::class)) {
  102. throw new \LogicException(sprintf('You cannot use the "%s()" method as the "symfony/intl" package is not installed. Try running "composer require symfony/intl".', __METHOD__));
  103. }
  104. $new = clone $this;
  105. $new->emoji = $emoji;
  106. return $new;
  107. }
  108. /**
  109. * @param string $string
  110. * @param string $separator
  111. * @param string|null $locale
  112. */
  113. public function slug($string, $separator = '-', $locale = null)
  114. {
  115. $locale = $locale ?? $this->defaultLocale;
  116. $transliterator = [];
  117. if ($locale && ('de' === $locale || strncmp($locale, 'de_', strlen('de_')) === 0)) {
  118. // Use the shortcut for German in UnicodeString::ascii() if possible (faster and no requirement on intl)
  119. $transliterator = ['de-ASCII'];
  120. } elseif (\function_exists('transliterator_transliterate') && $locale) {
  121. $transliterator = (array) $this->createTransliterator($locale);
  122. }
  123. if ($emojiTransliterator = $this->createEmojiTransliterator($locale)) {
  124. $transliterator[] = $emojiTransliterator;
  125. }
  126. if ($this->symbolsMap instanceof \Closure) {
  127. // If the symbols map is passed as a closure, there is no need to fallback to the parent locale
  128. // as the closure can just provide substitutions for all locales of interest.
  129. $symbolsMap = $this->symbolsMap;
  130. array_unshift($transliterator, static function ($s) use ($symbolsMap, $locale) {
  131. return $symbolsMap($s, $locale);
  132. });
  133. }
  134. $unicodeString = (new UnicodeString($string))->ascii($transliterator);
  135. if (\is_array($this->symbolsMap)) {
  136. $map = null;
  137. if (isset($this->symbolsMap[$locale])) {
  138. $map = $this->symbolsMap[$locale];
  139. } else {
  140. $parent = self::getParentLocale($locale);
  141. if ($parent && isset($this->symbolsMap[$parent])) {
  142. $map = $this->symbolsMap[$parent];
  143. }
  144. }
  145. if ($map) {
  146. foreach ($map as $char => $replace) {
  147. $unicodeString = $unicodeString->replace($char, ' '.$replace.' ');
  148. }
  149. }
  150. }
  151. return $unicodeString
  152. ->replaceMatches('/[^A-Za-z0-9]++/', $separator)
  153. ->trim($separator)
  154. ;
  155. }
  156. /**
  157. * @param string $locale
  158. */
  159. private function createTransliterator($locale)
  160. {
  161. if (\array_key_exists($locale, $this->transliterators)) {
  162. return $this->transliterators[$locale];
  163. }
  164. // Exact locale supported, cache and return
  165. if ($id = self::LOCALE_TO_TRANSLITERATOR_ID[$locale] ?? null) {
  166. return $this->transliterators[$locale] = \Transliterator::create($id.'/BGN') ?? \Transliterator::create($id);
  167. }
  168. // Locale not supported and no parent, fallback to any-latin
  169. if (!$parent = self::getParentLocale($locale)) {
  170. return $this->transliterators[$locale] = null;
  171. }
  172. // Try to use the parent locale (ie. try "de" for "de_AT") and cache both locales
  173. if ($id = self::LOCALE_TO_TRANSLITERATOR_ID[$parent] ?? null) {
  174. $transliterator = \Transliterator::create($id.'/BGN') ?? \Transliterator::create($id);
  175. }
  176. return $this->transliterators[$locale] = $this->transliterators[$parent] = $transliterator ?? null;
  177. }
  178. /**
  179. * @param string|null $locale
  180. */
  181. private function createEmojiTransliterator($locale)
  182. {
  183. if (\is_string($this->emoji)) {
  184. $locale = $this->emoji;
  185. } elseif (!$this->emoji) {
  186. return null;
  187. }
  188. while (null !== $locale) {
  189. try {
  190. return EmojiTransliterator::create("emoji-$locale");
  191. } catch (\IntlException $exception) {
  192. $locale = self::getParentLocale($locale);
  193. }
  194. }
  195. return null;
  196. }
  197. /**
  198. * @param string|null $locale
  199. */
  200. private static function getParentLocale($locale)
  201. {
  202. if (!$locale) {
  203. return null;
  204. }
  205. if (false === $str = strrchr($locale, '_')) {
  206. // no parent locale
  207. return null;
  208. }
  209. return substr($locale, 0, -\strlen($str));
  210. }
  211. }