Passed
Push — master ( 4c0cb7...cfbeec )
by Caen
03:53 queued 15s
created

ConvertsMarkdownToPlainText   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 108
Duplicated Lines 0 %

Importance

Changes 57
Bugs 2 Features 0
Metric Value
eloc 57
c 57
b 2
f 0
dl 0
loc 108
rs 10
wmc 14

6 Methods

Rating   Name   Duplication   Size   Complexity  
A applyStringTransformations() 0 11 2
A applyRegexTransformations() 0 28 2
A removeBlockquotes() 0 12 3
A __construct() 0 3 1
A execute() 0 3 1
A removeTables() 0 12 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Hyde\Framework\Actions;
6
7
use function array_keys;
8
use function array_values;
9
use function explode;
10
use function implode;
11
use function preg_replace;
12
use function rtrim;
13
use function str_replace;
14
use function substr;
15
16
/**
17
 * Converts Markdown to plain text.
18
 *
19
 * @see \Hyde\Framework\Testing\Feature\Actions\ConvertsMarkdownToPlainTextTest
20
 *
21
 * @experimental This class is experimental and does not have a stable API yet.
22
 *
23
 * @internal This class is experimental and should not be used outside HydePHP.
24
 */
25
class ConvertsMarkdownToPlainText
26
{
27
    protected const ATX_HEADERS = ['/^(\n)?\s{0,}#{1,6}\s+| {0,}(\n)?\s{0,}#{0,} {0,}(\n)?\s{0,}$/m' => '$1$2$3'];
28
    protected const SETEXT_HEADERS = ['/\n={2,}/' => "\n"];
29
    protected const HORIZONTAL_RULES = ['/^(-\s*?|\*\s*?|_\s*?){3,}\s*/m' => ''];
30
    protected const HTML_TAGS = ['/<[^>]*>/' => ''];
31
    protected const CODE_BLOCKS = ['/(`{3,})(.*?)\1/m' => '$2'];
32
    protected const FENCED_CODEBLOCKS = ['/`{3}.*\n/' => '', '/`{3}/' => ''];
33
    protected const TILDE_FENCED_CODEBLOCKS = ['/~{3}.*\n/' => '', '/~{3}/' => ''];
34
    protected const INLINE_CODE = ['/`(.+?)`/' => '$1'];
35
    protected const IMAGES = ['/\!\[(.*?)\][\[\(].*?[\]\)]/' => '$1'];
36
    protected const INLINE_LINKS = ['/\[(.*?)\][\[\(].*?[\]\)]/' => '$1'];
37
    protected const REFERENCE_LINKS = ['/^\s{1,2}\[(.*?)\]: (\S+)( ".*?")?\s*$/' => ''];
38
    protected const STRIKETHROUGH = ['/~~/' => ''];
39
    protected const BLOCKQUOTES = ['/^\s{0,3}>\s?/' => ''];
40
    protected const FOOTNOTES = ['/\[\^.+?\](\: .*?$)?/' => ''];
41
    protected const EMPHASIS = ['/([\*_]{1,3})(\S.*?\S{0,1})\1/' => '$2'];
42
43
    /** Emphasis (repeat the line to remove double emphasis) */
44
    protected const DOUBLE_EMPHASIS = self::EMPHASIS;
45
46
    /** Replace two or more newlines with exactly two */
47
    protected const REPEATED_NEWLINES = ['/\n{2,}/' => "\n\n"];
48
49
    protected string $markdown;
50
51
    public function __construct(string $markdown)
52
    {
53
        $this->markdown = $markdown;
54
    }
55
56
    /**
57
     * Regex based on https://github.com/stiang/remove-markdown, licensed under MIT.
58
     */
59
    public function execute(): string
60
    {
61
        return $this->applyStringTransformations($this->applyRegexTransformations($this->markdown));
62
    }
63
64
    protected function applyRegexTransformations(string $markdown): string
65
    {
66
        /** @var array<array-key, array<string, string>> $patterns */
67
        $patterns = [
68
            static::ATX_HEADERS,
69
            static::SETEXT_HEADERS,
70
            static::HORIZONTAL_RULES,
71
            static::HTML_TAGS,
72
            static::CODE_BLOCKS,
73
            static::FENCED_CODEBLOCKS,
74
            static::TILDE_FENCED_CODEBLOCKS,
75
            static::INLINE_CODE,
76
            static::IMAGES,
77
            static::INLINE_LINKS,
78
            static::REFERENCE_LINKS,
79
            static::STRIKETHROUGH,
80
            static::BLOCKQUOTES,
81
            static::FOOTNOTES,
82
            static::EMPHASIS,
83
            static::DOUBLE_EMPHASIS,
84
            static::REPEATED_NEWLINES,
85
        ];
86
87
        foreach ($patterns as $pattern) {
88
            $markdown = preg_replace(array_keys($pattern), array_values($pattern), $markdown) ?? $markdown;
89
        }
90
91
        return $markdown;
92
    }
93
94
    protected function applyStringTransformations(string $markdown): string
95
    {
96
        $lines = explode("\n", $markdown);
97
        foreach ($lines as $line => $contents) {
98
            $contents = $this->removeTables($contents);
99
            $contents = $this->removeBlockquotes($contents);
100
101
            $lines[$line] = $contents;
102
        }
103
104
        return implode("\n", $lines);
105
    }
106
107
    protected function removeTables(string $contents): string
108
    {
109
        // Remove dividers
110
        if (str_starts_with($contents, '|--') && str_ends_with($contents, '--|')) {
111
            $contents = str_replace(['|', '-'], ['', ''], $contents);
112
        }
113
        // Remove cells
114
        if (str_starts_with($contents, '| ') && str_ends_with($contents, '|')) {
115
            $contents = rtrim(str_replace(['| ', ' | ', ' |'], ['', '', ''], $contents), ' ');
116
        }
117
118
        return $contents;
119
    }
120
121
    protected function removeBlockquotes(string $contents): string
122
    {
123
        // Remove blockquotes
124
        if (str_starts_with($contents, '> ')) {
125
            $contents = substr($contents, 2);
126
        }
127
        // Remove multiline blockquotes
128
        if (str_starts_with($contents, '>')) {
129
            $contents = substr($contents, 1);
130
        }
131
132
        return $contents;
133
    }
134
}
135