-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSlugRule.php
More file actions
66 lines (56 loc) · 2.09 KB
/
Copy pathSlugRule.php
File metadata and controls
66 lines (56 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
declare(strict_types=1);
namespace KaririCode\Sanitizer\Rule\String;
use KaririCode\Sanitizer\Contract\SanitizationContext;
use KaririCode\Sanitizer\Contract\SanitizationRule;
/**
* Converts a string to a URL-safe slug.
*
* Transliterates common accented characters, lowercases,
* replaces non-alphanumeric with hyphens, collapses multiple hyphens.
*
* @author Walmir Silva <walmir.silva@kariricode.org>
*
* @since 3.1.0 ARFA 1.3
*/
final readonly class SlugRule implements SanitizationRule
{
#[\Override]
public function sanitize(mixed $value, SanitizationContext $context): mixed
{
if (! \is_string($value)) {
return $value;
}
$separatorRaw = $context->getParameter('separator', '-');
$separator = \is_string($separatorRaw) ? $separatorRaw : '-';
// Transliterate common accented characters
$slug = $this->transliterate($value);
$slug = mb_strtolower($slug, 'UTF-8');
$slug = preg_replace('/[^a-z0-9]+/', $separator, $slug) ?? $slug;
$slug = trim($slug, $separator);
return $slug;
}
#[\Override]
public function getName(): string
{
return 'string.slug';
}
private function transliterate(string $value): string
{
$map = [
'á' => 'a', 'à' => 'a', 'ã' => 'a', 'â' => 'a', 'ä' => 'a',
'é' => 'e', 'è' => 'e', 'ê' => 'e', 'ë' => 'e',
'í' => 'i', 'ì' => 'i', 'î' => 'i', 'ï' => 'i',
'ó' => 'o', 'ò' => 'o', 'õ' => 'o', 'ô' => 'o', 'ö' => 'o',
'ú' => 'u', 'ù' => 'u', 'û' => 'u', 'ü' => 'u',
'ç' => 'c', 'ñ' => 'n', 'ß' => 'ss',
'Á' => 'A', 'À' => 'A', 'Ã' => 'A', 'Â' => 'A', 'Ä' => 'A',
'É' => 'E', 'È' => 'E', 'Ê' => 'E', 'Ë' => 'E',
'Í' => 'I', 'Ì' => 'I', 'Î' => 'I', 'Ï' => 'I',
'Ó' => 'O', 'Ò' => 'O', 'Õ' => 'O', 'Ô' => 'O', 'Ö' => 'O',
'Ú' => 'U', 'Ù' => 'U', 'Û' => 'U', 'Ü' => 'U',
'Ç' => 'C', 'Ñ' => 'N',
];
return strtr($value, $map);
}
}