I'm migrating the Zend\Db
driven DBAL of a Zend Framework 3 application to Doctrine. Everything is working fine, but now I got a problem with the export of data.
Before the migration it was working as follows:
There is a more or less complex data structure. The Mapper
executed some database requests and built a nested DataObject
from this data. So, the start point for the export was an object, filled with all data and having sub-objects, also with all their data. So I simply converted it to JSON
:
public function exportToJson(AbstractDataObject $dataObject)
{
return json_encode($dataObject, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
public function exportToXml(AbstractDataObject $dataObject)
{
$dataObjectVars = json_decode(json_encode($dataObject->jsonSerialize()), true);
$xml = new \SimpleXMLElement('<' . self::XML_DEFAULT_ROOT_ELEMENT . ' />');
$this->arrayToXml($dataObjectVars, $xml);
$domxml = new \DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
$domxml->loadXML($xml->asXML());
$xmlString = $domxml->saveXML();
return $xmlString;
}
protected function arrayToXml($array, &$xml)
{
foreach ($array as $key => $value) {
if(is_array($value)){
if(is_int($key)){
$key = self::XML_DEFAULT_ELEMENT_NAME;
}
$label = $xml->addChild($key);
$this->arrayToXml($value, $label);
}
else {
$xml->addChild($key, $value);
}
}
}
All DataObject
s extended the AbstractDataObject
and it provided a method, that made it easily exportable to JSON
:
class AbstractDataObject implements \JsonSerializable
{
public function jsonSerialize()
{
$reflection = new \ReflectionClass($this);
$properties = $reflection->getProperties();
$members = [];
foreach ($properties as $property) {
$property->setAccessible(true);
$members[$property->getName()] = $property->getValue($this);
}
$keys = array_keys($members);
$values = array_values($members);
$keysUnderscored = preg_replace_callback('/([A-Z])/', function($matches) {
return '_' . strtolower($matches[1]);
}, $keys);
$varsUnderscored = array_combine($keysUnderscored, $values);
return $varsUnderscored;
}
}
Now the object to export is an entity and it usually doesn't not have all its data loaded. That means, the approach described above doesn't work anymore.
Is there / What is a proper way to convert a nested entity (means an entity with its sub-entities) to a structured data format (array
/ JSON
/ XML
)?