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

MarkdownConverter   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 2
dl 0
loc 69
ccs 0
cts 35
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A convert() 0 8 1
B generateHeaderId() 0 35 1
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