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

dg / texy / 22262497275

21 Feb 2026 07:01PM UTC coverage: 93.057% (+0.7%) from 92.367%
22262497275

push

github

dg
added CLAUDE.md

2426 of 2607 relevant lines covered (93.06%)

0.93 hits per line

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

98.6
/src/Texy/Modules/HtmlOutputModule.php
1
<?php declare(strict_types=1);
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
namespace Texy\Modules;
9

10
use Texy;
11
use Texy\HtmlElement;
12
use Texy\Regexp;
13
use function array_intersect, array_keys, array_unshift, max, reset, rtrim, str_repeat, str_replace, strtr, wordwrap;
14

15

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

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

27
        /** base indent level */
28
        public int $baseIndent = 0;
29

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

33
        /** indent space counter */
34
        private int $space = 0;
35

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

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

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

45

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

52

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

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

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

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

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

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

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

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

101

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

117
                $s = '';
1✔
118

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

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

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

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

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

148

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

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

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

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

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

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

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

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

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

198
                $open = null;
1✔
199
                $close = null;
1✔
200
                $indent = 0;
1✔
201

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

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

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

225
                        // TODO: problematic formatting of select / options, object / params
226
                }
227

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

240
                return $s;
1✔
241
        }
242

243

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

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

266
                        array_unshift($tmp, $item);
1✔
267
                }
268

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

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

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

288
                return $s;
1✔
289
        }
290

291

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

303
                        $itemTag = $item['tag'];
1✔
304

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

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

324
                return $s;
1✔
325
        }
326

327

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