Test Failed
Push — develop ( 32ca41...230235 )
by Brent
04:59
created

MarkdownParser::parse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Pageon\Lib\Markdown;
4
5
use Closure;
6
use League\CommonMark\CommonMarkConverter;
7
use League\CommonMark\Environment;
8
use League\CommonMark\Inline\Element\Image;
9
use League\CommonMark\Inline\Element\Link;
10
use Pageon\Html\Image\ImageFactory;
11
12
/**
13
 *  - Code block classes.
14
 *  - External links with `target="_blank"`.
15
 *  - Images are parsed with with the image factory
16
 */
17
class MarkdownParser
18
{
19
    /** @var \Closure[] */
20
    private static $extensions;
21
22
    /** @var \League\CommonMark\CommonMarkConverter */
23
    private $converter;
24
25
    public static function extension(Closure $closure): void
26
    {
27
        self::$extensions[] = $closure;
28
    }
29
30
    public function __construct(ImageFactory $imageFactory)
31
    {
32
        $environment = Environment::createCommonMarkEnvironment();
33
34
        foreach (self::$extensions as $closure) {
35
            $environment = $closure($environment);
36
        }
37
38
        $environment
39
            ->addInlineRenderer(Link::class, new ExternalLinkRenderer())
40
            ->addInlineRenderer(Image::class, new ImageRenderer($imageFactory));
41
42
        $this->converter = new CommonMarkConverter([], $environment);
43
    }
44
45
    public function parse(string $markdown): string
46
    {
47
        return $this->converter->convertToHtml($markdown);
48
    }
49
}
50