• 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

95.8
/src/Texy/Modules/HtmlOutputModule.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\Regexp;
15
use function array_intersect, array_keys, array_unshift, max, reset, rtrim, str_repeat, str_replace, strtr, wordwrap;
16

17

18
/**
19
 * Formats and validates HTML output (well-forming, indentation, line wrapping).
20
 */
21
final class HtmlOutputModule extends Texy\Module
22
{
23
        /** indent HTML code? */
24
        public bool $indent = true;
25

26
        /** @var string[] */
27
        public array $preserveSpaces = ['textarea', 'pre', 'script', 'code', 'samp', 'kbd'];
28

29
        /** base indent level */
30
        public int $baseIndent = 0;
31

32
        /** wrap width, doesn't include indent space */
33
        public int $lineWrap = 80;
34

35
        /** indent space counter */
36
        private int $space = 0;
37

38
        /** @var array<string, int> */
39
        private array $tagUsed = [];
40

41
        /** @var array<int, array{tag: string, open: ?string, close: ?string, dtdContent: array<string, int>, indent: int}> */
42
        private array $tagStack = [];
43

44
        /** @var array<string, int>  content DTD used, when context is not defined */
45
        private array $baseDTD = [];
46

47

48
        public function __construct(Texy\Texy $texy)
1✔
49
        {
50
                $this->texy = $texy;
1✔
51
                $texy->addHandler('postProcess', $this->postProcess(...));
1✔
52
        }
1✔
53

54

55
        /**
56
         * Converts <strong><em> ... </strong> ... </em>.
57
         * into <strong><em> ... </em></strong><em> ... </em>
58
         */
59
        private function postProcess(Texy\Texy $texy, string &$s): void
1✔
60
        {
61
                $this->space = $this->baseIndent;
1✔
62
                $this->tagStack = [];
1✔
63
                $this->tagUsed = [];
1✔
64

65
                // special "base content"
66
                $dtd = $texy->getDTD();
1✔
67
                $this->baseDTD = $dtd['div'][1] + $dtd['html'][1] /*+ $dtd['head'][1]*/ + $dtd['body'][1] + ['html' => 1];
1✔
68

69
                // wellform and reformat
70
                $s = Regexp::replace(
1✔
71
                        $s . '</end/>',
1✔
72
                        '#([^<]*+)<(?:(!--.*--)|(/?)([a-z][a-z0-9._:-]*)(|[ \n].*)\s*(/?))>()#Uis',
1✔
73
                        $this->cb(...),
1✔
74
                );
75

76
                // empty out stack
77
                foreach ($this->tagStack as $item) {
1✔
78
                        $s .= $item['close'];
1✔
79
                }
80

81
                // right trim
82
                $s = Regexp::replace($s, "#[\t ]+(\n|\r|$)#", '$1'); // right trim
1✔
83

84
                // join double \r to single \n
85
                $s = str_replace("\r\r", "\n", $s);
1✔
86
                $s = strtr($s, "\r", "\n");
1✔
87

88
                // greedy chars
89
                $s = Regexp::replace($s, '#\x07 *#', '');
1✔
90
                // back-tabs
91
                $s = Regexp::replace($s, '#\t? *\x08#', '');
1✔
92

93
                // line wrap
94
                if ($this->lineWrap > 0) {
1✔
95
                        $s = Regexp::replace(
1✔
96
                                $s,
1✔
97
                                '#^(\t*)(.*)$#m',
1✔
98
                                $this->wrap(...),
1✔
99
                        );
100
                }
101
        }
1✔
102

103

104
        /**
105
         * Callback function: <tag> | </tag> | ....
106
         * @param  string[]  $matches
107
         */
108
        private function cb(array $matches): string
1✔
109
        {
110
                // html tag
111
                [, $mText, $mComment, $mEnd, $mTag, $mAttr, $mEmpty] = $matches;
1✔
112
                // [1] => text
113
                // [1] => !-- comment --
114
                // [2] => /
115
                // [3] => TAG
116
                // [4] => ... (attributes)
117
                // [5] => / (empty)
118

119
                $s = '';
1✔
120

121
                // phase #1 - stuff between tags
122
                if ($mText !== '') {
1✔
123
                        $item = reset($this->tagStack);
1✔
124
                        if ($item && !isset($item['dtdContent'][HtmlElement::InnerText])) {  // text not allowed?
1✔
125

126
                        } elseif (array_intersect(array_keys($this->tagUsed, filter_value: true, strict: false), $this->preserveSpaces)) { // inside pre & textarea preserve spaces
1✔
127
                                $s = Texy\Helpers::freezeSpaces($mText);
1✔
128

129
                        } else {
130
                                $s = Regexp::replace($mText, '#[ \n]+#', ' '); // otherwise shrink multiple spaces
1✔
131
                        }
132
                }
133

134
                // phase #2 - HTML comment
135
                if ($mComment) {
1✔
136
                        return $s . '<' . Texy\Helpers::freezeSpaces($mComment) . '>';
1✔
137
                }
138

139
                // phase #3 - HTML tag
140
                $mEmpty = $mEmpty || isset(HtmlElement::$emptyElements[$mTag]);
1✔
141
                if ($mEmpty && $mEnd) { // bad tag; /end/
1✔
142
                        return $s;
1✔
143
                } elseif ($mEnd) {
1✔
144
                        return $s . $this->processEndTag($mTag);
1✔
145
                } else {
146
                        return $this->processStartTag($mTag, $mEmpty, $mAttr, $s);
1✔
147
                }
148
        }
149

150

151
        private function processStartTag(string $tag, bool $empty, string $attr, string $s): string
1✔
152
        {
153
                $dtdContent = $this->baseDTD;
1✔
154
                $dtd = $this->texy->getDTD();
1✔
155

156
                if (!isset($dtd[$tag])) {
1✔
157
                        // unknown (non-html) tag
158
                        $allowed = true;
×
159
                        $item = reset($this->tagStack);
×
160
                        if ($item) {
×
161
                                $dtdContent = $item['dtdContent'];
×
162
                        }
163
                } else {
164
                        $s .= $this->closeOptionalTags($tag, $dtdContent);
1✔
165

166
                        // is tag allowed in this content?
167
                        $allowed = isset($dtdContent[$tag]);
1✔
168

169
                        // check deep element prohibitions
170
                        if ($allowed && isset(HtmlElement::$prohibits[$tag])) {
1✔
171
                                foreach (HtmlElement::$prohibits[$tag] as $pTag) {
1✔
172
                                        if (!empty($this->tagUsed[$pTag])) {
1✔
173
                                                $allowed = false;
1✔
174
                                                break;
1✔
175
                                        }
176
                                }
177
                        }
178
                }
179

180
                // empty elements se neukladaji do zasobniku
181
                if ($empty) {
1✔
182
                        if (!$allowed) {
1✔
183
                                return $s;
×
184
                        }
185

186
                        $indent = $this->indent && !array_intersect(array_keys($this->tagUsed, filter_value: true, strict: false), $this->preserveSpaces);
1✔
187

188
                        if ($indent && $tag === 'br') { // formatting exception
1✔
189
                                return rtrim($s) . '<' . $tag . $attr . ">\n" . str_repeat("\t", max(0, $this->space - 1)) . "\x07";
1✔
190

191
                        } elseif ($indent && !isset(HtmlElement::$inlineElements[$tag])) {
1✔
192
                                $space = "\r" . str_repeat("\t", $this->space);
1✔
193
                                return $s . $space . '<' . $tag . $attr . '>' . $space;
1✔
194

195
                        } else {
196
                                return $s . '<' . $tag . $attr . '>';
1✔
197
                        }
198
                }
199

200
                $open = null;
1✔
201
                $close = null;
1✔
202
                $indent = 0;
1✔
203

204
                if ($allowed) {
1✔
205
                        $open = '<' . $tag . $attr . '>';
1✔
206

207
                        // receive new content
208
                        if ($tagDTD = $dtd[$tag] ?? null) {
1✔
209
                                if (isset($tagDTD[1][HtmlElement::InnerTransparent])) {
1✔
210
                                        $dtdContent += $tagDTD[1];
1✔
211
                                        unset($dtdContent[HtmlElement::InnerTransparent]);
1✔
212
                                } else {
213
                                        $dtdContent = $tagDTD[1];
1✔
214
                                }
215
                        }
216

217
                        // format output
218
                        if ($this->indent && !isset(HtmlElement::$inlineElements[$tag])) {
1✔
219
                                $close = "\x08" . '</' . $tag . '>' . "\n" . str_repeat("\t", $this->space);
1✔
220
                                $s .= "\n" . str_repeat("\t", $this->space++) . $open . "\x07";
1✔
221
                                $indent = 1;
1✔
222
                        } else {
223
                                $close = '</' . $tag . '>';
1✔
224
                                $s .= $open;
1✔
225
                        }
226

227
                        // TODO: problematic formatting of select / options, object / params
228
                }
229

230
                // open tag, put to stack, increase counter
231
                $item = [
1✔
232
                        'tag' => $tag,
1✔
233
                        'open' => $open,
1✔
234
                        'close' => $close,
1✔
235
                        'dtdContent' => $dtdContent,
1✔
236
                        'indent' => $indent,
1✔
237
                ];
238
                array_unshift($this->tagStack, $item);
1✔
239
                $tmp = &$this->tagUsed[$tag];
1✔
240
                $tmp++;
1✔
241

242
                return $s;
1✔
243
        }
244

245

246
        private function processEndTag(string $tag): string
1✔
247
        {
248
                // has start tag?
249
                if (empty($this->tagUsed[$tag])) {
1✔
250
                        return '';
1✔
251
                }
252

253
                // autoclose tags
254
                $tmp = [];
1✔
255
                $back = true;
1✔
256
                $s = '';
1✔
257
                foreach ($this->tagStack as $i => $item) {
1✔
258
                        $itemTag = $item['tag'];
1✔
259
                        $s .= $item['close'];
1✔
260
                        $this->space -= $item['indent'];
1✔
261
                        $this->tagUsed[$itemTag]--;
1✔
262
                        $back = $back && isset(HtmlElement::$inlineElements[$itemTag]);
1✔
263
                        unset($this->tagStack[$i]);
1✔
264
                        if ($itemTag === $tag) {
1✔
265
                                break;
1✔
266
                        }
267

268
                        array_unshift($tmp, $item);
1✔
269
                }
270

271
                if (!$back || !$tmp) {
1✔
272
                        return $s;
1✔
273
                }
274

275
                // allowed-check (nejspis neni ani potreba)
276
                $item = reset($this->tagStack);
1✔
277
                $dtdContent = $item ? $item['dtdContent'] : $this->baseDTD;
1✔
278
                if (!isset($dtdContent[$tmp[0]['tag']])) {
1✔
279
                        return $s;
×
280
                }
281

282
                // autoopen tags
283
                foreach ($tmp as $item) {
1✔
284
                        $s .= $item['open'];
1✔
285
                        $this->space += $item['indent'];
1✔
286
                        $this->tagUsed[$item['tag']]++;
1✔
287
                        array_unshift($this->tagStack, $item);
1✔
288
                }
289

290
                return $s;
1✔
291
        }
292

293

294
        /** @param  array<string, int>  $dtdContent */
295
        private function closeOptionalTags(string $tag, array &$dtdContent): string
1✔
296
        {
297
                $s = '';
1✔
298
                foreach ($this->tagStack as $i => $item) {
1✔
299
                        // is tag allowed here?
300
                        $dtdContent = $item['dtdContent'];
1✔
301
                        if (isset($dtdContent[$tag])) {
1✔
302
                                break;
1✔
303
                        }
304

305
                        $itemTag = $item['tag'];
1✔
306

307
                        // auto-close hidden, optional and inline tags
308
                        if (
309
                                $item['close']
1✔
310
                                && (
311
                                        !isset(HtmlElement::$optionalEnds[$itemTag])
1✔
312
                                        && !isset(HtmlElement::$inlineElements[$itemTag])
1✔
313
                                )
314
                        ) {
315
                                break;
1✔
316
                        }
317

318
                        // close it
319
                        $s .= $item['close'];
1✔
320
                        $this->space -= $item['indent'];
1✔
321
                        $this->tagUsed[$itemTag]--;
1✔
322
                        unset($this->tagStack[$i]);
1✔
323
                        $dtdContent = $this->baseDTD;
1✔
324
                }
325

326
                return $s;
1✔
327
        }
328

329

330
        /**
331
         * Callback function: wrap lines.
332
         * @param  string[]  $m
333
         */
334
        private function wrap(array $m): string
1✔
335
        {
336
                [, $space, $s] = $m;
1✔
337
                return $space . wordwrap($s, $this->lineWrap, "\n" . $space);
1✔
338
        }
339
}
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