Completed
Push — master ( 408d1e...675fac )
by Vladimir
02:25
created

MarkdownEngine::blockFencedCodeComplete()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 12
nc 4
nop 1
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace allejo\stakx\Engines\Markdown;
4
5
use allejo\stakx\Engines\ParsingEngine;
6
use Highlight\Highlighter;
7
8
class MarkdownEngine extends \ParsedownExtra implements ParsingEngine
9
{
10
    protected $highlighter;
11
12
    public function __construct ()
13
    {
14
        parent::__construct();
15
16
        $this->highlighter = new Highlighter();
17
    }
18
19
    protected function blockHeader($line)
20
    {
21
        $Block = parent::blockHeader($line);
22
23
        // Create our unique ids by sanitizing the header content
24
        $id = strtolower($Block['element']['text']);
25
        $id = str_replace(' ', '-', $id);
26
        $id = preg_replace('/[^0-9a-zA-Z-_]/', '', $id);
27
        $id = preg_replace('/-+/', '-', $id);
28
29
        $Block['element']['attributes']['id'] = $id;
30
31
        return $Block;
32
    }
33
34
    public function blockFencedCodeComplete ($block)
35
    {
36
        // The class has a `language-` prefix, remove this to get the language
37
        if (isset($block['element']['text']['attributes']))
38
        {
39
            $cssClass = &$block['element']['text']['attributes']['class'];
40
            $language = substr($cssClass, 9);
41
            $cssClass = 'hljs ' . $cssClass;
42
43
            try
44
            {
45
                $highlighted = $this->highlighter->highlight($language, $block['element']['text']['text']);
46
                $block['element']['text']['text'] = $highlighted->value;
47
48
                // Only return the block if Highlighter knew the language and how to handle it.
49
                return $block;
50
            }
51
            // Exception thrown when language not supported
52
            catch (\DomainException $exception)
53
            {
54
                trigger_error("An unsupported language ($language) was detected in a code block", E_USER_WARNING);
55
            }
56
        }
57
58
        return parent::blockFencedCodeComplete($block);
59
    }
60
}