Completed
Pull Request — master (#10)
by Tomáš
04:48 queued 01:50
created

MarkdownConverter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
3
/*
4
 * This file is a part of Sculpin.
5
 *
6
 * (c) Dragonfly Development Inc.
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 Symplify\PHP7_Sculpin\MarkdownBundle;
13
14
use Michelf\MarkdownExtra;
15
use Symplify\PHP7_Sculpin\Converter\SourceConverterContext;
16
use Symplify\PHP7_Sculpin\Converter\ConverterInterface;
17
18
final class MarkdownConverter implements ConverterInterface
19
{
20
    /**
21
     * @var string
22
     */
23
    const NAME = 'markdown';
24
25
    /**
26
     * @var MarkdownExtra
27
     */
28
    private $markdown;
29
30
    public function __construct(MarkdownExtra $markdown)
31
    {
32
        $this->markdown = $markdown;
33
        $this->markdown->header_id_func = [$this, 'generateHeaderId'];
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function convert(SourceConverterContext $converterContext)
40
    {
41
        $converterContext->setContent(
42
            $this->markdown->transform(
43
                $converterContext->content()
44
            )
45
        );
46
    }
47
48
    /**
49
     * This method is called to generate an id="" attribute for a header.
50
     */
51
    public function generateHeaderId(string $headerText) : string
52
    {
53
        // $headerText is completely raw markdown input. We need to strip it
54
        // from all markup, because we are only interested in the actual 'text'
55
        // part of it.
56
57
        // Step 1: Remove html tags.
58
        $result = strip_tags($headerText);
59
60
        // Step 2: Remove all markdown links. To do this, we simply remove
61
        // everything between ( and ) if the ( occurs right after a ].
62
        $result = preg_replace('%
63
            (?<= \\]) # Look behind to find ]
64
            (
65
                \\(     # match (
66
                [^\\)]* # match everything except )
67
                \\)     # match )
68
            )
69
70
            %x', '', $result);
71
72
        // Step 3: Convert spaces to dashes, and remove unwanted special
73
        // characters.
74
        $map = [
75
            ' ' => '-',
76
            '(' => '',
77
            ')' => '',
78
            '[' => '',
79
            ']' => '',
80
        ];
81
82
        return rawurlencode(strtolower(
83
            strtr($result, $map)
84
        ));
85
    }
86
}
87