|
|
@ -14,6 +14,12 @@ use App\Dom\NodeFunctionValue; |
|
|
|
|
|
|
|
class Yaml implements ISerialize, IUnserialize |
|
|
|
{ |
|
|
|
/** |
|
|
|
* Convert a YAML string into a Dom\Document. |
|
|
|
* |
|
|
|
* @param string $document |
|
|
|
* @return Document |
|
|
|
*/ |
|
|
|
public function unserialize(string $document): Document |
|
|
|
{ |
|
|
|
$data = SymfonyYaml::parse($document, SymfonyYaml::PARSE_CUSTOM_TAGS); |
|
|
@ -22,6 +28,12 @@ class Yaml implements ISerialize, IUnserialize |
|
|
|
return $document; |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* Convert a Dom\Document into a YAML string. |
|
|
|
* |
|
|
|
* @param Document $document |
|
|
|
* @return string |
|
|
|
*/ |
|
|
|
public function serialize(Document $document): string |
|
|
|
{ |
|
|
|
$data = $this->domToArray($document); |
|
|
@ -58,6 +70,12 @@ class Yaml implements ISerialize, IUnserialize |
|
|
|
return $result; |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* Serialize a single node, only meant to be used as part of/by domToArray. |
|
|
|
* |
|
|
|
* @param Node $node |
|
|
|
* @return mixed |
|
|
|
*/ |
|
|
|
private function serializeNode(Node $node) |
|
|
|
{ |
|
|
|
switch (true) |
|
|
@ -71,9 +89,18 @@ class Yaml implements ISerialize, IUnserialize |
|
|
|
default: |
|
|
|
return $node->hasName() ? [$node->getName() => $this->domToArray($node)] : [$this->domToArray($node)]; |
|
|
|
} |
|
|
|
throw new \Exception('Unrecognized node type: '.get_class($node)); |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* Convert an array returned from Symfony's Yaml component when parsing a |
|
|
|
* yaml document and convert it into a Dom\Document. |
|
|
|
* |
|
|
|
* Children are pushed directly onto the passed $parent node |
|
|
|
* |
|
|
|
* @param Node $parent node that the data is to be unserialized under |
|
|
|
* @param array<mixed,mixed> $data the data to unserialize |
|
|
|
* @return void |
|
|
|
*/ |
|
|
|
protected function arrayToDom(Node $parent, array $data) |
|
|
|
{ |
|
|
|
foreach ($data as $k => $v) |
|
|
@ -93,6 +120,10 @@ class Yaml implements ISerialize, IUnserialize |
|
|
|
{ |
|
|
|
$fun_node = new NodeFunctionValue($node, $fun_name, $fun_value); |
|
|
|
} |
|
|
|
else |
|
|
|
{ |
|
|
|
throw new \Exception('Cannot unserialize value from function node--is not array or scalar'); |
|
|
|
} |
|
|
|
$node->addChild($fun_node); |
|
|
|
} |
|
|
|
else |
|
|
@ -106,6 +137,10 @@ class Yaml implements ISerialize, IUnserialize |
|
|
|
{ |
|
|
|
$node = new NodeValue($parent, is_string($k) ? $k : null, $v); |
|
|
|
} |
|
|
|
else |
|
|
|
{ |
|
|
|
throw new \Exception('Cannot unserialize value from YAML--value is not TaggedValue, array or scalar'); |
|
|
|
} |
|
|
|
} |
|
|
|
$parent->addChild($node); |
|
|
|
} |
|
|
|