1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace WebTheory\Html; |
4
|
|
|
|
5
|
|
|
use JsonSerializable; |
6
|
|
|
use WebTheory\Html\Contracts\HtmlInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* @deprecated version 0.2.0 |
10
|
|
|
*/ |
11
|
|
|
class HtmlMap implements HtmlInterface, JsonSerializable |
12
|
|
|
{ |
13
|
|
|
protected array $map; |
14
|
|
|
|
15
|
|
|
public function __construct(array $map) |
16
|
|
|
{ |
17
|
|
|
$this->map = $map; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Generates an html string from array of element definitions |
22
|
|
|
* |
23
|
|
|
* 'tag' => string |
24
|
|
|
* 'attributes' => array || string |
25
|
|
|
* 'content' => string |
26
|
|
|
* 'children' => array |
27
|
|
|
*/ |
28
|
|
|
protected function constructHtml(array $map = null, bool $recall = false): string |
29
|
|
|
{ |
30
|
|
|
static $markedUp; |
31
|
|
|
|
32
|
|
|
$html = ''; |
33
|
|
|
|
34
|
|
|
if (!$recall) { |
35
|
|
|
$markedUp = []; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
foreach ($map ?? $this->map as $currentElement => $definition) { |
39
|
|
|
if (in_array($currentElement, $markedUp)) { |
40
|
|
|
continue; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
// add values already existing as strings to $html as they may already exist as markup |
44
|
|
|
if (is_object($definition) && method_exists($definition, '__toString') || is_string($definition)) { |
|
|
|
|
45
|
|
|
$html .= $definition; |
46
|
|
|
$markedUp[] = $currentElement; |
47
|
|
|
|
48
|
|
|
continue; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
$html .= Html::open($definition['tag'], $definition['attributes'] ?? ''); |
|
|
|
|
52
|
|
|
$html .= $definition['content'] ?? ''; |
53
|
|
|
|
54
|
|
|
// store children in array to be passed as $html_map argument in recursive call |
55
|
|
|
if (!empty($children = $definition['children'] ?? null)) { |
56
|
|
|
foreach ($children as $child) { |
57
|
|
|
$childMap[$child] = $this->map[$child]; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$html .= $this->constructHtml($childMap, true); |
|
|
|
|
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$html .= Html::maybeClose($definition['tag']); |
64
|
|
|
$markedUp[] = $currentElement; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
// reset static variables if in initial call stack |
68
|
|
|
if (!$recall) { |
69
|
|
|
$markedUp = null; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return $html; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
public function toHtml(): string |
76
|
|
|
{ |
77
|
|
|
return $this->constructHtml(); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
public function toJson(): string |
81
|
|
|
{ |
82
|
|
|
return json_encode($this, JSON_THROW_ON_ERROR); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
public function jsonSerialize(): array |
86
|
|
|
{ |
87
|
|
|
return $this->map; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
public function __toString(): string |
91
|
|
|
{ |
92
|
|
|
return $this->toHtml(); |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|