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

UniqueSlugNormalizer::normalize()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 9
c 3
b 1
f 0
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.9666
cc 3
nc 2
nop 2
crap 3
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 3057
    public function __construct(TextNormalizerInterface $innerNormalizer)
25
    {
26 3057
        $this->innerNormalizer = $innerNormalizer;
27 3057
    }
28
29 2946
    public function clearHistory(): void
30
    {
31 2946
        $this->alreadyUsed = [];
32 2946
    }
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