[String] Add locale-sensitive map for slugging symbols

This commit is contained in:
Laurent Masforné 2020-04-15 09:16:33 +02:00 committed by Nicolas Grekas
parent 0bec08f0d8
commit 1331584fa1
2 changed files with 29 additions and 5 deletions

View File

@ -51,6 +51,9 @@ class AsciiSlugger implements SluggerInterface, LocaleAwareInterface
];
private $defaultLocale;
private $symbolsMap = [
'en' => ['@' => 'at', '&' => 'and'],
];
/**
* Cache of transliterators per locale.
@ -59,9 +62,10 @@ class AsciiSlugger implements SluggerInterface, LocaleAwareInterface
*/
private $transliterators = [];
public function __construct(string $defaultLocale = null)
public function __construct(string $defaultLocale = null, array $symbolsMap = null)
{
$this->defaultLocale = $defaultLocale;
$this->symbolsMap = $symbolsMap ?? $this->symbolsMap;
}
/**
@ -95,10 +99,15 @@ class AsciiSlugger implements SluggerInterface, LocaleAwareInterface
$transliterator = (array) $this->createTransliterator($locale);
}
return (new UnicodeString($string))
->ascii($transliterator)
->replace('@', $separator.'at'.$separator)
->replace('&', $separator.'and'.$separator)
$unicodeString = (new UnicodeString($string))->ascii($transliterator);
if (isset($this->symbolsMap[$locale])) {
foreach ($this->symbolsMap[$locale] as $char => $replace) {
$unicodeString = $unicodeString->replace($char, ' '.$replace.' ');
}
}
return $unicodeString
->replaceMatches('/[^A-Za-z0-9]++/', $separator)
->trim($separator)
;

View File

@ -49,4 +49,19 @@ class SluggerTest extends TestCase
$this->assertSame('hello-world', (string) $slugger->slug('hello world'));
$this->assertSame('hello_world', (string) $slugger->slug('hello world', '_'));
}
public function testSlugCharReplacementLocaleConstruct()
{
$slugger = new AsciiSlugger('fr', ['fr' => ['&' => 'et', '@' => 'chez']]);
$slug = (string) $slugger->slug('toi & moi avec cette adresse slug@test.fr', '_');
$this->assertSame('toi_et_moi_avec_cette_adresse_slug_chez_test_fr', $slug);
}
public function testSlugCharReplacementLocaleMethod()
{
$slugger = new AsciiSlugger(null, ['es' => ['&' => 'y', '@' => 'en senal']]);
$slug = (string) $slugger->slug('yo & tu a esta dirección slug@test.es', '_', 'es');
$this->assertSame('yo_y_tu_a_esta_direccion_slug_en_senal_test_es', $slug);
}
}