1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the league/commonmark package. |
7
|
|
|
* |
8
|
|
|
* (c) Colin O'Dell <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace League\CommonMark\Normalizer; |
15
|
|
|
|
16
|
|
|
use League\CommonMark\Configuration\ConfigurationAwareInterface; |
17
|
|
|
use League\CommonMark\Configuration\ConfigurationInterface; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Creates URL-friendly strings based on the given string input |
21
|
|
|
*/ |
22
|
|
|
final class SlugNormalizer implements TextNormalizerInterface, ConfigurationAwareInterface |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* @var int |
26
|
|
|
* |
27
|
|
|
* @psalm-allow-private-mutation |
28
|
|
|
*/ |
29
|
|
|
private $defaultMaxLength = 255; |
30
|
|
|
|
31
|
3054 |
|
public function setConfiguration(ConfigurationInterface $configuration): void |
32
|
|
|
{ |
33
|
3054 |
|
$this->defaultMaxLength = $configuration->get('slug_normalizer/max_length'); |
34
|
3054 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* {@inheritdoc} |
38
|
|
|
* |
39
|
|
|
* @psalm-immutable |
40
|
|
|
*/ |
41
|
222 |
|
public function normalize(string $text, array $context = []): string |
42
|
|
|
{ |
43
|
|
|
// Add any requested prefix |
44
|
222 |
|
$slug = ($context['prefix'] ?? '') . $text; |
45
|
|
|
// Trim whitespace |
46
|
222 |
|
$slug = \trim($slug); |
47
|
|
|
// Convert to lowercase |
48
|
222 |
|
$slug = \mb_strtolower($slug); |
49
|
|
|
// Try replacing whitespace with a dash |
50
|
222 |
|
$slug = \preg_replace('/\s+/u', '-', $slug) ?? $slug; |
51
|
|
|
// Try removing characters other than letters, numbers, and marks. |
52
|
222 |
|
$slug = \preg_replace('/[^\p{L}\p{Nd}\p{Nl}\p{M}-]+/u', '', $slug) ?? $slug; |
53
|
|
|
// Trim to requested length if given |
54
|
222 |
|
if ($length = $context['length'] ?? $this->defaultMaxLength) { |
55
|
219 |
|
$slug = \mb_substr($slug, 0, $length); |
56
|
|
|
} |
57
|
|
|
|
58
|
222 |
|
return $slug; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|