1 | <?php |
||
2 | |||
3 | namespace SymfonyBundles\Slugify; |
||
4 | |||
5 | class Slugify |
||
6 | { |
||
7 | /** |
||
8 | * @var array |
||
9 | */ |
||
10 | protected const MAP = [' ' => '-', '_' => '-']; |
||
11 | |||
12 | /** |
||
13 | * @var string |
||
14 | */ |
||
15 | protected const OPTIONS = 'Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC; [:Punctuation:] Remove; Lower();'; |
||
16 | |||
17 | /** |
||
18 | * @param string $source |
||
19 | * @param string $postfix |
||
20 | * |
||
21 | * @return string |
||
22 | * |
||
23 | * @throws \RuntimeException |
||
24 | * @throws \InvalidArgumentException |
||
25 | */ |
||
26 | 4 | public static function create(string $source, string $postfix = '.html'): string |
|
27 | { |
||
28 | 4 | $slug = \transliterator_transliterate(static::OPTIONS, $source); |
|
29 | |||
30 | 4 | if (false === $slug) { |
|
31 | throw new \InvalidArgumentException(sprintf('Incorrect source string "%s".', $source)); |
||
32 | } |
||
33 | |||
34 | 4 | $slug = \strtr($slug, static::MAP); |
|
35 | 4 | $slug = \preg_replace('#^\-|[^a-z0-9\-]|\-$#', '', $slug); |
|
36 | |||
37 | 4 | if (false === \is_string($slug)) { |
|
0 ignored issues
–
show
introduced
by
![]() |
|||
38 | throw new \RuntimeException(sprintf('Can not remove special chars from "%s".', $source)); |
||
39 | } |
||
40 | |||
41 | 4 | $slug = \preg_replace('#(\-+)#', '-', $slug); |
|
42 | |||
43 | 4 | if (false === \is_string($slug)) { |
|
44 | throw new \RuntimeException(sprintf('Can not remove "-" duplicates "%s".', $source)); |
||
45 | } |
||
46 | |||
47 | 4 | return $slug . $postfix; |
|
48 | } |
||
49 | } |
||
50 |