Passed
Push — renovate/vimeo-psalm-5.x ( 3efdba )
by
unknown
03:10
created

RegexHelper::isEscapable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the league/commonmark package.
7
 *
8
 * (c) Colin O'Dell <[email protected]>
9
 *
10
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
11
 *  - (c) John MacFarlane
12
 *
13
 * For the full copyright and license information, please view the LICENSE
14
 * file that was distributed with this source code.
15
 */
16
17
namespace League\CommonMark\Util;
18
19
use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock;
20
21
/**
22
 * Provides regular expressions and utilities for parsing Markdown
23
 *
24
 * All of the PARTIAL_ regex constants assume that they'll be used in case-insensitive searches
25
 * All other complete regexes provided by this class (either via constants or methods) will have case-insensitivity enabled.
26
 *
27
 * @phpcs:disable Generic.Strings.UnnecessaryStringConcat.Found
28
 *
29
 * @psalm-immutable
30
 */
31
final class RegexHelper
32
{
33
    // Partial regular expressions (wrap with `/` on each side and add the case-insensitive `i` flag before use)
34
    public const PARTIAL_ENTITY                = '&(?:#x[a-f0-9]{1,6}|#[0-9]{1,7}|[a-z][a-z0-9]{1,31});';
35
    public const PARTIAL_ESCAPABLE             = '[!"#$%&\'()*+,.\/:;<=>?@[\\\\\]^_`{|}~-]';
36
    public const PARTIAL_ESCAPED_CHAR          = '\\\\' . self::PARTIAL_ESCAPABLE;
37
    public const PARTIAL_IN_DOUBLE_QUOTES      = '"(' . self::PARTIAL_ESCAPED_CHAR . '|[^"\x00])*"';
38
    public const PARTIAL_IN_SINGLE_QUOTES      = '\'(' . self::PARTIAL_ESCAPED_CHAR . '|[^\'\x00])*\'';
39
    public const PARTIAL_IN_PARENS             = '\\((' . self::PARTIAL_ESCAPED_CHAR . '|[^)\x00])*\\)';
40
    public const PARTIAL_REG_CHAR              = '[^\\\\()\x00-\x20]';
41
    public const PARTIAL_IN_PARENS_NOSP        = '\((' . self::PARTIAL_REG_CHAR . '|' . self::PARTIAL_ESCAPED_CHAR . '|\\\\)*\)';
42
    public const PARTIAL_TAGNAME               = '[a-z][a-z0-9-]*';
43
    public const PARTIAL_BLOCKTAGNAME          = '(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)';
44
    public const PARTIAL_ATTRIBUTENAME         = '[a-z_:][a-z0-9:._-]*';
45
    public const PARTIAL_UNQUOTEDVALUE         = '[^"\'=<>`\x00-\x20]+';
46
    public const PARTIAL_SINGLEQUOTEDVALUE     = '\'[^\']*\'';
47
    public const PARTIAL_DOUBLEQUOTEDVALUE     = '"[^"]*"';
48
    public const PARTIAL_ATTRIBUTEVALUE        = '(?:' . self::PARTIAL_UNQUOTEDVALUE . '|' . self::PARTIAL_SINGLEQUOTEDVALUE . '|' . self::PARTIAL_DOUBLEQUOTEDVALUE . ')';
49
    public const PARTIAL_ATTRIBUTEVALUESPEC    = '(?:' . '\s*=' . '\s*' . self::PARTIAL_ATTRIBUTEVALUE . ')';
50
    public const PARTIAL_ATTRIBUTE             = '(?:' . '\s+' . self::PARTIAL_ATTRIBUTENAME . self::PARTIAL_ATTRIBUTEVALUESPEC . '?)';
51
    public const PARTIAL_OPENTAG               = '<' . self::PARTIAL_TAGNAME . self::PARTIAL_ATTRIBUTE . '*' . '\s*\/?>';
52
    public const PARTIAL_CLOSETAG              = '<\/' . self::PARTIAL_TAGNAME . '\s*[>]';
53
    public const PARTIAL_OPENBLOCKTAG          = '<' . self::PARTIAL_BLOCKTAGNAME . self::PARTIAL_ATTRIBUTE . '*' . '\s*\/?>';
54
    public const PARTIAL_CLOSEBLOCKTAG         = '<\/' . self::PARTIAL_BLOCKTAGNAME . '\s*[>]';
55
    public const PARTIAL_HTMLCOMMENT           = '<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->';
56
    public const PARTIAL_PROCESSINGINSTRUCTION = '[<][?][\s\S]*?[?][>]';
57
    public const PARTIAL_DECLARATION           = '<![A-Z]+' . '\s+[^>]*>';
58
    public const PARTIAL_CDATA                 = '<!\[CDATA\[[\s\S]*?]\]>';
59
    public const PARTIAL_HTMLTAG               = '(?:' . self::PARTIAL_OPENTAG . '|' . self::PARTIAL_CLOSETAG . '|' . self::PARTIAL_HTMLCOMMENT . '|' .
60
        self::PARTIAL_PROCESSINGINSTRUCTION . '|' . self::PARTIAL_DECLARATION . '|' . self::PARTIAL_CDATA . ')';
61
    public const PARTIAL_HTMLBLOCKOPEN         = '<(?:' . self::PARTIAL_BLOCKTAGNAME . '(?:[\s\/>]|$)' . '|' .
62
        '\/' . self::PARTIAL_BLOCKTAGNAME . '(?:[\s>]|$)' . '|' . '[?!])';
63
    public const PARTIAL_LINK_TITLE            = '^(?:"(' . self::PARTIAL_ESCAPED_CHAR . '|[^"\x00])*"' .
64
        '|' . '\'(' . self::PARTIAL_ESCAPED_CHAR . '|[^\'\x00])*\'' .
65
        '|' . '\((' . self::PARTIAL_ESCAPED_CHAR . '|[^()\x00])*\))';
66
67
    public const REGEX_PUNCTUATION        = '/^[\x{2000}-\x{206F}\x{2E00}-\x{2E7F}\p{Pc}\p{Pd}\p{Pe}\p{Pf}\p{Pi}\p{Po}\p{Ps}\\\\\'!"#\$%&\(\)\*\+,\-\.\\/:;<=>\?@\[\]\^_`\{\|\}~]/u';
68
    public const REGEX_UNSAFE_PROTOCOL    = '/^javascript:|vbscript:|file:|data:/i';
69
    public const REGEX_SAFE_DATA_PROTOCOL = '/^data:image\/(?:png|gif|jpeg|webp)/i';
70
    public const REGEX_NON_SPACE          = '/[^ \t\f\v\r\n]/';
71
72
    public const REGEX_WHITESPACE_CHAR         = '/^[ \t\n\x0b\x0c\x0d]/';
73
    public const REGEX_UNICODE_WHITESPACE_CHAR = '/^\pZ|\s/u';
74
    public const REGEX_THEMATIC_BREAK          = '/^(?:\*[ \t]*){3,}$|^(?:_[ \t]*){3,}$|^(?:-[ \t]*){3,}$/';
75
    public const REGEX_LINK_DESTINATION_BRACES = '/^(?:<(?:[^<>\\n\\\\\\x00]|\\\\.)*>)/';
76
77
    /**
78
     * @psalm-pure
79
     */
80 92
    public static function isEscapable(string $character): bool
81
    {
82 92
        return \preg_match('/' . self::PARTIAL_ESCAPABLE . '/', $character) === 1;
83
    }
84
85
    /**
86
     * @psalm-pure
87
     */
88 2144
    public static function isLetter(?string $character): bool
89
    {
90 2144
        if ($character === null) {
91
            return false;
92
        }
93
94 2144
        return \preg_match('/[\pL]/u', $character) === 1;
95
    }
96
97
    /**
98
     * Attempt to match a regex in string s at offset offset
99
     *
100
     * @return int|null Index of match, or null
101
     *
102
     * @psalm-pure
103
     */
104 1326
    public static function matchAt(string $regex, string $string, int $offset = 0): ?int
105
    {
106 1326
        $matches = [];
107 1326
        $string  = \mb_substr($string, $offset, null, 'utf-8');
108 1326
        if (! \preg_match($regex, $string, $matches, \PREG_OFFSET_CAPTURE)) {
109 1250
            return null;
110
        }
111
112
        // PREG_OFFSET_CAPTURE always returns the byte offset, not the char offset, which is annoying
113 240
        $charPos = \mb_strlen(\mb_strcut($string, 0, $matches[0][1], 'utf-8'), 'utf-8');
114
115 240
        return $offset + $charPos;
116
    }
117
118
    /**
119
     * Functional wrapper around preg_match_all which only returns the first set of matches
120
     *
121
     * @return string[]|null
122
     *
123
     * @psalm-pure
124
     */
125 1324
    public static function matchFirst(string $pattern, string $subject, int $offset = 0): ?array
126
    {
127 1324
        if ($offset !== 0) {
128 28
            $subject = \substr($subject, $offset);
129
        }
130
131 1324
        \preg_match_all($pattern, $subject, $matches, \PREG_SET_ORDER);
132
133 1324
        if ($matches === []) {
134 1024
            return null;
135
        }
136
137 462
        return $matches[0] ?: null;
138
    }
139
140
    /**
141
     * Replace backslash escapes with literal characters
142
     *
143
     * @psalm-pure
144
     */
145 452
    public static function unescape(string $string): string
146
    {
147 452
        $allEscapedChar = '/\\\\(' . self::PARTIAL_ESCAPABLE . ')/';
148
149 452
        $escaped = \preg_replace($allEscapedChar, '$1', $string);
150
        \assert(\is_string($escaped));
151
152 452
        return \preg_replace_callback('/' . self::PARTIAL_ENTITY . '/i', static fn ($e) => Html5EntityDecoder::decode($e[0]), $escaped);
153
    }
154
155
    /**
156
     * @internal
157
     *
158
     * @param int $type HTML block type
159
     *
160
     * @psalm-param HtmlBlock::TYPE_* $type
161
     *
162
     * @phpstan-param HtmlBlock::TYPE_* $type
163
     *
164
     * @throws \InvalidArgumentException if an invalid type is given
165
     *
166
     * @psalm-pure
167
     */
168 220
    public static function getHtmlBlockOpenRegex(int $type): string
169
    {
170
        switch ($type) {
171
            case HtmlBlock::TYPE_1_CODE_CONTAINER:
172 220
                return '/^<(?:script|pre|textarea|style)(?:\s|>|$)/i';
173
            case HtmlBlock::TYPE_2_COMMENT:
174 206
                return '/^<!--/';
175
            case HtmlBlock::TYPE_3:
176 196
                return '/^<[?]/';
177
            case HtmlBlock::TYPE_4:
178 194
                return '/^<![A-Z]/i';
179
            case HtmlBlock::TYPE_5_CDATA:
180 192
                return '/^<!\[CDATA\[/i';
181
            case HtmlBlock::TYPE_6_BLOCK_ELEMENT:
182 188
                return '%^<[/]?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[123456]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|[/]?[>]|$)%i';
183
            case HtmlBlock::TYPE_7_MISC_ELEMENT:
184 128
                return '/^(?:' . self::PARTIAL_OPENTAG . '|' . self::PARTIAL_CLOSETAG . ')\\s*$/i';
185
            default:
186 2
                throw new \InvalidArgumentException('Invalid HTML block type');
187
        }
188
    }
189
190
    /**
191
     * @internal
192
     *
193
     * @param int $type HTML block type
194
     *
195
     * @psalm-param HtmlBlock::TYPE_* $type
196
     *
197
     * @phpstan-param HtmlBlock::TYPE_* $type
198
     *
199
     * @throws \InvalidArgumentException if an invalid type is given
200
     *
201
     * @psalm-pure
202
     */
203 28
    public static function getHtmlBlockCloseRegex(int $type): string
204
    {
205
        switch ($type) {
206
            case HtmlBlock::TYPE_1_CODE_CONTAINER:
207 28
                return '%<\/(?:script|pre|textarea|style)>%i';
208
            case HtmlBlock::TYPE_2_COMMENT:
209 10
                return '/-->/';
210
            case HtmlBlock::TYPE_3:
211 2
                return '/\?>/';
212
            case HtmlBlock::TYPE_4:
213 2
                return '/>/';
214
            case HtmlBlock::TYPE_5_CDATA:
215 2
                return '/\]\]>/';
216
            default:
217 6
                throw new \InvalidArgumentException('Invalid HTML block type');
218
        }
219
    }
220
221
    /**
222
     * @psalm-pure
223
     */
224 6
    public static function isLinkPotentiallyUnsafe(string $url): bool
225
    {
226 6
        return \preg_match(self::REGEX_UNSAFE_PROTOCOL, $url) !== 0 && \preg_match(self::REGEX_SAFE_DATA_PROTOCOL, $url) === 0;
227
    }
228
}
229