Completed
Push — master ( 1572d2...f75b0d )
by Jitendra
20s
created

SpanElementParser   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 86
rs 10
c 0
b 0
f 0
wmc 14

6 Methods

Rating   Name   Duplication   Size   Complexity  
A anchors() 0 9 2
A emails() 0 6 1
A spans() 0 26 6
A images() 0 8 3
A links() 0 8 1
A parse() 0 5 1
1
<?php
2
3
namespace Ahc;
4
5
class SpanElementParser
6
{
7
    use HtmlHelper;
8
9
    const RE_URL       = '~<(https?:[\/]{2}[^\s]+?)>~';
10
    const RE_EMAIL     = '~<(\S+?@\S+?)>~';
11
    const RE_MD_IMG    = '~!\[(.+?)\]\s*\((.+?)\s*(".+?")?\)~';
12
    const RE_MD_URL    = '~\[(.+?)\]\s*\((.+?)\s*(".+?")?\)~';
13
    const RE_MD_FONT   = '!(\*{1,2}|_{1,2}|`|~~)(.+?)\\1!';
14
15
    public function parse($markup)
16
    {
17
        return $this->spans(
18
            $this->anchors(
19
                $this->links($markup)
20
            )
21
        );
22
    }
23
24
    protected function links($markup)
25
    {
26
        $markup = $this->emails($markup);
27
28
        return \preg_replace(
29
            static::RE_URL,
30
            '<a href="$1">$1</a>',
31
            $markup
32
        );
33
    }
34
35
    protected function emails($markup)
36
    {
37
        return \preg_replace(
38
            static::RE_EMAIL,
39
            '<a href="mailto:$1">$1</a>',
40
            $markup
41
        );
42
    }
43
44
    protected function anchors($markup)
45
    {
46
        $markup = $this->images($markup);
47
48
        return \preg_replace_callback(static::RE_MD_URL, function ($a) {
49
            $title = isset($a[3]) ? " title={$a[3]} " : '';
50
51
            return "<a href=\"{$a[2]}\"{$title}>{$a[1]}</a>";
52
        }, $markup);
53
    }
54
55
    protected function images($markup)
56
    {
57
        return \preg_replace_callback(static::RE_MD_IMG, function ($img) {
58
            $title = isset($img[3]) ? " title={$img[3]} " : '';
59
            $alt   = $img[1] ? " alt=\"{$img[1]}\" " : '';
60
61
            return "<img src=\"{$img[2]}\"{$title}{$alt}/>";
62
        }, $markup);
63
    }
64
65
    protected function spans($markup)
66
    {
67
        // em/code/strong/del
68
        return \preg_replace_callback(static::RE_MD_FONT, function ($em) {
69
            switch (\substr($em[1], 0, 2)) {
70
                case  '**':
71
                case '__':
72
                    $tag = 'strong';
73
                    break;
74
75
                case '~~':
76
                    $tag = 'del';
77
                    break;
78
79
                case $em[1] === '*':
80
                case $em[1] === '_':
81
                    $tag = 'em';
82
                    break;
83
84
                default:
85
                    $tag = 'code';
86
                    $em[2] = $this->escape($em[2]);
87
            }
88
89
            return "<$tag>{$em[2]}</$tag>";
90
        }, $markup);
91
    }
92
}
93