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

dg / texy / 15479423458

05 Jun 2025 11:37PM UTC coverage: 92.741% (+0.5%) from 92.224%
15479423458

push

github

dg
HtmlElement: removed toHtml() & toText()

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

78 existing lines in 11 files now uncovered.

2389 of 2576 relevant lines covered (92.74%)

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

17

18
/**
19
 * Html tags module.
20
 */
21
final class HtmlModule extends Texy\Module
22
{
23
        /** pass HTML comments to output? */
24
        public bool $passComment = true;
25

26

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

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

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

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

65

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

75

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

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

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

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

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

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

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

116
                return $res;
1✔
117
        }
118

119

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

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

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

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

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

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

166
                $el->validateAttrs($texy->getDTD());
1✔
167

168
                return $el;
1✔
169
        }
170

171

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

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

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

185

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

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

202

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

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

227

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

246

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

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

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

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

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

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

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

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

296
                return true;
1✔
297
        }
298

299

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

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

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