Debian Codegraph @

vendor/ipl/html/src/HtmlDocument.php

raw
1 <?php
2
3 namespace ipl\Html;
4
5 use Countable;
6 use InvalidArgumentException;
7 use ipl\Html\Contract\MutableHtml;
8 use ipl\Html\Contract\Wrappable;
9 use ipl\Stdlib\Events;
10 use RuntimeException;
11 use Throwable;
12
13 /**
14 * HTML document
15 *
16 * An HTML document is composed of a tree of HTML nodes, i.e. text nodes and HTML elements.
17 */
18 class HtmlDocument implements Countable, Wrappable, MutableHtml
19 {
20 use Events;
21
22 /** @var string Emitted after the content has been assembled */
23 public const ON_ASSEMBLED = 'assembled';
24
25 /** @var string Content separator */
26 protected $contentSeparator = '';
27
28 /** @var bool Whether the document has been assembled */
29 protected $hasBeenAssembled = false;
30
31 /** @var ?Wrappable Wrapper */
32 protected $wrapper;
33
34 /** @var ?Wrappable Wrapped element */
35 private null|Wrappable $wrapped = null;
36
37 /** @var ?Wrappable The currently responsible wrapper */
38 private null|Wrappable $renderedBy = null;
39
40 /** @var ValidHtml[] Content */
41 private $content = [];
42
43 /** @var array */
44 private $contentIndex = [];
45
46 /**
47 * Set the element to wrap
48 *
49 * @param Wrappable $element
50 *
51 * @return $this
52 */
53 private function setWrapped(Wrappable $element)
54 {
55 $this->wrapped = $element;
56
57 return $this;
58 }
59
60 /**
61 * Consume the wrapped element
62 *
63 * @return ?Wrappable
64 */
65 private function consumeWrapped()
66 {
67 $wrapped = $this->wrapped;
68 $this->wrapped = null;
69
70 return $wrapped;
71 }
72
73 public function getContent()
74 {
75 return $this->content;
76 }
77
78 /**
79 * Set the content
80 *
81 * @param mixed $content
82 *
83 * @return $this
84 */
85 public function setContent($content)
86 {
87 $this->content = [];
88 $this->setHtmlContent(...Html::wantHtmlList($content));
89
90 return $this;
91 }
92
93 public function setHtmlContent(ValidHtml ...$content)
94 {
95 $this->content = [];
96 foreach ($content as $element) {
97 $this->addIndexedContent($element);
98 }
99
100 return $this;
101 }
102
103 /**
104 * Get the content separator
105 *
106 * @return string
107 */
108 public function getSeparator()
109 {
110 return $this->contentSeparator;
111 }
112
113 /**
114 * Set the content separator
115 *
116 * @param string $separator
117 *
118 * @return $this
119 */
120 public function setSeparator($separator)
121 {
122 $this->contentSeparator = $separator;
123
124 return $this;
125 }
126
127 /**
128 * Get the first {@link BaseHtmlElement} with the given tag
129 *
130 * @param string $tag
131 *
132 * @return BaseHtmlElement
133 *
134 * @throws InvalidArgumentException If no {@link BaseHtmlElement} with the given tag exists
135 */
136 public function getFirst($tag)
137 {
138 foreach ($this->content as $c) {
139 if ($c instanceof BaseHtmlElement && $c->getTag() === $tag) {
140 return $c;
141 }
142 }
143
144 throw new InvalidArgumentException(sprintf(
145 'Trying to get first %s, but there is no such',
146 $tag
147 ));
148 }
149
150 public function insertAfter(ValidHtml $newNode, ValidHtml $existingNode): self
151 {
152 $index = array_search($existingNode, $this->content, true);
153 if ($index === false) {
154 throw new InvalidArgumentException('The content does not contain the $existingNode');
155 }
156
157 array_splice($this->content, (int) $index + 1, 0, [$newNode]);
158
159 $this->reIndexContent();
160
161 return $this;
162 }
163
164 public function insertBefore(ValidHtml $newNode, ValidHtml $existingNode): self
165 {
166 $index = array_search($existingNode, $this->content);
167 if ($index === false) {
168 throw new InvalidArgumentException('The content does not contain the $existingNode');
169 }
170
171 array_splice($this->content, (int) $index, 0, [$newNode]);
172
173 $this->reIndexContent();
174
175 return $this;
176 }
177
178 /**
179 * Add content
180 *
181 * @param mixed $content
182 *
183 * @return $this
184 */
185 public function add($content)
186 {
187 $this->addHtml(...Html::wantHtmlList($content));
188
189 return $this;
190 }
191
192 public function addHtml(ValidHtml ...$content)
193 {
194 foreach ($content as $element) {
195 $this->addIndexedContent($element);
196 }
197
198 return $this;
199 }
200
201 /**
202 * Add content from the given document
203 *
204 * @param HtmlDocument $from
205 * @param callable $callback Optional callback in order to transform the content to add
206 *
207 * @return $this
208 */
209 public function addFrom(HtmlDocument $from, $callback = null)
210 {
211 $from->ensureAssembled();
212
213 $isCallable = is_callable($callback);
214 foreach ($from->getContent() as $item) {
215 $this->add($isCallable ? $callback($item) : $item);
216 }
217
218 return $this;
219 }
220
221 public function contains(ValidHtml $content)
222 {
223 $key = spl_object_hash($content);
224 if (array_key_exists($key, $this->contentIndex)) {
225 return true;
226 }
227
228 foreach ($this->content as $child) {
229 if ($child instanceof self && $child->contains($content)) {
230 return true;
231 }
232 }
233
234 return false;
235 }
236
237 /**
238 * Prepend content
239 *
240 * @param mixed $content
241 *
242 * @return $this
243 */
244 public function prepend($content)
245 {
246 $this->prependHtml(...Html::wantHtmlList($content));
247
248 return $this;
249 }
250
251 public function prependHtml(ValidHtml ...$content)
252 {
253 foreach (array_reverse($content) as $html) {
254 array_unshift($this->content, $html);
255 $this->incrementIndexKeys();
256 $this->addObjectPosition($html, 0);
257 }
258
259 return $this;
260 }
261
262 public function remove(ValidHtml $content)
263 {
264 $key = spl_object_hash($content);
265 if (array_key_exists($key, $this->contentIndex)) {
266 foreach ($this->contentIndex[$key] as $pos) {
267 unset($this->content[$pos]);
268 }
269 }
270 $this->content = array_values($this->content);
271
272 $this->reIndexContent();
273
274 return $this;
275 }
276
277 /**
278 * Ensure that the document has been assembled
279 *
280 * @return $this
281 */
282 public function ensureAssembled()
283 {
284 if (! $this->hasBeenAssembled) {
285 $this->hasBeenAssembled = true;
286 $this->assemble();
287
288 $this->emit(static::ON_ASSEMBLED, [$this]);
289 }
290
291 return $this;
292 }
293
294 public function isEmpty()
295 {
296 $this->ensureAssembled();
297
298 return empty($this->content);
299 }
300
301 /**
302 * Render the content to HTML but ignore any wrapper
303 *
304 * @return string
305 */
306 public function renderUnwrapped()
307 {
308 $this->ensureAssembled();
309 $html = [];
310
311 // This **must** be consumed after the document's assembly but before rendering the content.
312 // If the document consumes it during assembly, nothing happens. If the document is used as
313 // wrapper for another element, consuming it asap prevents a left-over reference and avoids
314 // the element from getting rendered multiple times.
315 $wrapped = $this->consumeWrapped();
316
317 $content = $this->getContent();
318 if ($wrapped !== null && ! $this->contains($wrapped) && ! $this->isIntermediateWrapper($wrapped)) {
319 $content[] = $wrapped;
320 }
321
322 foreach ($content as $element) {
323 if ($element instanceof self) {
324 $element->renderedBy = $this;
325 }
326
327 $html[] = $element->render();
328
329 if ($element instanceof self) {
330 $element->renderedBy = null;
331 }
332 }
333
334 return implode($this->contentSeparator, $html);
335 }
336
337 public function __clone()
338 {
339 foreach ($this->content as $key => $element) {
340 $this->content[$key] = clone $element;
341 }
342
343 $this->reIndexContent();
344 }
345
346 /**
347 * Render content to HTML when treated like a string
348 *
349 * Calls {@link render()} internally in order to render the text to HTML.
350 * Exceptions will be automatically caught and returned as HTML string as well using {@link Error::render()}.
351 *
352 * @return string
353 */
354 public function __toString()
355 {
356 try {
357 return $this->render();
358 } catch (Throwable $e) {
359 return Error::render($e);
360 }
361 }
362
363 /**
364 * Assemble the document
365 *
366 * Override this method in order to provide content in concrete classes.
367 */
368 protected function assemble()
369 {
370 }
371
372 /**
373 * Render the document to HTML respecting the set wrapper
374 *
375 * @return string
376 */
377 protected function renderWrapped()
378 {
379 $wrapper = $this->wrapper;
380
381 if (isset($this->renderedBy)) {
382 if (
383 $wrapper === $this->renderedBy
384 || ($wrapper instanceof self && $wrapper->contains($this->renderedBy))
385 ) {
386 // $this might be an intermediate wrapper that's already about to be rendered.
387 // In case of an element (referencing $this as a wrapper) that is a child of an
388 // outer wrapper, it is required to ignore $wrapper as otherwise it's a loop.
389 // ($wrapper then is in the render path of the outer wrapper and sideways "stolen")
390 return $this->renderUnwrapped();
391 }
392
393 $wrapper->renderedBy = $this->renderedBy;
394 } elseif (isset($wrapper->renderedBy)) {
395 throw new RuntimeException('Wrapper loop detected');
396 } else {
397 $this->renderedBy = $wrapper;
398 }
399
400 $html = $wrapper->renderWrappedDocument($this);
401
402 if (isset($this->renderedBy)) {
403 if ($this->renderedBy === $wrapper) {
404 $this->renderedBy = null;
405 } elseif ($wrapper->renderedBy === $this->renderedBy) {
406 $wrapper->renderedBy = null;
407 }
408 }
409
410 return $html;
411 }
412
413 /**
414 * Render the given document to HTML by treating this document as the wrapper
415 *
416 * @param HtmlDocument $document
417 *
418 * @return string
419 */
420 protected function renderWrappedDocument(HtmlDocument $document)
421 {
422 return $this->setWrapped($document)->render();
423 }
424
425 #[\ReturnTypeWillChange]
426 public function count()
427 {
428 return count($this->content);
429 }
430
431 public function getWrapper()
432 {
433 return $this->wrapper;
434 }
435
436 public function setWrapper(Wrappable $wrapper)
437 {
438 $this->wrapper = $wrapper;
439
440 return $this;
441 }
442
443 public function addWrapper(Wrappable $wrapper)
444 {
445 if ($this->wrapper === null) {
446 $this->setWrapper($wrapper);
447 } else {
448 $this->wrapper->addWrapper($wrapper);
449 }
450
451 return $this;
452 }
453
454 public function prependWrapper(Wrappable $wrapper)
455 {
456 if ($this->wrapper === null) {
457 $this->setWrapper($wrapper);
458 } else {
459 $wrapper->addWrapper($this->wrapper);
460 $this->setWrapper($wrapper);
461 }
462
463 return $this;
464 }
465
466 /**
467 * Check whether the given element wraps this document (recursively)
468 *
469 * @param ValidHtml $element
470 *
471 * @return bool
472 */
473 protected function wrappedBy(ValidHtml $element)
474 {
475 if ($this->wrapper === null) {
476 return false;
477 }
478
479 if ($this->wrapper === $element || $this->wrapper->wrappedBy($element)) {
480 return true;
481 }
482
483 return false;
484 }
485
486 /**
487 * Get whether the given element is an intermediate wrapper
488 *
489 * @param ValidHtml $element
490 *
491 * @return bool
492 */
493 protected function isIntermediateWrapper(ValidHtml $element): bool
494 {
495 foreach ($this->content as $child) {
496 if ($child instanceof self && ($child->wrappedBy($element) || $child->isIntermediateWrapper($element))) {
497 return true;
498 }
499 }
500
501 return false;
502 }
503
504 /**
505 * Last call before rendering the document
506 *
507 * @return void
508 */
509 protected function beforeRender(): void
510 {
511 }
512
513 public function render()
514 {
515 $this->ensureAssembled();
516 $this->beforeRender();
517 if ($this->wrapper === null) {
518 return $this->renderUnwrapped();
519 } else {
520 return $this->renderWrapped();
521 }
522 }
523
524 private function addIndexedContent(ValidHtml $html)
525 {
526 $pos = count($this->content);
527 $this->content[$pos] = $html;
528 $this->addObjectPosition($html, $pos);
529 }
530
531 private function addObjectPosition(ValidHtml $html, $pos)
532 {
533 $key = spl_object_hash($html);
534 if (array_key_exists($key, $this->contentIndex)) {
535 $this->contentIndex[$key][] = $pos;
536 } else {
537 $this->contentIndex[$key] = [$pos];
538 }
539 }
540
541 private function incrementIndexKeys()
542 {
543 foreach ($this->contentIndex as & $index) {
544 foreach ($index as & $pos) {
545 $pos++;
546 }
547 }
548 }
549
550 private function reIndexContent()
551 {
552 $this->contentIndex = [];
553 foreach ($this->content as $pos => $html) {
554 $this->addObjectPosition($html, $pos);
555 }
556 }
557 }