You are here

public function XmlEncoder::decode in Zircon Profile 8

Same name in this branch
  1. 8 vendor/symfony/serializer/Encoder/XmlEncoder.php \Symfony\Component\Serializer\Encoder\XmlEncoder::decode()
  2. 8 core/modules/serialization/src/Encoder/XmlEncoder.php \Drupal\serialization\Encoder\XmlEncoder::decode()
Same name and namespace in other branches
  1. 8.0 vendor/symfony/serializer/Encoder/XmlEncoder.php \Symfony\Component\Serializer\Encoder\XmlEncoder::decode()

Decodes a string into PHP data.

Parameters

string $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.

Return value

mixed

Throws

UnexpectedValueException

Overrides DecoderInterface::decode

File

vendor/symfony/serializer/Encoder/XmlEncoder.php, line 73

Class

XmlEncoder
Encodes XML data.

Namespace

Symfony\Component\Serializer\Encoder

Code

public function decode($data, $format, array $context = array()) {
  if ('' === trim($data)) {
    throw new UnexpectedValueException('Invalid XML data, it can not be empty.');
  }
  $internalErrors = libxml_use_internal_errors(true);
  $disableEntities = libxml_disable_entity_loader(true);
  libxml_clear_errors();
  $dom = new \DOMDocument();
  $dom
    ->loadXML($data, LIBXML_NONET | LIBXML_NOBLANKS);
  libxml_use_internal_errors($internalErrors);
  libxml_disable_entity_loader($disableEntities);
  if ($error = libxml_get_last_error()) {
    libxml_clear_errors();
    throw new UnexpectedValueException($error->message);
  }
  foreach ($dom->childNodes as $child) {
    if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
      throw new UnexpectedValueException('Document types are not allowed.');
    }
  }
  $rootNode = $dom->firstChild;

  // todo: throw an exception if the root node name is not correctly configured (bc)
  if ($rootNode
    ->hasChildNodes()) {
    $xpath = new \DOMXPath($dom);
    $data = array();
    foreach ($xpath
      ->query('namespace::*', $dom->documentElement) as $nsNode) {
      $data['@' . $nsNode->nodeName] = $nsNode->nodeValue;
    }
    unset($data['@xmlns:xml']);
    if (empty($data)) {
      return $this
        ->parseXml($rootNode);
    }
    return array_merge($data, (array) $this
      ->parseXml($rootNode));
  }
  if (!$rootNode
    ->hasAttributes()) {
    return $rootNode->nodeValue;
  }
  $data = array();
  foreach ($rootNode->attributes as $attrKey => $attr) {
    $data['@' . $attrKey] = $attr->nodeValue;
  }
  $data['#'] = $rootNode->nodeValue;
  return $data;
}