• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

dg / texy / 21345344909

26 Jan 2026 03:32AM UTC coverage: 92.382% (-0.4%) from 92.744%
21345344909

push

github

dg
HtmlElement: removed toHtml() & toText()

18 of 19 new or added lines in 5 files covered. (94.74%)

149 existing lines in 21 files now uncovered.

2401 of 2599 relevant lines covered (92.38%)

0.92 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.81
/src/Texy/Modules/HtmlModule.php
1
<?php
2

3
/**
4
 * This file is part of the Texy! (https://texy.nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
declare(strict_types=1);
9

10
namespace Texy\Modules;
11

12
use Texy;
13
use Texy\HtmlElement;
14
use Texy\Patterns;
15
use Texy\Regexp;
16
use function array_flip, explode, is_array, is_string, preg_match, preg_match_all, str_contains, str_ends_with, strtolower, strtoupper, strtr, substr, trim;
17
use const PREG_SET_ORDER;
18

19

20
/**
21
 * Processes HTML tags and comments in input text.
22
 */
23
final class HtmlModule extends Texy\Module
24
{
25
        /** pass HTML comments to output? */
26
        public bool $passComment = true;
27

28

29
        public function __construct(Texy\Texy $texy)
1✔
30
        {
31
                $this->texy = $texy;
1✔
32

33
                $texy->addHandler('htmlComment', $this->commentToElement(...));
1✔
34
                $texy->addHandler('htmlTag', $this->tagToElement(...));
1✔
35

36
                $texy->registerLinePattern(
1✔
37
                        $this->parseTag(...),
1✔
38
                        '~
39
                                < (/?)                          # tag begin
40
                                ([a-z][a-z0-9_:-]{0,50})        # tag name
41
                                (
42
                                        (?:
43
                                                \s++ [a-z0-9_:-]++ |   # attribute name
44
                                                = \s*+ " [^"' . Patterns::MARK . ']*+ " |     # attribute value in double quotes
45
                                                = \s*+ \' [^\'' . Patterns::MARK . ']*+ \' |  # attribute value in single quotes
46
                                                = [^\s>' . Patterns::MARK . ']++              # attribute value without quotes
1✔
47
                                        )*
48
                                )
49
                                \s*+
50
                                (/?)                             # self-closing slash
51
                                >
52
                        ~is',
53
                        'html/tag',
1✔
54
                );
55

56
                $texy->registerLinePattern(
1✔
57
                        $this->parseComment(...),
1✔
58
                        '~
59
                                <!--
60
                                ( [^' . Patterns::MARK . ']*? )
1✔
61
                                -->
62
                        ~is',
63
                        'html/comment',
1✔
64
                );
65
        }
1✔
66

67

68
        /**
69
         * Callback for: <!-- comment -->.
70
         * @param  string[]  $matches
71
         */
72
        public function parseComment(Texy\LineParser $parser, array $matches): HtmlElement|string|null
1✔
73
        {
74
                [, $mComment] = $matches;
1✔
75
                return $this->texy->invokeAroundHandlers('htmlComment', $parser, [$mComment]);
1✔
76
        }
77

78

79
        /**
80
         * Callback for: <tag attr="...">.
81
         * @param  string[]  $matches
82
         */
83
        public function parseTag(Texy\LineParser $parser, array $matches): ?string
1✔
84
        {
85
                [, $mEnd, $mTag, $mAttr, $mEmpty] = $matches;
1✔
86
                // [1] => /
87
                // [2] => tag
88
                // [3] => attributes
89
                // [4] => /
90

91
                $isStart = $mEnd !== '/';
1✔
92
                $isEmpty = $mEmpty === '/';
1✔
93
                if (!$isEmpty && str_ends_with($mAttr, '/')) { // uvizlo v $mAttr?
1✔
UNCOV
94
                        $mAttr = substr($mAttr, 0, -1);
×
UNCOV
95
                        $isEmpty = true;
×
96
                }
97

98
                // error - can't close empty element
99
                if ($isEmpty && !$isStart) {
1✔
UNCOV
100
                        return null;
×
101
                }
102

103
                // error - end element with atttrs
104
                $mAttr = trim(strtr($mAttr, "\n", ' '));
1✔
105
                if ($mAttr && !$isStart) {
1✔
106
                        return null;
1✔
107
                }
108

109
                $el = new HtmlElement($mTag);
1✔
110
                if ($isStart) {
1✔
111
                        $el->attrs = $this->parseAttributes($mAttr);
1✔
112
                }
113

114
                $res = $this->texy->invokeAroundHandlers('htmlTag', $parser, [$el, $isStart, $isEmpty]);
1✔
115

116
                if ($res instanceof HtmlElement) {
1✔
117
                        return $this->texy->protect($isStart ? $res->startTag() : $res->endTag(), $res->getContentType());
1✔
118
                }
119

120
                return $res;
1✔
121
        }
122

123

124
        public function tagToElement(
1✔
125
                Texy\HandlerInvocation $invocation,
126
                HtmlElement $el,
127
                bool $isStart,
128
                ?bool $forceEmpty = null,
129
        ): ?HtmlElement
