/
HtmlElement.php
120 lines (110 loc) · 2.68 KB
/
HtmlElement.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
<?php
namespace Omeka\View\Helper;
use Laminas\View\Helper\AbstractHtmlElement;
/**
* View helper for rendering a HTML element.
*/
class HtmlElement extends AbstractHtmlElement
{
/**
* @var array Cached elements and their attributes
*/
protected $elements = [];
/**
* @var string The current element
*/
protected $element;
/**
* HTML element helper
*
* @param string $element The current element
* @return self
*/
public function __invoke($element)
{
$this->element = $element;
if (!isset($this->elements[$element])) {
$this->elements[$element] = [];
}
return $this;
}
/**
* Render the element and its attributes
*
* @return string
*/
public function __toString()
{
$attributes = $this->elements[$this->element];
return '<' . $this->element . $this->htmlAttribs($attributes) . '>';
}
/**
* Set an attribute to the current element
*
* @param string $key
* @param string $value
* @return self
*/
public function setAttribute($key, $value)
{
$this->elements[$this->element][$key] = $value;
return $this;
}
/**
* Append an attribute to an element
*
* @param string $key
* @param string $value
* @return self
*/
public function appendAttribute($key, $value)
{
if (isset($this->elements[$this->element][$key])) {
$current = $this->elements[$this->element][$key];
if (is_array($current)) {
$this->elements[$this->element][$key][] = $value;
} else {
$this->elements[$this->element][$key] = [$current, $value];
}
} else {
$this->elements[$this->element][$key] = $value;
}
return $this;
}
/**
* Set attributes to the current element
*
* @param array $attributes
* @return self
*/
public function setAttributes(array $attributes)
{
foreach ($attributes as $key => $value) {
$this->setAttribute($key, $value);
}
return $this;
}
/**
* Remove an attribute from the current element
*
* @param string $key
* @return self
*/
public function removeAttribute($key)
{
unset($this->elements[$this->element][$key]);
return $this;
}
/**
* Remove all attributes from the current element
*
* @return self
*/
public function removeAttributes()
{
if (isset($this->elements[$this->element])) {
$this->elements[$this->element] = [];
}
return $this;
}
}