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

dg / texy / 21344532034

26 Jan 2026 02:43AM UTC coverage: 91.98% (-0.4%) from 92.376%
21344532034

push

github

dg
added CLAUDE.md

2397 of 2606 relevant lines covered (91.98%)

0.92 hits per line

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

79.08
/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 function array_flip, explode, is_array, is_string, preg_match, preg_match_all, str_contains, str_ends_with, strtolower, strtoupper, strtr, substr, trim;
16
use const PREG_SET_ORDER;
17

18

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

27

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

32
                $texy->addHandler('htmlComment', $this->solveComment(...));
1✔
33
                $texy->addHandler('htmlTag', $this->solveTag(...));
1✔
34

35
                $texy->registerLinePattern(
1✔
36
                        $this->patternTag(...),
1✔
37
                        '#<(/?)([a-z][a-z0-9_:-]{0,50})((?:\s++[a-z0-9\_:-]++|=\s*+"[^"' . Patterns::MARK . ']*+"|=\s*+\'[^\'' . Patterns::MARK . ']*+\'|=[^\s>' . Patterns::MARK . ']++)*)\s*+(/?)>#isu',
1✔
38
                        'html/tag',
1✔
39
                );
40

41
                $texy->registerLinePattern(
1✔
42
                        $this->patternComment(...),
1✔
43
                        '#<!--([^' . Patterns::MARK . ']*?)-->#is',
1✔
44
                        'html/comment',
1✔
45
                );
46
        }
1✔
47

48

49
        /**
50
         * Callback for: <!-- comment -->.
51
         * @param  string[]  $matches
52
         */
53
        public function patternComment(Texy\LineParser $parser, array $matches): HtmlElement|string|null
1✔
54
        {
55
                [, $mComment] = $matches;
1✔
56
                return $this->texy->invokeAroundHandlers('htmlComment', $parser, [$mComment]);
1✔
57
        }
58

59

60
        /**
61
         * Callback for: <tag attr="...">.
62
         * @param  string[]  $matches
63
         */
64
        public function patternTag(Texy\LineParser $parser, array $matches): ?string
1✔
65
        {
66
                [, $mEnd, $mTag, $mAttr, $mEmpty] = $matches;
1✔
67
                // [1] => /
68
                // [2] => tag
69
                // [3] => attributes
70
                // [4] => /
71

72
                $isStart = $mEnd !== '/';
1✔
73
                $isEmpty = $mEmpty === '/';
1✔
74
                if (!$isEmpty && str_ends_with($mAttr, '/')) { // uvizlo v $mAttr?
1✔
75
                        $mAttr = substr($mAttr, 0, -1);
×
76
                        $isEmpty = true;
×
77
                }
78

79
                // error - can't close empty element
80
                if ($isEmpty && !$isStart) {
1✔
81
                        return null;
×
82
                }
83

84
                // error - end element with atttrs
85
                $mAttr = trim(strtr($mAttr, "\n", ' '));
1✔
86
                if ($mAttr && !$isStart) {
1✔
87
                        return null;
1✔
88
                }
89

90
                $el = new HtmlElement($mTag);
1✔
91
                if ($isStart) {
1✔
92
                        $el->attrs = $this->parseAttributes($mAttr);
1✔
93
                }
94

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

97
                if ($res instanceof HtmlElement) {
1✔
98
                        return $this->texy->protect($isStart ? $res->startTag() : $res->endTag(), $res->getContentType());
1✔
99
                }
100

101
                return $res;
1✔
102
        }
103

104

105
        /**
106
         * Finish invocation.
107
         */
108
        private function solveTag(
1✔
109
                Texy\HandlerInvocation $invocation,
110
                HtmlElement $el,
111
                bool $isStart,
112
                ?bool $forceEmpty = null,
113
        ): ?HtmlElement