130
        {
131
                $texy = $this->texy;
1✔
132

133
                // tag & attibutes
134
                $allowedTags = $texy->allowedTags; // speed-up
1✔
135
                if (!$allowedTags) {
1✔
136
                        return null; // all tags are disabled
1✔
137
                }
138

139
                // convert case
140
                $name = $el->getName();
1✔
141
                $lower = strtolower($name);
1✔
142
                if (isset($texy->getDTD()[$lower]) || $name === strtoupper($name)) {
1✔
143
                        // complete UPPER convert to lower
144
                        $name = $lower;
1✔
145
                        $el->setName($name);
1✔
146
                }
147

148
                if (is_array($allowedTags)) {
1✔
149
                        if (!isset($allowedTags[$name])) {
1✔
150
                                return null;
1✔
151
                        }
152
                } else { // allowedTags === Texy\Texy::ALL
UNCOV
153
                        if ($forceEmpty) {
×
UNCOV
154
                                $el->setName($name, empty: true);
×
155
                        }
156
                }
157

158
                // end tag? we are finished
159
                if (!$isStart) {
1✔
160
                        return $el;
1✔
161
                }
162

163
                $this->applyAttrs($el->attrs, is_array($allowedTags) ? $allowedTags[$name] : $texy::ALL);
1✔
164
                $this->applyClasses($el->attrs, $texy->getAllowedProps()[0]);
1✔
165
                $this->applyStyles($el->attrs, $texy->getAllowedProps()[1]);
1✔
166
                if (!$this->validateAttrs($el, $texy)) {
1✔
167
                        return null;
1✔
168
                }
169

170
                $el->validateAttrs($texy->getDTD());
1✔
171

172
                return $el;
1✔
173
        }
174

175

176
        public function commentToElement(Texy\HandlerInvocation $invocation, string $content): string
1✔
177
        {
178
                if (!$this->passComment) {
1✔
UNCOV
179
                        return '';
×
180
                }
181

182
                // sanitize comment
183
                $content = Regexp::replace($content, '~-{2,}~', ' - ');
1✔
184
                $content = trim($content, '-');
1✔
185

186
                return $this->texy->protect('<!--' . $content . '-->', Texy\Texy::CONTENT_MARKUP);
1✔
187
        }
188

189

190
        /**
191
         * @param  array<string, array<string|int|bool>|string|int|bool|null>  $attrs
192
         * @param  bool|string[]  $allowedAttrs
193
         */
194
        private function applyAttrs(array &$attrs, bool|array $allowedAttrs): void
1✔
195
        {
196
                if (!$allowedAttrs) {
1✔
197
                        $attrs = [];
1✔
198

199
                } elseif (is_array($allowedAttrs)) {
1✔
200
                        // skip disabled
201
                        $allowedAttrs = array_flip($allowedAttrs);
1✔
202
                        foreach ($attrs as $key => $foo) {
1✔
203
                                if (!isset($allowedAttrs[$key])) {
1✔
UNCOV
204
                                        unset($attrs[$key]);
×
205
                                }
206
                        }
207
                }
208
        }
1✔
209

210

211
        /**
212
         * @param  array<string, string|int|bool|array<string|int|bool>|null>  $attrs
213
         * @param  array<string, int>|bool  $allowedClasses
214
         */
215
        private function applyClasses(array &$attrs, bool|array $allowedClasses): void
1✔
216
        {
217
                if (!isset($attrs['class'])) {
1✔
UNCOV
218
                } elseif (is_array($allowedClasses)) {
×
UNCOV
219
                        $attrs['class'] = is_string($attrs['class']) ? explode(' ', $attrs['class']) : (array) $attrs['class'];
×
UNCOV
220
                        foreach ($attrs['class'] as $key => $value) {
×
221
                                if (!isset($allowedClasses[$value])) {
×
222
                                        unset($attrs['class'][$key]); // id & class are case-sensitive
×
223
                                }
224
                        }
225
                } elseif ($allowedClasses !== Texy\Texy::ALL) {
×
UNCOV
226
                        $attrs['class'] = null;
×
227
                }
228

229
                if (!isset($attrs['id'])) {
1✔
230
                } elseif (is_array($allowedClasses)) {
1✔
UNCOV
231
                        if (!is_string($attrs['id']) || !isset($allowedClasses['#' . $attrs['id']])) {
×
UNCOV
232
                                $attrs['id'] = null;
×
233
                        }
234

235
                } elseif ($allowedClasses !== Texy\Texy::ALL) {
1✔
236
                        $attrs['id'] = null;
×
237
                }
238
        }
1✔
239

240

241
        /**
242
         * @param  array<string, string|int|bool|array<string|int|bool>|null>  $attrs
243
         * @param  array<string, int>|bool  $allowedStyles
244
         */
245
        private function applyStyles(array &$attrs, bool|array $allowedStyles): void
