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

dg / texy / 16790351274

06 Aug 2025 10:42PM UTC coverage: 92.746% (+0.005%) from 92.741%
16790351274

push

github

dg
HtmlElement: removed toHtml() & toText()

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

136 existing lines in 23 files now uncovered.

2391 of 2578 relevant lines covered (92.75%)

0.93 hits per line

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

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

3
/**
4
 * This file is part of the Texy! (https://texy.info)
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
 * Html tags module.
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
         */
71
        public function parseComment(Texy\LineParser $parser, array $matches): HtmlElement|string|null
1✔
72
        {
73
                [, $mComment] = $matches;
1✔
74
                return $this->texy->invokeAroundHandlers('htmlComment', $parser, [$mComment]);
1✔
75
        }
76

77

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

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

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

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

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

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

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

118
                return $res;
1✔
119
        }
120

121

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

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

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

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

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

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

168
                $el->validateAttrs($texy->getDTD());
1✔
169

170
                return $el;
1✔
171
        }
172

173

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

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

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

187

188
        private function applyAttrs(&$attrs, $allowedAttrs): void
189
        {
190
                if (!$allowedAttrs) {
1✔
191
                        $attrs = [];
1✔
192

193
                } elseif (is_array($allowedAttrs)) {
1✔
194
                        // skip disabled
195
                        $allowedAttrs = array_flip($allowedAttrs);
1✔
196
                        foreach ($attrs as $key => $foo) {
1✔
197
                                if (!isset($allowedAttrs[$key])) {
1✔
UNCOV
198
                                        unset($attrs[$key]);
×
199
                                }
200
                        }
201
                }
202
        }
1✔
203

204

205
        private function applyClasses(&$attrs, $allowedClasses): void
206
        {
207
                if (!isset($attrs['class'])) {
1✔
208
                } elseif (is_array($allowedClasses)) {
×
209
                        $attrs['class'] = explode(' ', $attrs['class']);
×
210
                        foreach ($attrs['class'] as $key => $value) {
×
UNCOV
211
                                if (!isset($allowedClasses[$value])) {
×
UNCOV
212
                                        unset($attrs['class'][$key]); // id & class are case-sensitive
×
213
                                }
214
                        }
UNCOV
215
                } elseif ($allowedClasses !== Texy\Texy::ALL) {
×
UNCOV
216
                        $attrs['class'] = null;
×
217
                }
218

219
                if (!isset($attrs['id'])) {
1✔
220
                } elseif (is_array($allowedClasses)) {
1✔
UNCOV
221
                        if (!isset($allowedClasses['#' . $attrs['id']])) {
×
UNCOV
222
                                $attrs['id'] = null;
×
223
                        }
224
                } elseif ($allowedClasses !== Texy\Texy::ALL) {
1✔
UNCOV
225
                        $attrs['id'] = null;
×
226
                }
227
        }
1✔
228

229

230
        private function applyStyles(&$attrs, $allowedStyles): void
231
        {
232
                if (!isset($attrs['style'])) {
1✔
233
                } elseif (is_array($allowedStyles)) {
1✔
234
                        $tmp = explode(';', $attrs['style']);
×
235
                        $attrs['style'] = null;
×
236
                        foreach ($tmp as $value) {
×
237
                                $pair = explode(':', $value, 2);
×
238
                                $prop = trim($pair[0]);
×
UNCOV
239
                                if (isset($pair[1], $allowedStyles[strtolower($prop)])) { // CSS is case-insensitive
×
UNCOV
240
                                        $attrs['style'][$prop] = $pair[1];
×
241
                                }
242
                        }
243
                } elseif ($allowedStyles !== Texy\Texy::ALL) {
1✔
UNCOV
244
                        $attrs['style'] = null;
×
245
                }
246
        }
1✔
247

248

249
        private function validateAttrs(HtmlElement $el, Texy\Texy $texy): bool
1✔
250
        {
251
                foreach (['src', 'href', 'name', 'id'] as $attr) {
1✔
252
                        if (isset($el->attrs[$attr])) {
1✔
253
                                $el->attrs[$attr] = is_string($el->attrs[$attr])
1✔
254
                                        ? trim($el->attrs[$attr])
1✔
255
                                        : '';
×
256
                                if ($el->attrs[$attr] === '') {
1✔
UNCOV
257
                                        unset($el->attrs[$attr]);
×
258
                                }
259
                        }
260
                }
261

262
                $name = $el->getName();
1✔
263
                if ($name === 'img') {
1✔
264
                        if (!isset($el->attrs['src']) || !$texy->checkURL($el->attrs['src'], $texy::FILTER_IMAGE)) {
1✔
UNCOV
265
                                return false;
×
266
                        }
267

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

270
                } elseif ($name === 'a') {
1✔
271
                        if (!isset($el->attrs['href']) && !isset($el->attrs['name']) && !isset($el->attrs['id'])) {
1✔
272
                                return false;
1✔
273
                        }
274

275
                        if (isset($el->attrs['href'])) {
1✔
276
                                if ($texy->linkModule->forceNoFollow && str_contains($el->attrs['href'], '//')) {
1✔
277
                                        if (isset($el->attrs['rel'])) {
1✔
278
                                                $el->attrs['rel'] = (array) $el->attrs['rel'];
1✔
279
                                        }
280

281
                                        $el->attrs['rel'][] = 'nofollow';
1✔
282
                                }
283

284
                                if (!$texy->checkURL($el->attrs['href'], $texy::FILTER_ANCHOR)) {
1✔
285
                                        return false;
1✔
286
                                }
287

288
                                $texy->summary['links'][] = $el->attrs['href'];
1✔
289
                        }
290
                } elseif (Regexp::match($name, '~^h[1-6]~i')) {
1✔
291
                        $texy->headingModule->TOC[] = [
1✔
292
                                'el' => $el,
1✔
293
                                'level' => (int) substr($name, 1),
1✔
294
                                'type' => 'html',
1✔
295
                        ];
296
                }
297

298
                return true;
1✔
299
        }
300

301

302
        private function parseAttributes(string $attrs): array
1✔
303
        {
304
                $res = [];
1✔
305
                $matches = Regexp::matchAll(
1✔
306
                        $attrs,
1✔
307
                        <<<'X'
308
                                ~
1✔
309
                                ([a-z0-9_:-]+)                 # attribute name
310
                                \s*
311
                                (?:
312
                                        = \s*                      # equals sign
313
                                        (
314
                                                ' [^']* ' |            # single quoted value
315
                                                " [^"]* " |            # double quoted value
316
                                                [^'"\s]+               # unquoted value
317
                                        )
318
                                )?
319
                                ~is
320
                                X,
321
                );
322

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

335
                return $res;
1✔
336
        }
337
}
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