114
        {
115
                $texy = $this->texy;
1✔
116

117
                // tag & attibutes
118
                $allowedTags = $texy->allowedTags; // speed-up
1✔
119
                if (!$allowedTags) {
1✔
120
                        return null; // all tags are disabled
1✔
121
                }
122

123
                // convert case
124
                $name = $el->getName();
1✔
125
                $lower = strtolower($name);
1✔
126
                if (isset($texy->getDTD()[$lower]) || $name === strtoupper($name)) {
1✔
127
                        // complete UPPER convert to lower
128
                        $name = $lower;
1✔
129
                        $el->setName($name);
1✔
130
                }
131

132
                if (is_array($allowedTags)) {
1✔
133
                        if (!isset($allowedTags[$name])) {
1✔
134
                                return null;
1✔
135
                        }
136
                } else { // allowedTags === Texy\Texy::ALL
137
                        if ($forceEmpty) {
×
138
                                $el->setName($name, empty: true);
×
139
                        }
140
                }
141

142
                // end tag? we are finished
143
                if (!$isStart) {
1✔
144
                        return $el;
1✔
145
                }
146

147
                $this->applyAttrs($el->attrs, is_array($allowedTags) ? $allowedTags[$name] : $texy::ALL);
1✔
148
                $this->applyClasses($el->attrs, $texy->getAllowedProps()[0]);
1✔
149
                $this->applyStyles($el->attrs, $texy->getAllowedProps()[1]);
1✔
150
                if (!$this->validateAttrs($el, $texy)) {
1✔
151
                        return null;
1✔
152
                }
153

154
                $el->validateAttrs($texy->getDTD());
1✔
155

156
                return $el;
1✔
157
        }
158

159

160
        /**
161
         * Finish invocation.
162
         */
163
        private function solveComment(Texy\HandlerInvocation $invocation, string $content): string
1✔
164
        {
165
                if (!$this->passComment) {
1✔
166
                        return '';
×
167
                }
168

169
                // sanitize comment
170
                $content = Texy\Regexp::replace($content, '#-{2,}#', ' - ');
1✔
171
                $content = trim($content, '-');
1✔
172

173
                return $this->texy->protect('<!--' . $content . '-->', Texy\Texy::CONTENT_MARKUP);
1✔
174
        }
175

176

177
        /**
178
         * @param  array<string, array<string|int|bool>|string|int|bool|null>  $attrs
179
         * @param  bool|string[]  $allowedAttrs
180
         */
181
        private function applyAttrs(array &$attrs, bool|array $allowedAttrs): void
1✔
182
        {
183
                if (!$allowedAttrs) {
1✔
184
                        $attrs = [];
1✔
185

186
                } elseif (is_array($allowedAttrs)) {
1✔
187
                        // skip disabled
188
                        $allowedAttrs = array_flip($allowedAttrs);
1✔
189
                        foreach ($attrs as $key => $foo) {
1✔
190
                                if (!isset($allowedAttrs[$key])) {
1✔
191
                                        unset($attrs[$key]);
×
192
                                }
193
                        }
194
                }
195
        }
1✔
196

197

198
        /**
199
         * @param  array<string, string|int|bool|array<string|int|bool>|null>  $attrs
200
         * @param  array<string, int>|bool  $allowedClasses
201
         */
202
        private function applyClasses(array &$attrs, bool|array $allowedClasses): void
1✔
203
        {
204
                if (!isset($attrs['class'])) {
1✔
205
                } elseif (is_array($allowedClasses)) {
×
206
                        $attrs['class'] = is_string($attrs['class']) ? explode(' ', $attrs['class']) : (array) $attrs['class'];
×
207
                        foreach ($attrs['class'] as $key => $value) {
×
208
                                if (!isset($allowedClasses[$value])) {
×
209
                                        unset($attrs['class'][$key]); // id & class are case-sensitive
×
210
                                }
211
                        }
212
                } elseif ($allowedClasses !== Texy\Texy::ALL) {
×
213
                        $attrs['class'] = null;
×
214
                }
215

216
                if (!isset($attrs['id'])) {
1✔
217
                } elseif (is_array($allowedClasses)) {
1✔
218
                        if (!is_string($attrs['id']) || !isset($allowedClasses['#' . $attrs['id']])) {
×
219
                                $attrs['id'] = null;
×
220
                        }
221

222
                } elseif ($allowedClasses !== Texy\Texy::ALL) {
1✔
223
                        $attrs['id'] = null;
×
224
                }
225
        }
1✔
226

227

228
        /**
229
         * @param  array<string, string|int|bool|array<string|int|bool>|null>  $attrs
230
         * @param  array<string, int>|bool  $allowedStyles
231
         */
232
        private function applyStyles(array &$attrs, bool|array $allowedStyles): void