1✔
246
        {
247
                if (!isset($attrs['style'])) {
1✔
248
                } elseif (is_array($allowedStyles)) {
1✔
UNCOV
249
                        if (is_string($attrs['style'])) {
×
UNCOV
250
                                $parts = explode(';', $attrs['style']);
×
UNCOV
251
                                $attrs['style'] = [];
×
UNCOV
252
                                foreach ($parts as $value) {
×
UNCOV
253
                                        if (count($pair = explode(':', $value, 2)) === 2) {
×
UNCOV
254
                                                $attrs['style'][trim($pair[0])] = trim($pair[1]);
×
255
                                        }
256
                                }
257
                        } else {
UNCOV
258
                                $attrs['style'] = (array) $attrs['style'];
×
259
                        }
260

UNCOV
261
                        foreach ($attrs['style'] as $key => $value) {
×
UNCOV
262
                                if (!isset($allowedStyles[strtolower((string) $key)])) { // CSS is case-insensitive
×
UNCOV
263
                                        unset($attrs['style'][$key]);
×
264
                                }
265
                        }
266
                } elseif ($allowedStyles !== Texy\Texy::ALL) {
1✔
UNCOV
267
                        $attrs['style'] = null;
×
268
                }
269
        }
1✔
270

271

272
        private function validateAttrs(HtmlElement $el, Texy\Texy $texy): bool
1✔
273
        {
274
                foreach (['src', 'href', 'name', 'id'] as $attr) {
1✔
275
                        if (isset($el->attrs[$attr])) {
1✔
276
                                $el->attrs[$attr] = is_string($el->attrs[$attr])
1✔
277
                                        ? trim($el->attrs[$attr])
1✔
UNCOV
278
                                        : '';
×
279
                                if ($el->attrs[$attr] === '') {
1✔
UNCOV
280
                                        unset($el->attrs[$attr]);
×
281
                                }
282
                        }
283
                }
284

285
                $name = $el->getName();
1✔
286
                if ($name === 'img') {
1✔
287
                        if (!isset($el->attrs['src'])) {
1✔
UNCOV
288
                                return false;
×
289
                        }
290

291
                        assert(is_string($el->attrs['src']));
292
                        if (!$texy->checkURL($el->attrs['src'], $texy::FILTER_IMAGE)) {
1✔
UNCOV
293
                                return false;
×
294
                        }
295

296
                        $texy->summary['images'][] = $el->attrs['src'];
1✔
297

298
                } elseif ($name === 'a') {
1✔
299
                        if (!isset($el->attrs['href']) && !isset($el->attrs['name']) && !isset($el->attrs['id'])) {
1✔
300
                                return false;
1✔
301
                        }
302

303
                        if (isset($el->attrs['href'])) {
1✔
304
                                assert(is_string($el->attrs['href']));
305
                                if ($texy->linkModule->forceNoFollow && str_contains($el->attrs['href'], '//')) {
1✔
306
                                        $el->attrs['rel'] = (array) ($el->attrs['rel'] ?? []);
1✔
307
                                        $el->attrs['rel'][] = 'nofollow';
1✔
308
                                }
309

310
                                if (!$texy->checkURL($el->attrs['href'], $texy::FILTER_ANCHOR)) {
1✔
311
                                        return false;
1✔
312
                                }
313

314
                                $texy->summary['links'][] = $el->attrs['href'];
1✔
315
                        }
316

317
                } elseif (Regexp::match($name, '~^h[1-6]~i')) {
1✔
318
                        $texy->headingModule->TOC[] = [
1✔
319
                                'el' => $el,
1✔
320
                                'level' => (int) substr($name, 1),
1✔
321
                                'type' => 'html',
1✔
322
                        ];
323
                }
324

325
                return true;
1✔
326
        }
327

328

329
        /** @return array<string, string|bool> */
330
        private function parseAttributes(string $attrs): array
1✔
331
        {
332
                $res = [];
1✔
333
                $matches = Regexp::matchAll(
1✔
334
                        $attrs,
1✔
335
                        <<<'X'
336
                                ~
1✔
337
                                ([a-z0-9_:-]+)                 # attribute name
338
                                \s*
339
                                (?:
340
                                        = \s*                      # equals sign
341
                                        (
342
                                                ' [^']* ' |            # single quoted value
343
                                                " [^"]* " |            # double quoted value
344
                                                [^'"\s]+               # unquoted value
345
                                        )
346
                                )?
347
                                ~is
348
                                X,
349
                );
350

351
                foreach ($matches as $m) {
1✔
352
                        $key = strtolower($m[1]);
1✔
353
                        $value = $m[2];
1✔
354
                        if ($value == null) {
1✔
355
                                $res[$key] = true;
1✔
356
                        } elseif ($value[0] === '\'' || $value[0] === '"') {
1✔
357
                                $res[$key] = Texy\Helpers::unescapeHtml(substr($value, 1, -1));
1✔
358
                        } else {
359
                                $res[$key] = Texy\Helpers::unescapeHtml($value);
1✔
360
                        }
361
                }
362

363
                return $res;
1✔
364
        }
365
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc