Completed
Push — master ( a1590e...0af16c )
by Vladimir
02:39
created

MarkdownEngine::blockFencedCodeComplete()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

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