85 lines
2.3 KiB
PHP
85 lines
2.3 KiB
PHP
<?php
|
|
|
|
defined('ROOT_DIR') || exit;
|
|
|
|
class DOM {
|
|
private string $tag_name;
|
|
private bool $end_tag;
|
|
private array $attributes = array();
|
|
public array $child_nodes = array();
|
|
|
|
public function __construct($tag_name, $end_tag = true)
|
|
{
|
|
$this->tag_name = $tag_name ?? "div";
|
|
$this->end_tag = $end_tag;
|
|
}
|
|
|
|
// Добавить атрибут
|
|
public function setAttribute($name, $value): bool
|
|
{
|
|
$this->attributes[$name] = $value;
|
|
return true;
|
|
}
|
|
|
|
// Вывести на экран DOM
|
|
public function view(): bool
|
|
{
|
|
echo $this->render();
|
|
return true;
|
|
}
|
|
|
|
// Отрендерить DOM
|
|
public function render(): string
|
|
{
|
|
$string_dom = "<" . $this->tag_name . $this->render_attributes() . ">";
|
|
if($this->end_tag) $string_dom .= $this->render_child();
|
|
if($this->end_tag) $string_dom .= "</". $this->tag_name . ">";
|
|
return $string_dom;
|
|
}
|
|
|
|
// Отрендерить Атрибуты DOM
|
|
private function render_attributes(): string
|
|
{
|
|
$string_attributes = "";
|
|
foreach ($this->attributes as $key => $value)
|
|
$string_attributes .= " $key='$value'";
|
|
return $string_attributes;
|
|
}
|
|
|
|
// Отрендерить дочерние DOM
|
|
private function render_child(): string
|
|
{
|
|
$string_child = "";
|
|
foreach ($this->child_nodes as $key => $value) {
|
|
if(gettype($value) == "string") {
|
|
$string_child .= $value;
|
|
continue;
|
|
}
|
|
$string_child .= $value->render();
|
|
}
|
|
return $string_child;
|
|
}
|
|
|
|
// Добавить дочерний DOM в конец
|
|
public function append($content): bool
|
|
{
|
|
if(gettype($content) != "string" && gettype($content) != "object") return false;
|
|
$this->child_nodes[] = $content;
|
|
return true;
|
|
}
|
|
|
|
// Добавить дочерний DOM в начало
|
|
public function prepend($content): bool
|
|
{
|
|
if(gettype($content) != "string" && gettype($content) != "object") return false;
|
|
array_unshift($this->child_nodes, $content);
|
|
return true;
|
|
}
|
|
|
|
// Очистить все дочерние DOM
|
|
public function clear(): bool
|
|
{
|
|
$this->child_nodes = array();
|
|
return true;
|
|
}
|
|
} |