Completed
Push — 1.5 ( 6f6b16...137879 )
by Colin
02:25
created

DefaultSlugGenerator::getChildText()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 9.5222
c 0
b 0
f 0
cc 5
nc 3
nop 1
crap 5
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace League\CommonMark\Extension\HeadingPermalink\SlugGenerator;
13
14
use League\CommonMark\Inline\Element\Code;
15
use League\CommonMark\Inline\Element\Text;
16
use League\CommonMark\Node\Node;
17
18
/**
19
 * Creates URL-friendly strings based on the inner contents of a node and its descendants
20
 */
21
final class DefaultSlugGenerator implements SlugGeneratorInterface
22
{
23 72
    public function generateSlug(Node $node): string
24
    {
25 72
        $childText = $this->getChildText($node);
0 ignored issues
show
Deprecated Code introduced by
The method League\CommonMark\Extens...nerator::getChildText() has been deprecated with message: Use StringContainerHelper::getChildText() in 2.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
26
27 72
        return self::slugifyText($childText);
28
    }
29
30
    /**
31
     * @internal This method is only public to facilitate internal testing. DO NOT RELY ON ITS EXISTENCE OR BEHAVIOR!
32
     */
33 156
    public static function slugifyText(string $text): string
34
    {
35
        // Trim whitespace
36 156
        $slug = \trim($text);
37
        // Convert to lowercase
38 156
        $slug = \mb_strtolower($slug);
39
        // Try replacing whitespace with a dash
40 156
        $slug = \preg_replace('/\s+/u', '-', $slug) ?? $slug;
41
        // Try removing characters other than letters, numbers, and marks.
42 156
        $slug = \preg_replace('/[^\p{L}\p{Nd}\p{Nl}\p{M}-]+/u', '', $slug) ?? $slug;
43
44 156
        return $slug;
45
    }
46
47
    /**
48
     * @deprecated Use StringContainerHelper::getChildText() in 2.0
49
     */
50 72
    private function getChildText(Node $node): string
51
    {
52 72
        $text = '';
53
54 72
        $walker = $node->walker();
55 72
        while ($event = $walker->next()) {
56 72
            if ($event->isEntering() && (($child = $event->getNode()) instanceof Text || $child instanceof Code)) {
57 69
                $text .= $child->getContent();
58
            }
59
        }
60
61 72
        return $text;
62
    }
63
}
64