Completed
Push — latest ( da8ccb...1f5488 )
by Colin
15s queued 12s
created

SlugNormalizer::setConfiguration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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