Passed
Push — master ( 7b7005...55ec05 )
by Brent
02:29
created

Parsedown::element()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 3
nop 1
dl 0
loc 13
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Brendt\Stitcher\Lib;
4
5
use Brendt\Stitcher\Parser\ImageParser;
6
use \Parsedown as LibParsedown;
7
8
/**
9
 * This class adds two extensions to the Parsedown library:
10
 *
11
 *  - Code block classes.
12
 *  - External links with `target="_blank"`.
13
 *  - Images are parsed with with the image parser
14
 *
15
 * Class Parsedown
16
 * @package Brendt\Stitcher\Lib
17
 */
18
class Parsedown extends LibParsedown
19
{
20
    private $imageParser;
21
22
    public function __construct(ImageParser $imageParser) {
23
        $this->imageParser = $imageParser;
24
    }
25
26
    protected function element(array $Element) {
27
        $markup = parent::element($Element);
28
29
        if (isset($Element['attributes']['href']) && strpos($Element['attributes']['href'], '*') === 0) {
30
            return $this->parseBlankLink($Element);
31
        }
32
33
        if (isset($Element['attributes']['srcset'])) {
34
            return $this->parseImageWithSrcset($Element);
35
        }
36
37
        return $markup;
38
    }
39
40
    protected function blockFencedCode($Line) {
41
        $block = parent::blockFencedCode($Line);
42
43
        if (isset($block['element']['text']['attributes']['class'])) {
44
            $block['element']['attributes']['class'] = $block['element']['text']['attributes']['class'];
45
        }
46
47
        return $block;
48
    }
49
50
    protected function inlineImage($Excerpt) {
51
        $Inline = parent::inlineImage($Excerpt);
52
53
        if (!isset($Inline['element']['attributes']['src'])) {
54
            return $Inline;
55
        }
56
57
        $src = $Inline['element']['attributes']['src'];
58
59
        $responsiveImage = $this->imageParser->parse($src);
60
61
        $Inline['element']['attributes']['srcset'] = $responsiveImage['srcset'] ?? null;
62
        $Inline['element']['attributes']['sizes'] = $responsiveImage['sizes'] ?? null;
63
        $Inline['element']['attributes']['alt'] = $responsiveImage['alt'] ?? null;
64
65
        return $Inline;
66
    }
67
68
    private function parseBlankLink($Element): string {
69
        $href = $Element['attributes']['href'];
70
        $href = substr($href, 1);
71
72
        return "<a href='$href' target='_blank' rel='noreferrer noopener'>{$Element['text']}</a>";
73
    }
74
75
    private function parseImageWithSrcset($Element): string {
76
        $src = $Element['attributes']['src'];
77
        $srcset = $Element['attributes']['srcset'];
78
        $sizes = $Element['attributes']['sizes'];
79
        $alt = $Element['attributes']['alt'];
80
81
        return "<img src=\"{$src}\" srcset=\"{$srcset}\" sizes=\"{$sizes}\" alt=\"{$alt}\" />";
82
    }
83
}
84