Skip to content

[Serializer] Make document type nodes ignorable when decoding XML #44363

@boenner

Description

@boenner

Symfony version(s) affected

4.4, 5.3, 5.4, 6.0

Description

When decoding XML using the XmlEncoder, ignoring the document type node with the decoder_ignored_node_types option is not possible.

How to reproduce

Using the XmlEncoder with the document type node included in the ignore nodes

$xmlEncoder = new XmlEncoder();
$xml = '<?xml version="1.0"?><!DOCTYPE foobar SYSTEM "http://foo.bar"><foo>bar</foo>';
$xmlEncoder->decode($xml, 'xml', [XmlEncoder::DECODER_IGNORED_NODE_TYPES => [XML_DOCUMENT_TYPE_NODE]])

throws a NotEncodableValueException because Document types are not allowed.

Possible Solution

Consider the ignored node types before checking the current node in the decode function:

$rootNode = null;
$decoderIgnoredNodeTypes = $context[self::DECODER_IGNORED_NODE_TYPES] ?? $this->defaultContext[self::DECODER_IGNORED_NODE_TYPES];
foreach ($dom->childNodes as $child) {
    if (\in_array($child->nodeType, $decoderIgnoredNodeTypes, true)) {
        continue;
    }
    if (\XML_DOCUMENT_TYPE_NODE === $child->nodeType) {
        throw new NotEncodableValueException('Document types are not allowed.');
    }
    if (!$rootNode) {
        $rootNode = $child;
    }
}

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions