Decodes a string into PHP data.
scalar $data Data to decode:
string $format Format name:
array $context options that decoders have access to.:
The format parameter specifies which format the data is in; valid values depend on the specific implementation. Authors implementing this interface are encouraged to document which formats they support in a non-inherited phpdoc comment.
mixed
Overrides DecoderInterface::decode
public function decode($data, $format, array $context = array()) {
$internalErrors = libxml_use_internal_errors(true);
$disableEntities = libxml_disable_entity_loader(true);
libxml_clear_errors();
$dom = new \DOMDocument();
$dom
->loadXML($data, LIBXML_NONET);
libxml_use_internal_errors($internalErrors);
libxml_disable_entity_loader($disableEntities);
foreach ($dom->childNodes as $child) {
if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
throw new UnexpectedValueException('Document types are not allowed.');
}
}
$xml = simplexml_import_dom($dom);
if ($error = libxml_get_last_error()) {
throw new UnexpectedValueException($error->message);
}
if (!$xml
->count()) {
if (!$xml
->attributes()) {
return (string) $xml;
}
$data = array();
foreach ($xml
->attributes() as $attrkey => $attr) {
$data['@' . $attrkey] = (string) $attr;
}
$data['#'] = (string) $xml;
return $data;
}
return $this
->parseXml($xml);
}