Completed
Push — master ( fb47ed...8a4ab4 )
by Colin
01:43
created

DefaultSlugGenerator::generateSlug()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
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\Extension\HeadingPermalink\SlugGenerator;
15
16
use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock;
17
use League\CommonMark\Extension\CommonMark\Node\Inline\HtmlInline;
18
use League\CommonMark\Node\Node;
19
use League\CommonMark\Node\StringContainerHelper;
20
21
/**
22
 * Creates URL-friendly strings based on the inner contents of a node and its descendants
23
 */
24
final class DefaultSlugGenerator implements SlugGeneratorInterface
25
{
26 72
    public function generateSlug(Node $node): string
27
    {
28 72
        $childText = StringContainerHelper::getChildText($node, [HtmlBlock::class, HtmlInline::class]);
29
30 72
        return self::slugifyText($childText);
31
    }
32
33
    /**
34
     * @internal This method is only public to facilitate internal testing. DO NOT RELY ON ITS EXISTENCE OR BEHAVIOR!
35
     */
36 156
    public static function slugifyText(string $text): string
37
    {
38
        // Trim whitespace
39 156
        $slug = \trim($text);
40
        // Convert to lowercase
41 156
        $slug = \mb_strtolower($slug);
42
        // Try replacing whitespace with a dash
43 156
        $slug = \preg_replace('/\s+/u', '-', $slug) ?? $slug;
44
        // Try removing characters other than letters, numbers, and marks.
45 156
        $slug = \preg_replace('/[^\p{L}\p{Nd}\p{Nl}\p{M}-]+/u', '', $slug) ?? $slug;
46
47 156
        return $slug;
48
    }
49
}
50