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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
|
<?php
namespace ipl\Html;
use Countable;
use Exception;
use InvalidArgumentException;
use ipl\Html\Contract\Wrappable;
use RuntimeException;
/**
* HTML document
*
* An HTML document is composed of a tree of HTML nodes, i.e. text nodes and HTML elements.
*/
class HtmlDocument implements Countable, Wrappable
{
/** @var string Content separator */
protected $contentSeparator = '';
/** @var bool Whether the document has been assembled */
protected $hasBeenAssembled = false;
/** @var Wrappable Wrapper */
protected $wrapper;
/** @var Wrappable Wrapped element */
private $wrapped;
/** @var HtmlDocument The currently responsible wrapper */
private $renderedBy;
/** @var ValidHtml[] Content */
private $content = [];
/** @var array */
private $contentIndex = [];
/**
* Set the element to wrap
*
* @param Wrappable $element
*
* @return $this
*/
private function setWrapped(Wrappable $element)
{
$this->wrapped = $element;
return $this;
}
/**
* Consume the wrapped element
*
* @return Wrappable
*/
private function consumeWrapped()
{
$wrapped = $this->wrapped;
$this->wrapped = null;
return $wrapped;
}
/**
* Get the content
*
* return ValidHtml[]
*/
public function getContent()
{
return $this->content;
}
/**
* Set the content
*
* @param mixed $content
*
* @return $this
*/
public function setContent($content)
{
$this->content = [];
$this->setHtmlContent(...Html::wantHtmlList($content));
return $this;
}
/**
* Set content
*
* @param ValidHtml ...$content
*
* @return $this
*/
public function setHtmlContent(ValidHtml ...$content)
{
$this->content = [];
foreach ($content as $element) {
$this->addIndexedContent($element);
}
return $this;
}
/**
* Get the content separator
*
* @return string
*/
public function getSeparator()
{
return $this->contentSeparator;
}
/**
* Set the content separator
*
* @param string $separator
*
* @return $this
*/
public function setSeparator($separator)
{
$this->contentSeparator = $separator;
return $this;
}
/**
* Get the first {@link BaseHtmlElement} with the given tag
*
* @param string $tag
*
* @return BaseHtmlElement
*
* @throws InvalidArgumentException If no {@link BaseHtmlElement} with the given tag exists
*/
public function getFirst($tag)
{
foreach ($this->content as $c) {
if ($c instanceof BaseHtmlElement && $c->getTag() === $tag) {
return $c;
}
}
throw new InvalidArgumentException(sprintf(
'Trying to get first %s, but there is no such',
$tag
));
}
/**
* Add content
*
* @param mixed $content
*
* @return $this
*/
public function add($content)
{
$this->addHtml(...Html::wantHtmlList($content));
return $this;
}
/**
* Add content
*
* @param ValidHtml ...$content
*
* @return $this
*/
public function addHtml(ValidHtml ...$content)
{
foreach ($content as $element) {
$this->addIndexedContent($element);
}
return $this;
}
/**
* Add content from the given document
*
* @param HtmlDocument $from
* @param callable $callback Optional callback in order to transform the content to add
*
* @return $this
*/
public function addFrom(HtmlDocument $from, $callback = null)
{
$from->ensureAssembled();
$isCallable = is_callable($callback);
foreach ($from->getContent() as $item) {
$this->add($isCallable ? $callback($item) : $item);
}
return $this;
}
/**
* Check whether the given element is a direct or indirect child of this document
*
* A direct child is one that is part of this document's content. An indirect child
* is one that is either part of a direct child's content (recursively) or a wrapper
* of such (recursively).
*
* @param ValidHtml $element
*
* @return bool
*/
public function contains(ValidHtml $element)
{
$key = spl_object_hash($element);
if (array_key_exists($key, $this->contentIndex)) {
return true;
}
foreach ($this->content as $child) {
if ($child instanceof self && ($child->contains($element) || $child->wrappedBy($element))) {
return true;
}
}
return false;
}
/**
* Prepend content
*
* @param mixed $content
*
* @return $this
*/
public function prepend($content)
{
$this->prependHtml(...Html::wantHtmlList($content));
return $this;
}
/**
* Prepend content
*
* @param ValidHtml ...$content
*
* @return $this
*/
public function prependHtml(ValidHtml ...$content)
{
foreach (array_reverse($content) as $html) {
array_unshift($this->content, $html);
$this->incrementIndexKeys();
$this->addObjectPosition($html, 0);
}
return $this;
}
/**
* Remove content
*
* @param ValidHtml $html
*
* @return $this
*/
public function remove(ValidHtml $html)
{
$key = spl_object_hash($html);
if (array_key_exists($key, $this->contentIndex)) {
foreach ($this->contentIndex[$key] as $pos) {
unset($this->content[$pos]);
}
}
$this->content = array_values($this->content);
$this->reIndexContent();
return $this;
}
/**
* Ensure that the document has been assembled
*
* @return $this
*/
public function ensureAssembled()
{
if (! $this->hasBeenAssembled) {
$this->hasBeenAssembled = true;
$this->assemble();
}
return $this;
}
/**
* Get whether the document is empty
*
* @return bool
*/
public function isEmpty()
{
$this->ensureAssembled();
return empty($this->content);
}
/**
* Render the content to HTML but ignore any wrapper
*
* @return string
*/
public function renderUnwrapped()
{
$this->ensureAssembled();
$html = [];
// This **must** be consumed after the document's assembly but before rendering the content.
// If the document consumes it during assembly, nothing happens. If the document is used as
// wrapper for another element, consuming it asap prevents a left-over reference and avoids
// the element from getting rendered multiple times.
$wrapped = $this->consumeWrapped();
$content = $this->getContent();
if ($wrapped !== null && ! $this->contains($wrapped)) {
$content[] = $wrapped;
}
foreach ($content as $element) {
if ($element instanceof self) {
$element->renderedBy = $this;
}
$html[] = $element->render();
if ($element instanceof self) {
unset($element->renderedBy);
}
}
return implode($this->contentSeparator, $html);
}
public function __clone()
{
foreach ($this->content as $key => $element) {
$this->content[$key] = clone $element;
}
$this->reIndexContent();
}
/**
* Render content to HTML when treated like a string
*
* Calls {@link render()} internally in order to render the text to HTML.
* Exceptions will be automatically caught and returned as HTML string as well using {@link Error::render()}.
*
* @return string
*/
public function __toString()
{
try {
return $this->render();
} catch (Exception $e) {
return Error::render($e);
}
}
/**
* Assemble the document
*
* Override this method in order to provide content in concrete classes.
*/
protected function assemble()
{
}
/**
* Render the document to HTML respecting the set wrapper
*
* @return string
*/
protected function renderWrapped()
{
$wrapper = $this->wrapper;
if (isset($this->renderedBy)) {
if ($wrapper === $this->renderedBy || $wrapper->contains($this->renderedBy)) {
// $this might be an intermediate wrapper that's already about to be rendered.
// In case of an element (referencing $this as a wrapper) that is a child of an
// outer wrapper, it is required to ignore $wrapper as otherwise it's a loop.
// ($wrapper then is in the render path of the outer wrapper and sideways "stolen")
return $this->renderUnwrapped();
}
$wrapper->renderedBy = $this->renderedBy;
} elseif (isset($wrapper->renderedBy)) {
throw new RuntimeException('Wrapper loop detected');
} else {
$this->renderedBy = $wrapper;
}
$html = $wrapper->renderWrappedDocument($this);
if (isset($this->renderedBy)) {
if ($this->renderedBy === $wrapper) {
unset($this->renderedBy);
} elseif ($wrapper->renderedBy === $this->renderedBy) {
unset($wrapper->renderedBy);
}
}
return $html;
}
/**
* Render the given document to HTML by treating this document as the wrapper
*
* @param HtmlDocument $document
*
* @return string
*/
protected function renderWrappedDocument(HtmlDocument $document)
{
return $this->setWrapped($document)->render();
}
#[\ReturnTypeWillChange]
public function count()
{
return count($this->content);
}
public function getWrapper()
{
return $this->wrapper;
}
public function setWrapper(Wrappable $wrapper)
{
$this->wrapper = $wrapper;
return $this;
}
public function addWrapper(Wrappable $wrapper)
{
if ($this->wrapper === null) {
$this->setWrapper($wrapper);
} else {
$this->wrapper->addWrapper($wrapper);
}
return $this;
}
public function prependWrapper(Wrappable $wrapper)
{
if ($this->wrapper === null) {
$this->setWrapper($wrapper);
} else {
$wrapper->addWrapper($this->wrapper);
$this->setWrapper($wrapper);
}
return $this;
}
/**
* Check whether the given element wraps this document (recursively)
*
* @param ValidHtml $element
*
* @return bool
*/
protected function wrappedBy(ValidHtml $element)
{
if ($this->wrapper === null) {
return false;
}
if ($this->wrapper === $element || $this->wrapper->wrappedBy($element)) {
return true;
}
return false;
}
public function render()
{
$this->ensureAssembled();
if ($this->wrapper === null) {
return $this->renderUnwrapped();
} else {
return $this->renderWrapped();
}
}
private function addIndexedContent(ValidHtml $html)
{
$pos = count($this->content);
$this->content[$pos] = $html;
$this->addObjectPosition($html, $pos);
}
private function addObjectPosition(ValidHtml $html, $pos)
{
$key = spl_object_hash($html);
if (array_key_exists($key, $this->contentIndex)) {
$this->contentIndex[$key][] = $pos;
} else {
$this->contentIndex[$key] = [$pos];
}
}
private function incrementIndexKeys()
{
foreach ($this->contentIndex as & $index) {
foreach ($index as & $pos) {
$pos++;
}
}
}
private function reIndexContent()
{
$this->contentIndex = [];
foreach ($this->content as $pos => $html) {
$this->addObjectPosition($html, $pos);
}
}
}
|