66
77use DOMDocument ;
88use DOMElement ;
9+ use DOMNode ;
910use Exception ;
1011
1112/**
@@ -74,7 +75,7 @@ class XmlBuilder
7475{
7576 protected DOMDocument $ dom ;
7677
77- protected DOMElement | DOMDocument $ currentNode ;
78+ protected DOMNode $ currentNode ;
7879
7980 public function __construct ()
8081 {
@@ -93,7 +94,7 @@ public function __get(string $tag): XmlBuilder
9394 return $ this ;
9495 }
9596
96- public function val ($ val ): self
97+ public function val (string $ val ): self
9798 {
9899 $ this ->currentNode ->nodeValue = $ val ;
99100 return $ this ;
@@ -104,6 +105,9 @@ public function val($val): self
104105 */
105106 public function attr (string $ attr , string $ val ): self
106107 {
108+ if (!$ this ->currentNode instanceof DOMElement) {
109+ throw new Exception ('Current node is not DOMElement ' );
110+ }
107111 $ this ->currentNode ->setAttribute ($ attr , $ val );
108112 return $ this ;
109113 }
@@ -113,38 +117,46 @@ public function attr(string $attr, string $val): self
113117 */
114118 public function parent (): self
115119 {
120+ if ($ this ->currentNode ->parentNode === null ) {
121+ throw new Exception ('Element has no parent ' );
122+ }
116123 $ this ->currentNode = $ this ->currentNode ->parentNode ;
117124 return $ this ;
118125 }
119126
120127 /**
121- * Traverses to parent with $name
128+ * Traverses to parent with $tagName
122129 *
123130 * @throws Exception
124131 */
125- public function parents (string $ tag ): self
132+ public function parents (string $ tagName ): self
126133 {
127134 $ traverseNode = $ this ->currentNode ;
128135 $ elFound = false ;
129136 while ($ traverseNode ->parentNode ) {
130137 $ traverseNode = $ traverseNode ->parentNode ;
131- if ($ traverseNode ->tagName === $ tag ) {
138+ if ($ traverseNode instanceof DOMElement && $ traverseNode ->tagName === $ tagName ) {
132139 $ this ->currentNode = $ traverseNode ;
133140 $ elFound = true ;
134141 break ;
135142 }
136143 }
137144
138145 if (!$ elFound ) {
139- throw new Exception ("Parent {$ tag } not found in XML " );
146+ throw new Exception ("Parent {$ tagName } not found in XML " );
140147 }
141148
142149 return $ this ;
143150 }
144151
145152 public function __toString (): string
146153 {
147- return $ this ->dom ->saveXML ();
154+ $ string = $ this ->dom ->saveXML ();
155+ if ($ string === false ) {
156+ throw new Exception ('Failed to convert DOM to string ' );
157+ }
158+
159+ return $ string ;
148160 }
149161
150162 public function getDom (): DOMDocument
0 commit comments