Passed
Push — master ( 19b461...296556 )
by Caen
03:53 queued 14s
created

ConvertsMarkdownToPlainText::trimWhitespace()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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