UniqueSlugNormalizer   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 5
eloc 14
c 3
b 1
f 0
dl 0
loc 39
ccs 15
cts 15
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A normalize() 0 17 3
A __construct() 0 3 1
A clearHistory() 0 3 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
// phpcs:disable Squiz.Strings.DoubleQuoteUsage.ContainsVar
17
final class UniqueSlugNormalizer implements UniqueSlugNormalizerInterface
18
{
19
    /** @var TextNormalizerInterface */
20
    private $innerNormalizer;
21
    /** @var array<string, bool> */
22
    private $alreadyUsed = [];
23
24 3099
    public function __construct(TextNormalizerInterface $innerNormalizer)
25
    {
26 3099
        $this->innerNormalizer = $innerNormalizer;
27 3099
    }
28
29 2988
    public function clearHistory(): void
30
    {
31 2988
        $this->alreadyUsed = [];
32 2988
    }
33
34
    /**
35
     * {@inheritDoc}
36
     *
37
     * @psalm-allow-private-mutation
38
     */
39 117
    public function normalize(string $text, array $context = []): string
40
    {
41 117
        $normalized = $this->innerNormalizer->normalize($text, $context);
42
43
        // If it's not unique, add an incremental number to the end until we get a unique version
44 117
        if (\array_key_exists($normalized, $this->alreadyUsed)) {
45 24
            $suffix = 0;
46
            do {
47 24
                ++$suffix;
48 24
            } while (\array_key_exists("$normalized-$suffix", $this->alreadyUsed));
49
50 24
            $normalized = "$normalized-$suffix";
51
        }
52
53 117
        $this->alreadyUsed[$normalized] = true;
54
55 117
        return $normalized;
56
    }
57
}
58