|
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\Bundle\MarkdownBundle; |
|
13
|
|
|
|
|
14
|
|
|
use Symplify\PHP7_Sculpin\Core\Converter\SourceConverterContext; |
|
15
|
|
|
use Symplify\PHP7_Sculpin\Core\Converter\ConverterInterface; |
|
16
|
|
|
use Symplify\PHP7_Sculpin\Core\Converter\ParserInterface; |
|
17
|
|
|
|
|
18
|
|
|
final class MarkdownConverter implements ConverterInterface |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* @var ParserInterface |
|
22
|
|
|
*/ |
|
23
|
|
|
private $markdown; |
|
24
|
|
|
|
|
25
|
|
|
public function __construct(ParserInterface $markdown) |
|
26
|
|
|
{ |
|
27
|
|
|
$this->markdown = $markdown; |
|
28
|
|
|
$this->markdown->header_id_func = [$this, 'generateHeaderId']; |
|
|
|
|
|
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* {@inheritdoc} |
|
33
|
|
|
*/ |
|
34
|
|
|
public function convert(SourceConverterContext $converterContext) |
|
35
|
|
|
{ |
|
36
|
|
|
$converterContext->setContent( |
|
37
|
|
|
$this->markdown->transform( |
|
38
|
|
|
$converterContext->content() |
|
39
|
|
|
) |
|
40
|
|
|
); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* This method is called to generate an id="" attribute for a header. |
|
45
|
|
|
*/ |
|
46
|
|
|
public function generateHeaderId(string $headerText) : string |
|
47
|
|
|
{ |
|
48
|
|
|
// $headerText is completely raw markdown input. We need to strip it |
|
49
|
|
|
// from all markup, because we are only interested in the actual 'text' |
|
50
|
|
|
// part of it. |
|
51
|
|
|
|
|
52
|
|
|
// Step 1: Remove html tags. |
|
53
|
|
|
$result = strip_tags($headerText); |
|
54
|
|
|
|
|
55
|
|
|
// Step 2: Remove all markdown links. To do this, we simply remove |
|
56
|
|
|
// everything between ( and ) if the ( occurs right after a ]. |
|
57
|
|
|
$result = preg_replace('% |
|
58
|
|
|
(?<= \\]) # Look behind to find ] |
|
59
|
|
|
( |
|
60
|
|
|
\\( # match ( |
|
61
|
|
|
[^\\)]* # match everything except ) |
|
62
|
|
|
\\) # match ) |
|
63
|
|
|
) |
|
64
|
|
|
|
|
65
|
|
|
%x', '', $result); |
|
66
|
|
|
|
|
67
|
|
|
// Step 3: Convert spaces to dashes, and remove unwanted special |
|
68
|
|
|
// characters. |
|
69
|
|
|
$map = [ |
|
70
|
|
|
' ' => '-', |
|
71
|
|
|
'(' => '', |
|
72
|
|
|
')' => '', |
|
73
|
|
|
'[' => '', |
|
74
|
|
|
']' => '', |
|
75
|
|
|
]; |
|
76
|
|
|
|
|
77
|
|
|
return rawurlencode(strtolower( |
|
78
|
|
|
strtr($result, $map) |
|
79
|
|
|
)); |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|
If you access a property on an interface, you most likely code against a concrete implementation of the interface.
Available Fixes
Adding an additional type check:
Changing the type hint: