Skip to content

Commit 5948d51

Browse files
authored
Merge pull request #106 from AndreasHeiberg/fix-to-string-node
Fix __toString() for AST Nodes
2 parents cb40df2 + ed8bf4e commit 5948d51

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

src/Language/AST/Node.php

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,11 +81,45 @@ private function cloneValue($value)
8181
*/
8282
public function __toString()
8383
{
84-
$tmp = (array) $this;
84+
$tmp = $this->toArray();
8585
$tmp['loc'] = [
8686
'start' => $this->loc->start,
8787
'end' => $this->loc->end
8888
];
89+
8990
return json_encode($tmp);
9091
}
92+
93+
/**
94+
* @return array
95+
*/
96+
public function toArray()
97+
{
98+
$tmp = (array) $this;
99+
$tmp['loc'] = [
100+
'start' => $this->loc->start,
101+
'end' => $this->loc->end
102+
];
103+
104+
$this->recursiveToArray($tmp);
105+
106+
return $tmp;
107+
}
108+
109+
/**
110+
* @param $object
111+
*/
112+
public function recursiveToArray(&$object)
113+
{
114+
if ($object instanceof Node) {
115+
/** @var Node $object */
116+
$object = $object->toArray();
117+
} elseif (is_object($object)) {
118+
$object = (array) $object;
119+
} elseif (is_array($object)) {
120+
foreach ($object as &$o) {
121+
$this->recursiveToArray($o);
122+
}
123+
}
124+
}
91125
}

0 commit comments

Comments
 (0)