Completed
Pull Request — master (#41)
by Vladimir
02:46
created

MarkdownEngine   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 53
ccs 23
cts 23
cp 1
rs 10
c 0
b 0
f 0
wmc 5
lcom 1
cbo 2

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A blockHeader() 0 14 1
B blockFencedCodeComplete() 0 26 3
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 3
    public function __construct ()
13
    {
14 3
        parent::__construct();
15
16 3
        $this->highlighter = new Highlighter();
17 3
    }
18
19 3
    protected function blockHeader($line)
20
    {
21 3
        $Block = parent::blockHeader($line);
22
23
        // Create our unique ids by sanitizing the header content
24 3
        $id = strtolower($Block['element']['text']);
25 3
        $id = str_replace(' ', '-', $id);
26 3
        $id = preg_replace('/[^0-9a-zA-Z-_]/', '', $id);
27 3
        $id = preg_replace('/-+/', '-', $id);
28
29 3
        $Block['element']['attributes']['id'] = $id;
30
31 3
        return $Block;
32
    }
33
34 3
    public function blockFencedCodeComplete ($block)
35
    {
36
        // The class has a `language-` prefix, remove this to get the language
37 3
        if (isset($block['element']['text']['attributes']))
38
        {
39 2
            $cssClass = &$block['element']['text']['attributes']['class'];
40 2
            $language = substr($cssClass, 9);
41 2
            $cssClass = 'hljs ' . $cssClass;
42
43
            try
44
            {
45 2
                $highlighted = $this->highlighter->highlight($language, $block['element']['text']['text']);
46 1
                $block['element']['text']['text'] = $highlighted->value;
47
48
                // Only return the block if Highlighter knew the language and how to handle it.
49 1
                return $block;
50
            }
51
            // Exception thrown when language not supported
52 1
            catch (\DomainException $exception)
53
            {
54 1
                trigger_error("An unsupported language ($language) was detected in a code block", E_USER_WARNING);
55
            }
56
        }
57
58 1
        return parent::blockFencedCodeComplete($block);
59
    }
60
}