Skip to content

[String] Fix AsciiSlugger with emojis #48395

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions src/Symfony/Component/String/Slugger/AsciiSlugger.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,8 @@ public function slug(string $string, string $separator = '-', string $locale = n
$transliterator = (array) $this->createTransliterator($locale);
}

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

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

private function createEmojiTransliterator(?string $locale): ?EmojiTransliterator
{
if (\is_string($this->emoji)) {
$locale = $this->emoji;
} elseif (!$this->emoji) {
return null;
}

while (null !== $locale) {
try {
return EmojiTransliterator::create("emoji-$locale");
} catch (\IntlException) {
$locale = self::getParentLocale($locale);
}
}

return null;
}

private static function getParentLocale(?string $locale): ?string
{
if (!$locale) {
Expand Down
11 changes: 11 additions & 0 deletions src/Symfony/Component/String/Tests/Slugger/AsciiSluggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public function provideSlugTests(): iterable

/**
* @dataProvider provideSlugEmojiTests
*
* @requires extension intl
*/
public function testSlugEmoji(string $expected, string $string, ?string $locale, string|bool $emoji = true)
Expand Down Expand Up @@ -94,5 +95,15 @@ public function provideSlugEmojiTests(): iterable
'en',
'github',
];
yield [
'un-chat-qui-sourit-chat-noir-et-un-tete-de-lion-vont-au-parc-national',
'un 😺, 🐈‍⬛, et un 🦁 vont au 🏞️',
'fr_XX', // Fallback on parent locale
];
yield [
'un-et-un-vont-au',
'un 😺, 🐈‍⬛, et un 🦁 vont au 🏞️',
'undefined_locale', // Behaves the same as if emoji support is disabled
];
}
}