1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @copyright 2017 Vladimir Jimenez |
5
|
|
|
* @license https://github.com/allejo/stakx/blob/master/LICENSE.md MIT |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace allejo\stakx\Engines\Markdown; |
9
|
|
|
|
10
|
|
|
use allejo\stakx\Engines\ParsingEngine; |
11
|
|
|
use Highlight\Highlighter; |
12
|
|
|
|
13
|
|
|
class MarkdownEngine extends \ParsedownExtra implements ParsingEngine |
14
|
|
|
{ |
15
|
|
|
protected $highlighter; |
16
|
|
|
|
17
|
4 |
|
public function __construct() |
18
|
|
|
{ |
19
|
4 |
|
parent::__construct(); |
20
|
|
|
|
21
|
4 |
|
$this->highlighter = new Highlighter(); |
22
|
4 |
|
} |
23
|
|
|
|
24
|
3 |
|
protected function blockHeader($line) |
25
|
|
|
{ |
26
|
3 |
|
$Block = parent::blockHeader($line); |
27
|
|
|
|
28
|
|
|
// Create our unique ids by sanitizing the header content |
29
|
3 |
|
$id = strtolower($Block['element']['text']); |
30
|
3 |
|
$id = str_replace(' ', '-', $id); |
31
|
3 |
|
$id = preg_replace('/[^0-9a-zA-Z-_]/', '', $id); |
32
|
3 |
|
$id = preg_replace('/-+/', '-', $id); |
33
|
|
|
|
34
|
3 |
|
$Block['element']['attributes']['id'] = $id; |
35
|
|
|
|
36
|
3 |
|
return $Block; |
37
|
|
|
} |
38
|
|
|
|
39
|
3 |
|
public function blockFencedCodeComplete($block) |
|
|
|
|
40
|
|
|
{ |
41
|
|
|
// The class has a `language-` prefix, remove this to get the language |
42
|
3 |
|
if (isset($block['element']['text']['attributes'])) |
43
|
|
|
{ |
44
|
2 |
|
$cssClass = &$block['element']['text']['attributes']['class']; |
45
|
2 |
|
$language = substr($cssClass, 9); |
46
|
2 |
|
$cssClass = 'hljs ' . $cssClass; |
47
|
|
|
|
48
|
|
|
try |
49
|
|
|
{ |
50
|
2 |
|
$highlighted = $this->highlighter->highlight($language, $block['element']['text']['text']); |
51
|
1 |
|
$block['element']['text']['text'] = $highlighted->value; |
52
|
|
|
|
53
|
|
|
// Only return the block if Highlighter knew the language and how to handle it. |
54
|
1 |
|
return $block; |
55
|
|
|
} |
56
|
|
|
// Exception thrown when language not supported |
57
|
1 |
|
catch (\DomainException $exception) |
58
|
|
|
{ |
59
|
1 |
|
trigger_error("An unsupported language ($language) was detected in a code block", E_USER_WARNING); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
return parent::blockFencedCodeComplete($block); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@return
annotation as described here.