Element.php
62 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPDM\__\HTML; |
| 4 | |
| 5 | class Element |
| 6 | { |
| 7 | protected string $tag; |
| 8 | protected array $attributes = []; |
| 9 | protected string $content = ''; |
| 10 | protected bool $selfClosing; |
| 11 | |
| 12 | public function __construct(string $tag, bool $selfClosing = false) |
| 13 | { |
| 14 | $this->tag = $tag; |
| 15 | $this->selfClosing = $selfClosing; |
| 16 | } |
| 17 | |
| 18 | public function attr(string $key, string $value): self |
| 19 | { |
| 20 | $this->attributes[$key] = $value; |
| 21 | return $this; |
| 22 | } |
| 23 | |
| 24 | public function attrs(array $attributes): self |
| 25 | { |
| 26 | foreach ($attributes as $key => $value) { |
| 27 | $this->attr($key, $value); |
| 28 | } |
| 29 | return $this; |
| 30 | } |
| 31 | |
| 32 | public function data(string $key, string $value): self |
| 33 | { |
| 34 | return $this->attr("data-{$key}", $value); |
| 35 | } |
| 36 | |
| 37 | public function content(string $content): self |
| 38 | { |
| 39 | $this->content = $content; |
| 40 | return $this; |
| 41 | } |
| 42 | |
| 43 | public function render(): string |
| 44 | { |
| 45 | $attrString = ''; |
| 46 | foreach ($this->attributes as $key => $value) { |
| 47 | $attrString .= " {$key}='" . htmlspecialchars($value, ENT_QUOTES) . "'"; |
| 48 | } |
| 49 | |
| 50 | if ($this->selfClosing) { |
| 51 | return "<{$this->tag}{$attrString} />"; |
| 52 | } |
| 53 | |
| 54 | return "<{$this->tag}{$attrString}>{$this->content}</{$this->tag}>"; |
| 55 | } |
| 56 | |
| 57 | public function __toString(): string |
| 58 | { |
| 59 | return $this->render(); |
| 60 | } |
| 61 | } |
| 62 |