1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\HtmlElement; |
4
|
|
|
|
5
|
|
|
class TagRenderer |
6
|
|
|
{ |
7
|
|
|
/** @var string */ |
8
|
|
|
protected $element; |
9
|
|
|
|
10
|
|
|
/** @var \Spatie\HtmlElement\Attributes */ |
11
|
|
|
protected $attributes; |
12
|
|
|
|
13
|
|
|
/** @var string */ |
14
|
|
|
protected $contents; |
15
|
|
|
|
16
|
|
|
public static function render(string $element, Attributes $attributes, string $contents) : string |
17
|
|
|
{ |
18
|
|
|
return (new static($element, $attributes, $contents))->renderTag(); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
protected function __construct(string $element, Attributes $attributes, string $contents) |
22
|
|
|
{ |
23
|
|
|
$this->element = $element; |
24
|
|
|
$this->attributes = $attributes; |
25
|
|
|
$this->contents = $contents; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
protected function renderTag() : string |
29
|
|
|
{ |
30
|
|
|
if ($this->isSelfClosingTag()) { |
31
|
|
|
return $this->renderOpeningTag(); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
return "{$this->renderOpeningTag()}{$this->contents}{$this->renderClosingTag()}"; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
protected function renderOpeningTag() : string |
38
|
|
|
{ |
39
|
|
|
return $this->attributes->isEmpty() ? |
40
|
|
|
"<{$this->element}>" : |
41
|
|
|
"<{$this->element} {$this->attributes}>"; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
protected function renderClosingTag() : string |
45
|
|
|
{ |
46
|
|
|
return "</{$this->element}>"; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
protected function isSelfClosingTag() : bool |
50
|
|
|
{ |
51
|
|
|
return in_array(strtolower($this->element), [ |
52
|
|
|
'area', 'base', 'br', 'col', 'embed', 'hr', |
53
|
|
|
'img', 'input', 'keygen', 'link', 'menuitem', |
54
|
|
|
'meta', 'param', 'source', 'track', 'wbr', |
55
|
|
|
]); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|