-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIndenter.php
288 lines (243 loc) · 8.94 KB
/
Indenter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
<?php
/**
* Qubus\Support
*
* @link https://github.com/QubusPHP/support
* @copyright 2022
* @author Joshua Parker <[email protected]>
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
/**
* @see https://github.com/gajus/dindent for the canonical source repository
*
* @license https://github.com/gajus/dindent/blob/master/LICENSE BSD 3-Clause
*/
declare(strict_types=1);
namespace Qubus\Support;
use Qubus\Exception\Data\TypeException;
use RuntimeException;
final class Indenter
{
public const ELEMENT_TYPE_BLOCK = 0;
public const ELEMENT_TYPE_INLINE = 1;
public const MATCH_INDENT_NO = 0;
public const MATCH_INDENT_DECREASE = 1;
public const MATCH_INDENT_INCREASE = 2;
public const MATCH_DISCARD = 3;
/** @var array $log */
private array $log = [];
/** @var array $options */
private array $options = [
'indentation_character' => ' '
];
/** @var array $inlineElements */
private array $inlineElements = [
'b',
'big',
'i',
'small',
'tt',
'abbr',
'acronym',
'cite',
'code',
'dfn',
'em',
'kbd',
'strong',
'samp',
'var',
'a',
'bdo',
'br',
'img',
'span',
'sub',
'sup',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'h7',
'button',
'input',
'label',
'map',
'object',
'output',
'q',
'select',
'small',
'time',
];
/** @var array $ignoreElements */
private array $ignoreElements = ['pre', 'script', 'textarea'];
/** @var array $temporaryReplacementsScript */
private array $temporaryReplacementsScript = [];
/** @var array $temporaryReplacementsIgnore */
private array $temporaryReplacementsIgnore = [];
/** @var array $temporaryReplacementsInline */
private array $temporaryReplacementsInline = [];
/**
* @param array $options
* @throws TypeException
*/
public function __construct(array $options = [])
{
foreach ($options as $name => $value) {
if (!array_key_exists($name, $this->options)) {
throw new TypeException('Unrecognized option.');
}
$this->options[$name] = $value;
}
}
/**
* @param string $elementName Element name, e.g. "b".
* @param Indenter::ELEMENT_TYPE_BLOCK|Indenter::ELEMENT_TYPE_INLINE $type
* @return void
* @throws TypeException
*/
public function setElementType(string $elementName, $type): void
{
if ($type === Indenter::ELEMENT_TYPE_BLOCK) {
$this->inlineElements = array_diff($this->inlineElements, [$elementName]);
} elseif ($type === Indenter::ELEMENT_TYPE_INLINE) {
$this->inlineElements[] = $elementName;
} else {
throw new TypeException('Unrecognized element type.');
}
$this->inlineElements = array_unique($this->inlineElements);
}
/**
* @param string|null $input HTML input.
* @return string Indented HTML.
*/
public function indent(?string $input = null): string
{
if (null === $input) {
return '';
}
$this->log = [];
// Indenter does not indent. Instead, it temporarily removes it from the code, indents the input,
// and restores the script body.
foreach ($this->ignoreElements as $key) {
if (preg_match_all('/<' . $key . '\b[^>]*>([\s\S]*?)<\/' . $key . '>/mi', $input, $matches)) {
$this->temporaryReplacementsIgnore[$key] = $matches[0];
foreach ($matches[0] as $i => $match) {
$input = str_replace($match, '<' . $key . '>' . ($i + 1) . '</' . $key . '>', $input);
}
}
}
// Indenter does not indent <script> body. Instead, it temporary removes it from the code,
// indents the input, and restores the script body.
if (preg_match_all('/<script\b[^>]*>([\s\S]*?)<\/script>/mi', $input, $matches)) {
$this->temporaryReplacementsScript = $matches[0];
foreach ($matches[0] as $i => $match) {
$input = str_replace($match, '<script>' . ($i + 1) . '</script>', $input);
}
}
// Removing double whitespaces to make the source code easier to read.
// With the exception of <pre>/ CSS white-space changing the default behaviour, double whitespace
// is meaningless in HTML output.
// This reason alone is sufficient not to use Indenter in production.
$input = str_replace("\t", '', $input);
$input = preg_replace('/\s{2,}/u', ' ', $input);
// Remove inline elements and replace them with text entities.
if (preg_match_all('/<(' . implode('|', $this->inlineElements) . ')[^>]*>(?:[^<]*)<\/\1>/', $input, $matches)) {
$this->temporaryReplacementsInline = $matches[0];
foreach ($matches[0] as $i => $match) {
$input = str_replace($match, 'ᐃ' . ($i + 1) . 'ᐃ', $input);
}
}
$subject = $input;
$output = '';
$nextLineIndentationLevel = 0;
do {
$indentationLevel = $nextLineIndentationLevel;
$patterns = [
// block tag
'/^(<([a-z]+)(?:[^>]*)>(?:[^<]*)<\/(?:\2)>)/' => Indenter::MATCH_INDENT_NO,
// DOCTYPE
'/^<!([^>]*)>/' => Indenter::MATCH_INDENT_NO,
// tag with implied closing
'/^<(input|link|meta|base|br|img|source|hr)([^>]*)>/' => Indenter::MATCH_INDENT_NO,
// self closing SVG tags
'/^<(animate|stop|path|circle|line|polyline|rect|use)([^>]*)\/>/' => Indenter::MATCH_INDENT_NO,
// opening tag
'/^<[^\/]([^>]*)>/' => Indenter::MATCH_INDENT_INCREASE,
// closing tag
'/^<\/([^>]*)>/' => Indenter::MATCH_INDENT_DECREASE,
// self-closing tag
'/^<(.+)\/>/' => Indenter::MATCH_INDENT_DECREASE,
// whitespace
'/^(\s+)/' => Indenter::MATCH_DISCARD,
// text node
'/([^<]+)/' => Indenter::MATCH_INDENT_NO
];
$rules = ['NO', 'DECREASE', 'INCREASE', 'DISCARD'];
foreach ($patterns as $pattern => $rule) {
if ($match = preg_match($pattern, $subject, $matches)) {
$this->log[] = [
'rule' => $rules[$rule],
'pattern' => $pattern,
'subject' => $subject,
'match' => $matches[0]
];
$subject = mb_substr($subject, mb_strlen($matches[0]));
if ($rule === Indenter::MATCH_DISCARD) {
break;
}
if ($rule === Indenter::MATCH_INDENT_NO) {
// do nothing
} elseif ($rule === Indenter::MATCH_INDENT_DECREASE) {
$nextLineIndentationLevel--;
$indentationLevel--;
} else {
$nextLineIndentationLevel++;
}
if ($indentationLevel < 0) {
$indentationLevel = 0;
}
$output .= str_repeat(
$this->options['indentation_character'],
$indentationLevel
) . $matches[0] . "\n";
break;
}
}
} while ($match);
$interpretedInput = '';
foreach ($this->log as $e) {
$interpretedInput .= $e['match'];
}
if ($interpretedInput !== $input) {
throw new RuntimeException('Did not reproduce the exact input.');
}
$output = preg_replace('/(<(\w+)[^>]*>)\s*(<\/\2>)/u', '\\1\\3', $output);
foreach ($this->ignoreElements as $key) {
if (isset($this->temporaryReplacementsIgnore[$key])) {
foreach ($this->temporaryReplacementsIgnore[$key] as $i => $original) {
$output = str_replace('<' . $key . '>' . ($i + 1) . '</' . $key . '>', $original, $output);
}
}
}
foreach ($this->temporaryReplacementsScript as $i => $original) {
$output = str_replace('<script>' . ($i + 1) . '</script>', $original, $output);
}
foreach ($this->temporaryReplacementsInline as $i => $original) {
$output = str_replace('ᐃ' . ($i + 1) . 'ᐃ', $original, $output);
}
return trim($output);
}
/**
* Debugging utility. Get log for the last indent operation.
*
* @return array
*/
public function getLog(): array
{
return $this->log;
}
}