Skip to content

Commit 1457026

Browse files
fancywebnicolas-grekas
authored andcommitted
[String] Fix AsciiSlugger with emojis
1 parent ba9fd9b commit 1457026

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

Slugger/AsciiSlugger.php

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -113,10 +113,8 @@ public function slug(string $string, string $separator = '-', string $locale = n
113113
$transliterator = (array) $this->createTransliterator($locale);
114114
}
115115

116-
if (\is_string($this->emoji)) {
117-
$transliterator[] = EmojiTransliterator::create("emoji-{$this->emoji}");
118-
} elseif ($this->emoji && null !== $locale) {
119-
$transliterator[] = EmojiTransliterator::create("emoji-{$locale}");
116+
if ($emojiTransliterator = $this->createEmojiTransliterator($locale)) {
117+
$transliterator[] = $emojiTransliterator;
120118
}
121119

122120
if ($this->symbolsMap instanceof \Closure) {
@@ -177,6 +175,25 @@ private function createTransliterator(string $locale): ?\Transliterator
177175
return $this->transliterators[$locale] = $this->transliterators[$parent] = $transliterator ?? null;
178176
}
179177

178+
private function createEmojiTransliterator(?string $locale): ?EmojiTransliterator
179+
{
180+
if (\is_string($this->emoji)) {
181+
$locale = $this->emoji;
182+
} elseif (!$this->emoji) {
183+
return null;
184+
}
185+
186+
while (null !== $locale) {
187+
try {
188+
return EmojiTransliterator::create("emoji-$locale");
189+
} catch (\IntlException) {
190+
$locale = self::getParentLocale($locale);
191+
}
192+
}
193+
194+
return null;
195+
}
196+
180197
private static function getParentLocale(?string $locale): ?string
181198
{
182199
if (!$locale) {

Tests/Slugger/AsciiSluggerTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ public function provideSlugTests(): iterable
4949

5050
/**
5151
* @dataProvider provideSlugEmojiTests
52+
*
5253
* @requires extension intl
5354
*/
5455
public function testSlugEmoji(string $expected, string $string, ?string $locale, string|bool $emoji = true)
@@ -94,5 +95,15 @@ public function provideSlugEmojiTests(): iterable
9495
'en',
9596
'github',
9697
];
98+
yield [
99+
'un-chat-qui-sourit-chat-noir-et-un-tete-de-lion-vont-au-parc-national',
100+
'un 😺, 🐈‍⬛, et un 🦁 vont au 🏞️',
101+
'fr_XX', // Fallback on parent locale
102+
];
103+
yield [
104+
'un-et-un-vont-au',
105+
'un 😺, 🐈‍⬛, et un 🦁 vont au 🏞️',
106+
'undefined_locale', // Behaves the same as if emoji support is disabled
107+
];
97108
}
98109
}

0 commit comments

Comments
 (0)