1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace HexMakina\Marker; |
4
|
|
|
|
5
|
|
|
class Element |
6
|
|
|
{ |
7
|
|
|
public const VOID_ELEMENTS = [ |
8
|
|
|
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', |
9
|
|
|
'link', 'meta', 'param', 'source', 'track', 'wbr' |
10
|
|
|
]; |
11
|
|
|
|
12
|
|
|
public const FORMAT_VOID = '<%s%s/>'; |
13
|
|
|
public const FORMAT_ELEMENT = '<%s%s>%s</%s>'; |
14
|
|
|
public const FORMAT_ATTRIBUTES = '%s="%s"'; |
15
|
|
|
|
16
|
|
|
|
17
|
|
|
protected string $tag; |
18
|
|
|
|
19
|
|
|
protected array $attributes; |
20
|
|
|
|
21
|
|
|
protected string $content; |
22
|
|
|
|
23
|
|
|
|
24
|
|
|
public function __construct(string $tag, string $content = null, array $attributes = []) |
25
|
|
|
{ |
26
|
|
|
$this->tag = $tag; |
27
|
|
|
$this->content = $content ?? ''; |
28
|
|
|
$this->attributes = $attributes; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function __toString() |
32
|
|
|
{ |
33
|
|
|
$ret = ''; |
34
|
|
|
$attributes = self::attributesAsString($this->attributes); |
35
|
|
|
|
36
|
|
|
if ($this->isVoid()) { |
37
|
|
|
$ret = sprintf( |
38
|
|
|
self::FORMAT_VOID, |
39
|
|
|
$this->tag, |
40
|
|
|
$attributes, |
41
|
|
|
); |
42
|
|
|
} else { |
43
|
|
|
$ret = sprintf( |
44
|
|
|
self::FORMAT_ELEMENT, |
45
|
|
|
$this->tag, |
46
|
|
|
$attributes, |
47
|
|
|
$this->content, |
48
|
|
|
$this->tag |
49
|
|
|
); |
50
|
|
|
} |
51
|
|
|
return $ret; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function isVoid(): bool |
55
|
|
|
{ |
56
|
|
|
return in_array($this->tag, self::VOID_ELEMENTS); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
|
60
|
|
|
private static function isBooleanAttribute($k): bool |
61
|
|
|
{ |
62
|
|
|
return is_int($k); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
private static function isValidValue($v): bool |
66
|
|
|
{ |
67
|
|
|
return !is_null($v) && $v != '' && !is_array($v); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public static function attributesAsString(array $attributes = []): string |
71
|
|
|
{ |
72
|
|
|
$ret = ''; |
73
|
|
|
foreach ($attributes as $k => $v) { |
74
|
|
|
if (self::isValidValue($v)) { |
75
|
|
|
$ret .= ' ' . (self::isBooleanAttribute($k) ? $v : sprintf(self::FORMAT_ATTRIBUTES, $k, $v)); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
return $ret; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|