Verified Commit 4994bb90 authored by Cyril Vazquez's avatar Cyril Vazquez
Browse files

Add ability to export without class (lazy mode)

parent 20cd6bc4
Pipeline #7255 failed with stages
......@@ -145,6 +145,8 @@ class Document
$object = $class->newInstanceWithoutConstructor();
$importedNodesPaths = [];
foreach ($class->getProperties() as $property) {
$property->setAccessible(true);
......@@ -163,14 +165,19 @@ class Document
$value = $element->getNodePath();
break;
}
} elseif (isset($property->tags['xpath'])) {
$nodes = $this->XPath->query($property->tags['xpath'][0], $element);
$xpath = $property->tags['xpath'][0];
$nodes = $this->XPath->query($xpath, $element);
if ($nodes->length == 0) {
if (empty($nodes) || $nodes->length == 0) {
continue;
}
// Mark node as imported for additionnal properties
foreach ($nodes as $node) {
$importedNodesPaths[] = $node->getNodePath();
}
$type = $property->getType();
switch (true) {
// Scalar property type
......@@ -206,7 +213,7 @@ class Document
case ($type == 'array'):
foreach ($nodes as $node) {
$value[] = $node->nodeValue;
}
}
break;
case ($type == 'object'):
......@@ -263,6 +270,46 @@ class Document
$property->setValue($object, $value);
}
if (isset($class->tags['additionnalProperties'])) {
$childElements = $this->XPath->query('*', $element);
foreach ($childElements as $childElement) {
if (in_array($childElement->getNodePath(), $importedNodesPaths)) {
continue;
}
$name = $childElement->localName;
if (!isset($object->{$name})) {
$object->{$name} = [];
}
$object->{$name}[] = $this->lazyExportElement($childElement);
}
}
return $object;
}
protected function lazyExportElement($element)
{
$childElements = $this->XPath->query('*', $element);
if ($childElements->length == 0) {
return $element->nodeValue;
}
$object = (object) [];
foreach ($childElements as $childElement) {
$name = $childElement->localName;
if (!isset($object->{$name})) {
$object->{$name} = [];
}
$object->{$name}[] = $this->lazyExportElement($childElement);
}
return $object;
}
......@@ -270,13 +317,13 @@ class Document
* Remove empty elements and attributes
* @param DOMNode $node
*/
public function removeEmptyNodes($node=null)
{
public function removeEmptyNodes($node = null)
{
if (!$node) {
$node = $this->documentElement;
}
}
switch($node->nodeType) {
switch ($node->nodeType) {
case \XML_ELEMENT_NODE:
$childNodeList = $node->childNodes;
for ($i=$childNodeList->length-1; $i>=0; $i--) {
......@@ -296,11 +343,11 @@ class Document
break;
case \XML_TEXT_NODE:
if (ctype_space($node->nodeValue)) {
if (ctype_space($node->nodeValue)) {
//&& $node->previousSibling && $node->previousSibling->nodeType == \XML_TEXT_NODE) {
$node->nodeValue = trim($node->nodeValue);
}
break;
}
}
}
\ No newline at end of file
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment