| 148 |
lars |
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 <colinodell@gmail.com>
|
|
|
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 |
private TextNormalizerInterface $innerNormalizer;
|
|
|
20 |
/** @var array<string, bool> */
|
|
|
21 |
private array $alreadyUsed = [];
|
|
|
22 |
|
|
|
23 |
public function __construct(TextNormalizerInterface $innerNormalizer)
|
|
|
24 |
{
|
|
|
25 |
$this->innerNormalizer = $innerNormalizer;
|
|
|
26 |
}
|
|
|
27 |
|
|
|
28 |
public function clearHistory(): void
|
|
|
29 |
{
|
|
|
30 |
$this->alreadyUsed = [];
|
|
|
31 |
}
|
|
|
32 |
|
|
|
33 |
/**
|
|
|
34 |
* {@inheritDoc}
|
|
|
35 |
*
|
|
|
36 |
* @psalm-allow-private-mutation
|
|
|
37 |
*/
|
|
|
38 |
public function normalize(string $text, array $context = []): string
|
|
|
39 |
{
|
|
|
40 |
$normalized = $this->innerNormalizer->normalize($text, $context);
|
|
|
41 |
|
|
|
42 |
// If it's not unique, add an incremental number to the end until we get a unique version
|
|
|
43 |
if (\array_key_exists($normalized, $this->alreadyUsed)) {
|
|
|
44 |
$suffix = 0;
|
|
|
45 |
do {
|
|
|
46 |
++$suffix;
|
|
|
47 |
} while (\array_key_exists("$normalized-$suffix", $this->alreadyUsed));
|
|
|
48 |
|
|
|
49 |
$normalized = "$normalized-$suffix";
|
|
|
50 |
}
|
|
|
51 |
|
|
|
52 |
$this->alreadyUsed[$normalized] = true;
|
|
|
53 |
|
|
|
54 |
return $normalized;
|
|
|
55 |
}
|
|
|
56 |
}
|