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