1✔
233
        {
234
                if (!isset($attrs['style'])) {
1✔
235
                } elseif (is_array($allowedStyles)) {
1✔
236
                        if (is_string($attrs['style'])) {
×
237
                                $parts = explode(';', $attrs['style']);
×
238
                                $attrs['style'] = [];
×
239
                                foreach ($parts as $value) {
×
240
                                        if (count($pair = explode(':', $value, 2)) === 2) {
×
241
                                                $attrs['style'][trim($pair[0])] = trim($pair[1]);
×
242
                                        }
243
                                }
244
                        } else {
245
                                $attrs['style'] = (array) $attrs['style'];
×
246
                        }
247

248
                        foreach ($attrs['style'] as $key => $value) {
×
249
                                if (!isset($allowedStyles[strtolower((string) $key)])) { // CSS is case-insensitive
×
250
                                        unset($attrs['style'][$key]);
×
251
                                }
252
                        }
253
                } elseif ($allowedStyles !== Texy\Texy::ALL) {
1✔
254
                        $attrs['style'] = null;
×
255
                }
256
        }
1✔
257

258

259
        private function validateAttrs(HtmlElement $el, Texy\Texy $texy): bool
1✔
260
        {
261
                foreach (['src', 'href', 'name', 'id'] as $attr) {
1✔
262
                        if (isset($el->attrs[$attr])) {
1✔
263
                                $el->attrs[$attr] = is_string($el->attrs[$attr])
1✔
264
                                        ? trim($el->attrs[$attr])
1✔
265
                                        : '';
×
266
                                if ($el->attrs[$attr] === '') {
1✔
267
                                        unset($el->attrs[$attr]);
×
268
                                }
269
                        }
270
                }
271

272
                $name = $el->getName();
1✔
273
                if ($name === 'img') {
1✔
274
                        if (!isset($el->attrs['src'])) {
1✔
275
                                return false;
×
276
                        }
277

278
                        assert(is_string($el->attrs['src']));
279
                        if (!$texy->checkURL($el->attrs['src'], $texy::FILTER_IMAGE)) {
1✔
280
                                return false;
×
281
                        }
282

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

285
                } elseif ($name === 'a') {
1✔
286
                        if (!isset($el->attrs['href']) && !isset($el->attrs['name']) && !isset($el->attrs['id'])) {
1✔
287
                                return false;
1✔
288
                        }
289

290
                        if (isset($el->attrs['href'])) {
1✔
291
                                assert(is_string($el->attrs['href']));
292
                                if ($texy->linkModule->forceNoFollow && str_contains($el->attrs['href'], '//')) {
1✔
293
                                        $el->attrs['rel'] = (array) ($el->attrs['rel'] ?? []);
1✔
294
                                        $el->attrs['rel'][] = 'nofollow';
1✔
295
                                }
296

297
                                if (!$texy->checkURL($el->attrs['href'], $texy::FILTER_ANCHOR)) {
1✔
298
                                        return false;
1✔
299
                                }
300

301
                                $texy->summary['links'][] = $el->attrs['href'];
1✔
302
                        }
303

304
                } elseif (preg_match('#^h[1-6]#i', $name)) {
1✔
305
                        $texy->headingModule->TOC[] = [
1✔
306
                                'el' => $el,
1✔
307
                                'level' => (int) substr($name, 1),
1✔
308
                                'type' => 'html',
1✔
309
                        ];
310
                }
311

312
                return true;
1✔
313
        }
314

315

316
        /** @return array<string, string|bool> */
317
        private function parseAttributes(string $attrs): array
1✔
318
        {
319
                $matches = $res = [];
1✔
320
                preg_match_all(
1✔
321
                        '#([a-z0-9\_:-]+)\s*(?:=\s*(\'[^\']*\'|"[^"]*"|[^\'"\s]+))?()#isu',
1✔
322
                        $attrs,
1✔
323
                        $matches,
1✔
324
                        PREG_SET_ORDER,
1✔
325
                );
326

327
                foreach ($matches as $m) {
1✔
328
                        $key = strtolower($m[1]);
1✔
329
                        $value = $m[2];
1✔
330
                        if ($value == null) {
1✔
331
                                $res[$key] = true;
1✔
332
                        } elseif ($value[0] === '\'' || $value[0] === '"') {
1✔
333
                                $res[$key] = Texy\Helpers::unescapeHtml(substr($value, 1, -1));
1✔
334
                        } else {
335
                                $res[$key] = Texy\Helpers::unescapeHtml($value);
1✔
336
                        }
337
                }
338

339
                return $res;
1✔
340
        }
341
}
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