Browse Source

YAML now supports a mostly no-op round trip to/from DOM

Changes some formatting as far as inline objects/arrays and loses comments, but should be all we need for what we're doing
master
Adam Pippin 3 years ago
parent
commit
d5a7b11b7a
  1. 10
      app/Dom/Node.php
  2. 52
      app/Serialize/Yaml.php

10
app/Dom/Node.php

@ -40,11 +40,21 @@ class Node implements \ArrayAccess, \Iterator
return $this->name;
}
public function hasName(): bool
{
return isset($this->name);
}
public function getParent(): Node
{
return $this->parent;
}
public function hasChildren(): bool
{
return sizeof($this->children) > 0;
}
public function getChildren(): array
{
return $this->children;

52
app/Serialize/Yaml.php

@ -24,10 +24,54 @@ class Yaml implements ISerialize, IUnserialize
public function serialize(Document $document): string
{
// TODO: Convert document to array
// Convert custom tags to Symfony\Component\Yaml\Tag\TaggedValue
// new TaggedValue('my_tag', ['data'=>'here'])
return SymfonyYaml::dump($data);
$data = $this->domToArray($document);
return SymfonyYaml::dump($data, 6);
}
/**
* Take a DOM node and return it turned into an array appropriate
* for serializing with the Symfony Yaml component.
*
* @param Node $node dom node to convert to array
* @return mixed
*/
protected function domToArray(Node $node)
{
$result = null;
foreach ($node as $child)
{
$child_ser = $this->serializeNode($child);
if (is_array($child_ser))
{
if (isset($result) && !is_array($result))
{
throw new \Exception('Invalid DOM: tagged value adjacent to property map');
}
$result = $result ?? [];
$result = array_merge($result, $child_ser);
}
else
{
$result = $child_ser;
}
}
return $result;
}
private function serializeNode(Node $node)
{
switch (true)
{
case $node instanceof NodeFunctionValue:
return new TaggedValue($node->getName(), $node->getValue());
case $node instanceof NodeFunction:
return new TaggedValue($node->getName(), $this->domToArray($node));
case $node instanceof NodeValue:
return $node->hasName() ? [$node->getName() => $node->getValue()] : [$node->getValue()];
default:
return $node->hasName() ? [$node->getName() => $this->domToArray($node)] : [$this->domToArray($node)];
}
throw new \Exception('Unrecognized node type: '.get_class($node));
}
protected function arrayToDom(Node $parent, array $data)

Loading…
Cancel
Save