Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Encoder/XmlEncoder.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Serializer\Encoder;
13
14 use Symfony\Component\Serializer\Exception\BadMethodCallException;
15 use Symfony\Component\Serializer\Exception\NotEncodableValueException;
16 use Symfony\Component\Serializer\SerializerAwareInterface;
17 use Symfony\Component\Serializer\SerializerAwareTrait;
18
19 /**
20 * @author Jordi Boggiano <[email protected]>
21 * @author John Wards <[email protected]>
22 * @author Fabian Vogler <[email protected]>
23 * @author Kévin Dunglas <[email protected]>
24 * @author Dany Maillard <[email protected]>
25 */
26 class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwareInterface, SerializerAwareInterface
27 {
28 use SerializerAwareTrait;
29
30 public const FORMAT = 'xml';
31
32 public const AS_COLLECTION = 'as_collection';
33
34 /**
35 * An array of ignored XML node types while decoding, each one of the DOM Predefined XML_* constants.
36 */
37 public const DECODER_IGNORED_NODE_TYPES = 'decoder_ignored_node_types';
38
39 /**
40 * An array of ignored XML node types while encoding, each one of the DOM Predefined XML_* constants.
41 */
42 public const ENCODER_IGNORED_NODE_TYPES = 'encoder_ignored_node_types';
43 public const ENCODING = 'xml_encoding';
44 public const FORMAT_OUTPUT = 'xml_format_output';
45
46 /**
47 * A bit field of LIBXML_* constants for loading XML documents.
48 */
49 public const LOAD_OPTIONS = 'load_options';
50
51 /**
52 * A bit field of LIBXML_* constants for saving XML documents.
53 */
54 public const SAVE_OPTIONS = 'save_options';
55
56 public const REMOVE_EMPTY_TAGS = 'remove_empty_tags';
57 public const ROOT_NODE_NAME = 'xml_root_node_name';
58 public const STANDALONE = 'xml_standalone';
59 public const TYPE_CAST_ATTRIBUTES = 'xml_type_cast_attributes';
60 public const VERSION = 'xml_version';
61 public const CDATA_WRAPPING = 'cdata_wrapping';
62 public const CDATA_WRAPPING_NAME_PATTERN = 'cdata_wrapping_name_pattern';
63 public const CDATA_WRAPPING_PATTERN = 'cdata_wrapping_pattern';
64 public const IGNORE_EMPTY_ATTRIBUTES = 'ignore_empty_attributes';
65 public const PRESERVE_NUMERIC_KEYS = 'preserve_numeric_keys';
66
67 private array $defaultContext = [
68 self::AS_COLLECTION => false,
69 self::DECODER_IGNORED_NODE_TYPES => [\XML_PI_NODE, \XML_COMMENT_NODE],
70 self::ENCODER_IGNORED_NODE_TYPES => [],
71 self::LOAD_OPTIONS => \LIBXML_NONET | \LIBXML_NOBLANKS,
72 self::SAVE_OPTIONS => 0,
73 self::REMOVE_EMPTY_TAGS => false,
74 self::ROOT_NODE_NAME => 'response',
75 self::TYPE_CAST_ATTRIBUTES => true,
76 self::CDATA_WRAPPING => true,
77 self::CDATA_WRAPPING_NAME_PATTERN => false,
78 self::CDATA_WRAPPING_PATTERN => '/[<>&]/',
79 self::IGNORE_EMPTY_ATTRIBUTES => false,
80 self::PRESERVE_NUMERIC_KEYS => false,
81 ];
82
83 public function __construct(array $defaultContext = [])
84 {
85 $this->defaultContext = array_merge($this->defaultContext, $defaultContext);
86 }
87
88 public function encode(mixed $data, string $format, array $context = []): string
89 {
90 $encoderIgnoredNodeTypes = $context[self::ENCODER_IGNORED_NODE_TYPES] ?? $this->defaultContext[self::ENCODER_IGNORED_NODE_TYPES];
91 $ignorePiNode = \in_array(\XML_PI_NODE, $encoderIgnoredNodeTypes, true);
92 if ($data instanceof \DOMDocument) {
93 return $this->saveXml($data, $ignorePiNode ? $data->documentElement : null);
94 }
95
96 $xmlRootNodeName = $context[self::ROOT_NODE_NAME] ?? $this->defaultContext[self::ROOT_NODE_NAME];
97
98 $dom = $this->createDomDocument($context);
99
100 if (null !== $data && !\is_scalar($data)) {
101 $root = $dom->createElement($xmlRootNodeName);
102 $dom->appendChild($root);
103 $this->buildXml($root, $data, $format, $context, $xmlRootNodeName);
104 } else {
105 $this->appendNode($dom, $data, $format, $context, $xmlRootNodeName);
106 }
107
108 return $this->saveXml($dom, $ignorePiNode ? $dom->documentElement : null, $context[self::SAVE_OPTIONS] ?? $this->defaultContext[self::SAVE_OPTIONS]);
109 }
110
111 public function decode(string $data, string $format, array $context = []): mixed
112 {
113 if ('' === trim($data)) {
114 throw new NotEncodableValueException('Invalid XML data, it cannot be empty.');
115 }
116
117 $internalErrors = libxml_use_internal_errors(true);
118 libxml_clear_errors();
119
120 $dom = new \DOMDocument();
121 $dom->loadXML($data, $context[self::LOAD_OPTIONS] ?? $this->defaultContext[self::LOAD_OPTIONS]);
122
123 libxml_use_internal_errors($internalErrors);
124
125 if ($error = libxml_get_last_error()) {
126 libxml_clear_errors();
127
128 throw new NotEncodableValueException($error->message);
129 }
130
131 $rootNode = null;
132 $decoderIgnoredNodeTypes = $context[self::DECODER_IGNORED_NODE_TYPES] ?? $this->defaultContext[self::DECODER_IGNORED_NODE_TYPES];
133 foreach ($dom->childNodes as $child) {
134 if (\in_array($child->nodeType, $decoderIgnoredNodeTypes, true)) {
135 continue;
136 }
137 if (\XML_DOCUMENT_TYPE_NODE === $child->nodeType) {
138 throw new NotEncodableValueException('Document types are not allowed.');
139 }
140 if (!$rootNode) {
141 $rootNode = $child;
142 }
143 }
144
145 // todo: throw an exception if the root node name is not correctly configured (bc)
146
147 if ($rootNode->hasChildNodes()) {
148 $data = $this->parseXml($rootNode, $context);
149 if (\is_array($data)) {
150 $data = $this->addXmlNamespaces($data, $rootNode, $dom);
151 }
152
153 return $data;
154 }
155
156 if (!$rootNode->hasAttributes()) {
157 return $rootNode->nodeValue;
158 }
159
160 $data = array_merge($this->parseXmlAttributes($rootNode, $context), ['#' => $rootNode->nodeValue]);
161
162 return $this->addXmlNamespaces($data, $rootNode, $dom);
163 }
164
165 public function supportsEncoding(string $format): bool
166 {
167 return self::FORMAT === $format;
168 }
169
170 public function supportsDecoding(string $format): bool
171 {
172 return self::FORMAT === $format;
173 }
174
175 final protected function appendXMLString(\DOMNode $node, string $val): bool
176 {
177 if ('' !== $val) {
178 $frag = $node->ownerDocument->createDocumentFragment();
179 $frag->appendXML($val);
180 $node->appendChild($frag);
181
182 return true;
183 }
184
185 return false;
186 }
187
188 final protected function appendText(\DOMNode $node, string $val): bool
189 {
190 $nodeText = $node->ownerDocument->createTextNode($val);
191 $node->appendChild($nodeText);
192
193 return true;
194 }
195
196 final protected function appendCData(\DOMNode $node, string $val): bool
197 {
198 $nodeText = $node->ownerDocument->createCDATASection($val);
199 $node->appendChild($nodeText);
200
201 return true;
202 }
203
204 final protected function appendDocumentFragment(\DOMNode $node, \DOMDocumentFragment $fragment): bool
205 {
206 $node->appendChild($fragment);
207
208 return true;
209 }
210
211 final protected function appendComment(\DOMNode $node, string $data): bool
212 {
213 $node->appendChild($node->ownerDocument->createComment($data));
214
215 return true;
216 }
217
218 /**
219 * Checks the name is a valid xml element name.
220 */
221 final protected function isElementNameValid(string $name): bool
222 {
223 return $name
224 && !str_contains($name, ' ')
225 && preg_match('#^[\pL_][\pL0-9._:-]*$#ui', $name);
226 }
227
228 /**
229 * Parse the input DOMNode into an array or a string.
230 */
231 private function parseXml(\DOMNode $node, array $context = []): array|string
232 {
233 $data = $this->parseXmlAttributes($node, $context);
234
235 $value = $this->parseXmlValue($node, $context);
236
237 if (!\count($data)) {
238 return $value;
239 }
240
241 if (!\is_array($value)) {
242 $data['#'] = $value;
243
244 return $data;
245 }
246
247 if (1 === \count($value) && key($value)) {
248 $data[key($value)] = current($value);
249
250 return $data;
251 }
252
253 foreach ($value as $key => $val) {
254 $data[$key] = $val;
255 }
256
257 return $data;
258 }
259
260 /**
261 * Parse the input DOMNode attributes into an array.
262 */
263 private function parseXmlAttributes(\DOMNode $node, array $context = []): array
264 {
265 if (!$node->hasAttributes()) {
266 return [];
267 }
268
269 $data = [];
270 $typeCastAttributes = (bool) ($context[self::TYPE_CAST_ATTRIBUTES] ?? $this->defaultContext[self::TYPE_CAST_ATTRIBUTES]);
271
272 foreach ($node->attributes as $attr) {
273 if (!is_numeric($attr->nodeValue) || !$typeCastAttributes || (isset($attr->nodeValue[1]) && '0' === $attr->nodeValue[0] && '.' !== $attr->nodeValue[1])) {
274 $data['@'.$attr->nodeName] = $attr->nodeValue;
275
276 continue;
277 }
278
279 if (false !== $val = filter_var($attr->nodeValue, \FILTER_VALIDATE_INT)) {
280 $data['@'.$attr->nodeName] = $val;
281
282 continue;
283 }
284
285 $data['@'.$attr->nodeName] = (float) $attr->nodeValue;
286 }
287
288 return $data;
289 }
290
291 /**
292 * Parse the input DOMNode value (content and children) into an array or a string.
293 */
294 private function parseXmlValue(\DOMNode $node, array $context = []): array|string
295 {
296 if (!$node->hasChildNodes()) {
297 return $node->nodeValue;
298 }
299
300 if (1 === $node->childNodes->length && \in_array($node->firstChild->nodeType, [\XML_TEXT_NODE, \XML_CDATA_SECTION_NODE], true)) {
301 return $node->firstChild->nodeValue;
302 }
303
304 $value = [];
305 $decoderIgnoredNodeTypes = $context[self::DECODER_IGNORED_NODE_TYPES] ?? $this->defaultContext[self::DECODER_IGNORED_NODE_TYPES];
306 foreach ($node->childNodes as $subnode) {
307 if (\in_array($subnode->nodeType, $decoderIgnoredNodeTypes, true)) {
308 continue;
309 }
310
311 $val = $this->parseXml($subnode, $context);
312
313 if ('item' === $subnode->nodeName && isset($val['@key'])) {
314 $value[$val['@key']] = $val['#'] ?? $val;
315 } else {
316 $value[$subnode->nodeName][] = $val;
317 }
318 }
319
320 $asCollection = $context[self::AS_COLLECTION] ?? $this->defaultContext[self::AS_COLLECTION];
321 foreach ($value as $key => $val) {
322 if (!$asCollection && \is_array($val) && 1 === \count($val)) {
323 $value[$key] = current($val);
324 }
325 }
326
327 return $value;
328 }
329
330 private function addXmlNamespaces(array $data, \DOMNode $node, \DOMDocument $document): array
331 {
332 $xpath = new \DOMXPath($document);
333
334 foreach ($xpath->query('namespace::*', $node) as $nsNode) {
335 $data['@'.$nsNode->nodeName] = $nsNode->nodeValue;
336 }
337
338 unset($data['@xmlns:xml']);
339
340 return $data;
341 }
342
343 /**
344 * Parse the data and convert it to DOMElements.
345 *
346 * @throws NotEncodableValueException
347 */
348 private function buildXml(\DOMNode $parentNode, mixed $data, string $format, array $context, ?string $xmlRootNodeName = null): bool
349 {
350 $append = true;
351 $removeEmptyTags = $context[self::REMOVE_EMPTY_TAGS] ?? $this->defaultContext[self::REMOVE_EMPTY_TAGS] ?? false;
352 $preserveNumericKeys = $context[self::PRESERVE_NUMERIC_KEYS] ?? $this->defaultContext[self::PRESERVE_NUMERIC_KEYS] ?? false;
353 $encoderIgnoredNodeTypes = $context[self::ENCODER_IGNORED_NODE_TYPES] ?? $this->defaultContext[self::ENCODER_IGNORED_NODE_TYPES];
354
355 if (\is_array($data) || ($data instanceof \Traversable && (null === $this->serializer || !$this->serializer->supportsNormalization($data, $format)))) {
356 foreach ($data as $key => $data) {
357 // Ah this is the magic @ attribute types.
358 if (str_starts_with($key, '@') && $this->isElementNameValid($attributeName = substr($key, 1))) {
359 if (!\is_scalar($data)) {
360 $data = $this->serializer->normalize($data, $format, $context);
361 }
362 if (\is_bool($data)) {
363 $data = (int) $data;
364 }
365
366 if ($context[self::IGNORE_EMPTY_ATTRIBUTES] ?? $this->defaultContext[self::IGNORE_EMPTY_ATTRIBUTES]) {
367 if (null === $data || '' === $data) {
368 continue;
369 }
370 }
371
372 $parentNode->setAttribute($attributeName, $data);
373 } elseif ('#' === $key) {
374 $append = $this->selectNodeType($parentNode, $data, $format, $context);
375 } elseif ('#comment' === $key) {
376 if (!\in_array(\XML_COMMENT_NODE, $encoderIgnoredNodeTypes, true)) {
377 $append = $this->appendComment($parentNode, $data);
378 }
379 } elseif (\is_array($data) && !is_numeric($key)) {
380 // Is this array fully numeric keys?
381 if (!$preserveNumericKeys && $data && null === array_find_key($data, static fn ($v, $k) => \is_string($k))) {
382 /*
383 * Create nodes to append to $parentNode based on the $key of this array
384 * Produces <xml><item>0</item><item>1</item></xml>
385 * From ["item" => [0,1]];.
386 */
387 foreach ($data as $subData) {
388 $append = $this->appendNode($parentNode, $subData, $format, $context, $key);
389 }
390 } else {
391 $append = $this->appendNode($parentNode, $data, $format, $context, $key);
392 }
393 } elseif (is_numeric($key) || !$this->isElementNameValid($key)) {
394 $append = $this->appendNode($parentNode, $data, $format, $context, 'item', $key);
395 } elseif (null !== $data || !$removeEmptyTags) {
396 $append = $this->appendNode($parentNode, $data, $format, $context, $key);
397 }
398 }
399
400 return $append;
401 }
402
403 if (\is_object($data)) {
404 if (null === $this->serializer) {
405 throw new BadMethodCallException(\sprintf('The serializer needs to be set to allow "%s()" to be used with object data.', __METHOD__));
406 }
407
408 $data = $this->serializer->normalize($data, $format, $context);
409 if (null !== $data && !\is_scalar($data)) {
410 return $this->buildXml($parentNode, $data, $format, $context, $xmlRootNodeName);
411 }
412
413 // top level data object was normalized into a scalar
414 if (!$parentNode->parentNode->parentNode) {
415 $root = $parentNode->parentNode;
416 $root->removeChild($parentNode);
417
418 return $this->appendNode($root, $data, $format, $context, $xmlRootNodeName);
419 }
420
421 return $this->appendNode($parentNode, $data, $format, $context, 'data');
422 }
423
424 throw new NotEncodableValueException('An unexpected value could not be serialized: '.(!\is_resource($data) ? var_export($data, true) : \sprintf('%s resource', get_resource_type($data))));
425 }
426
427 /**
428 * Selects the type of node to create and appends it to the parent.
429 */
430 private function appendNode(\DOMNode $parentNode, mixed $data, string $format, array $context, string $nodeName, ?string $key = null): bool
431 {
432 $dom = $parentNode instanceof \DOMDocument ? $parentNode : $parentNode->ownerDocument;
433 $node = $dom->createElement($nodeName);
434 if (null !== $key) {
435 $node->setAttribute('key', $key);
436 }
437 $appendNode = $this->selectNodeType($node, $data, $format, $context);
438 // we may have decided not to append this node, either in error or if its $nodeName is not valid
439 if ($appendNode) {
440 $parentNode->appendChild($node);
441 }
442
443 return $appendNode;
444 }
445
446 /**
447 * Checks if a value contains any characters which would require CDATA wrapping.
448 *
449 * @param array<string, mixed> $context
450 */
451 private function needsCdataWrapping(string $name, string $val, array $context): bool
452 {
453 return ($context[self::CDATA_WRAPPING] ?? $this->defaultContext[self::CDATA_WRAPPING])
454 && (preg_match($context[self::CDATA_WRAPPING_PATTERN] ?? $this->defaultContext[self::CDATA_WRAPPING_PATTERN], $val)
455 || (($context[self::CDATA_WRAPPING_NAME_PATTERN] ?? $this->defaultContext[self::CDATA_WRAPPING_NAME_PATTERN]) && preg_match($context[self::CDATA_WRAPPING_NAME_PATTERN] ?? $this->defaultContext[self::CDATA_WRAPPING_NAME_PATTERN], $name))
456 );
457 }
458
459 /**
460 * Tests the value being passed and decide what sort of element to create.
461 *
462 * @throws NotEncodableValueException
463 */
464 private function selectNodeType(\DOMNode $node, mixed $val, string $format, array $context): bool
465 {
466 if (\is_array($val)) {
467 return $this->buildXml($node, $val, $format, $context);
468 } elseif ($val instanceof \SimpleXMLElement) {
469 $child = $node->ownerDocument->importNode(dom_import_simplexml($val), true);
470 $node->appendChild($child);
471 } elseif ($val instanceof \Traversable) {
472 $this->buildXml($node, $val, $format, $context);
473 } elseif ($val instanceof \DOMNode) {
474 $child = $node->ownerDocument->importNode($val, true);
475 $node->appendChild($child);
476 } elseif (\is_object($val)) {
477 if (null === $this->serializer) {
478 throw new BadMethodCallException(\sprintf('The serializer needs to be set to allow "%s()" to be used with object data.', __METHOD__));
479 }
480
481 return $this->selectNodeType($node, $this->serializer->normalize($val, $format, $context), $format, $context);
482 } elseif (is_numeric($val)) {
483 return $this->appendText($node, is_nan($val) ? 'NAN' : (string) $val);
484 } elseif (\is_string($val) && $this->needsCdataWrapping($node->nodeName, $val, $context)) {
485 return $this->appendCData($node, $val);
486 } elseif (\is_string($val)) {
487 return $this->appendText($node, $val);
488 } elseif (\is_bool($val)) {
489 return $this->appendText($node, (int) $val);
490 }
491
492 return true;
493 }
494
495 /**
496 * Create a DOM document, taking serializer options into account.
497 */
498 private function createDomDocument(array $context): \DOMDocument
499 {
500 $document = new \DOMDocument();
501
502 // Set an attribute on the DOM document specifying, as part of the XML declaration,
503 $xmlOptions = [
504 // nicely formats output with indentation and extra space
505 self::FORMAT_OUTPUT => 'formatOutput',
506 // the version number of the document
507 self::VERSION => 'xmlVersion',
508 // the encoding of the document
509 self::ENCODING => 'encoding',
510 // whether the document is standalone
511 self::STANDALONE => 'xmlStandalone',
512 ];
513 foreach ($xmlOptions as $xmlOption => $documentProperty) {
514 if ($contextOption = $context[$xmlOption] ?? $this->defaultContext[$xmlOption] ?? false) {
515 $document->$documentProperty = $contextOption;
516 }
517 }
518
519 return $document;
520 }
521
522 /**
523 * @throws NotEncodableValueException
524 */
525 private function saveXml(\DOMDocument $document, ?\DOMNode $node = null, ?int $options = null): string
526 {
527 $prevErrorHandler = set_error_handler(static function ($type, $message, $file, $line, $context = []) use (&$prevErrorHandler) {
528 if (\E_ERROR === $type || \E_WARNING === $type) {
529 throw new NotEncodableValueException($message);
530 }
531
532 return $prevErrorHandler ? $prevErrorHandler($type, $message, $file, $line, $context) : false;
533 });
534 try {
535 return $document->saveXML($node, $options);
536 } finally {
537 restore_error_handler();
538 }
539 }
540 }