-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathElement.php
101 lines (100 loc) · 2.82 KB
/
Element.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
namespace Web4cstj\Document;
class Element extends Node
{
public $name;
public $firstChild = null;
public $lastChild = null;
public $attributes;
public $noContent = false;
public function __construct($name = "div", $content = [])
{
$this->name = $name;
$this->attributes = [];
$this->append($content);
}
public function __toString()
{
$resultat = '';
$resultat .= '<' . $this->name;
if (count($this->attributes) > 0) {
$resultat .= ' ' . implode(' ', $this->attributes);
}
if ($this->noContent) {
$resultat .= '/>';
return $resultat;
}
$resultat .= '>';
$node = $this->firstChild;
while ($node !== null) {
$resultat .= $node;
$node = $node->nextSibling;
}
$resultat .= '</' . $this->name . '>';
return $resultat;
}
public function setAttribute($name, $value = '') {
$attribute = new Attribute($name, $value);
$attribute->ownerElement = $this;
$this->attributes[$name] = $attribute;
return $attribute;
}
public function getAttribute($name) {
if (!isset($this->attributes[$name])) {
return "";
}
return $this->attributes[$name]->value;
}
public function append($element) {
if (is_null($element)) {
return;
}
if (is_array($element)) {
foreach($element as $e) {
$this->append($e);
}
return $element;
}
if ($element instanceof Attribute) {
$element->ownerElement = $this;
$this->attributes[$element->name] = $element;
return $element;
}
if ($element instanceof Node) {
$element->remove();
if ($this->lastChild === null) {
$this->firstChild = $element;
} else {
$this->lastChild->nextSibling = $element;
}
$this->lastChild = $element;
$element->parentNode = $this;
return $element;
}
return $this->append(new TextNode("$element"));
}
static public function create($name = "div")
{
return new self($name);
}
public function children()
{
$resultat = [];
$child = $this->firstChild;
while ($child) {
$resultat[] = $child;
}
return $resultat;
}
public function clone($deep = true) {
$clone = new static($this->name);
$clone->append($this->attributes);
$clone->noContent = $this->noContent;
if ($deep) {
foreach($this->children() as $child) {
$clone->append($child->clone(true));
}
}
return $clone;
}
}