feature #36456 [String] Add locale-sensitive map for slugging symbols (lmasforne)

This PR was merged into the 5.1-dev branch.

Discussion
----------

[String] Add locale-sensitive map for slugging symbols

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| Tickets       | Fix #36383
| License       | MIT

By default chars '@' and '&' are respectively replaced by 'at' and 'and' (so limited by enlgish language).
I had an $options arguments to 'slug' method to replace chars with your own logic.

Commits
-------

1331584fa1 [String] Add locale-sensitive map for slugging symbols
This commit is contained in:
Fabien Potencier 2020-04-24 10:33:33 +02:00
commit 260dea0387
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);
}
}