ytkns/src/HtmlTag.php
2020-06-10 16:03:13 +00:00

127 lines
3.8 KiB
PHP

<?php
namespace YTKNS;
class HtmlTag implements HtmlTypeInterface {
private string $tagName = 'div';
private array $attributes = [];
private array $children = [];
private bool $selfClosing = false;
public function __construct(string $tagName, array $attributes = [], $children = null) {
$this->tagName = $tagName;
foreach($attributes as $key => $val)
$this->setAttribute($key, $val);
if(is_bool($children))
$this->selfClosing = $children;
elseif(is_array($children)) {
foreach($children as $child)
if($child !== null && $child instanceof HtmlTypeInterface)
$this->appendChild($child);
}
}
public function getTagName(): string {
return $this->tagName;
}
public function getAttribute(string $name): ?string {
return $this->attributes[$name] ?? null;
}
public function setAttribute(string $name, $value): void {
if($value === null) {
$this->removeAttribute($name);
return;
}
$this->attributes[$name] = $value;
}
public function removeAttribute(string $name): void {
unset($this->attributes[$name]);
}
public function appendChild(HtmlTypeInterface $child): HtmlTypeInterface {
return $this->children[] = $child;
}
public function removeChild(HtmlTypeInterface $target): void {
$remove = [];
foreach($this->children as $child)
if($child === $target)
$remove[] = $child;
$this->children = array_diff($this->children, $remove);
}
public function setTextContent(string $textContent): void {
$this->children = [new HtmlText($textContent)];
}
public function getElementsByTagName(string $tagName): array {
$tagName = mb_strtolower($tagName);
$elements = [];
foreach($this->children as $child) {
if($child instanceof HtmlTag) {
$elements = array_merge($elements, $child->getElementsByTagName($tagName));
if(mb_strtolower($child->getTagName()) === $tagName)
$elements[] = $child;
}
}
return $elements;
}
public function getElementsByClassName(string $className): array {
$elements = [];
foreach($this->children as $child) {
if($child instanceof HtmlTag) {
$elements = array_merge($elements, $child->getElementsByClassName($className));
$classList = explode(' ', $child->getAttribute('class') ?? '');
if(in_array($className, $classList))
$elements[] = $child;
}
}
return $elements;
}
public function getElementById(string $idString): ?HtmlTag {
foreach($this->children as $child) {
if($child instanceof HtmlTag) {
if($child->getAttribute('id') == $idString)
return $child;
$element = $child->getElementById($idString);
if($element !== null)
return $element;
}
}
return null;
}
public function asHTML(): string {
$attrs = '';
$children = '';
foreach($this->attributes as $key => $val) {
$attrs .= sprintf(' %s', $key);
if($key !== $val)
$attrs .= sprintf('="%s"', htmlspecialchars($val));
}
if($this->selfClosing)
return sprintf('<%s%s/>', $this->getTagName(), $attrs);
foreach($this->children as $child)
$children .= $child->asHTML();
return sprintf('<%1$s%2$s>%3$s</%1$s>', $this->getTagName(), $attrs, $children);
}
}