b28f0fc0b26c32d87d024ffda790087214702357
[yaffs-website] / web / core / modules / rest / tests / src / Functional / XmlNormalizationQuirksTrait.php
1 <?php
2
3 namespace Drupal\Tests\rest\Functional;
4
5 /**
6  * Trait for ResourceTestBase subclasses testing $format='xml'.
7  */
8 trait XmlNormalizationQuirksTrait {
9
10   /**
11    * Applies the XML encoding quirks that remain after decoding.
12    *
13    * The XML encoding:
14    * - maps empty arrays to the empty string
15    * - maps single-item arrays to just that single item
16    * - restructures multiple-item arrays that lives in a single-item array
17    *
18    * @param array $normalization
19    *   A normalization.
20    *
21    * @return array
22    *   The updated normalization.
23    *
24    * @see \Symfony\Component\Serializer\Encoder\XmlEncoder
25    */
26   protected function applyXmlDecodingQuirks(array $normalization) {
27     foreach ($normalization as $key => $value) {
28       if ($value === [] || $value === NULL) {
29         $normalization[$key] = '';
30       }
31       elseif (is_array($value)) {
32         // Collapse single-item numeric arrays to just the single item.
33         if (count($value) === 1 && is_numeric(array_keys($value)[0]) && is_scalar($value[0])) {
34           $value = $value[0];
35         }
36         // Restructure multiple-item arrays inside a single-item numeric array.
37         // @see \Symfony\Component\Serializer\Encoder\XmlEncoder::buildXml()
38         elseif (count($value) === 1 && is_numeric(array_keys($value)[0]) && is_array(reset($value))) {
39           $rewritten_value = [];
40           foreach ($value[0] as $child_key => $child_value) {
41             if (is_numeric(array_keys(reset($value))[0])) {
42               $rewritten_value[$child_key] = ['@key' => $child_key] + $child_value;
43             }
44             else {
45               $rewritten_value[$child_key] = $child_value;
46             }
47           }
48           $value = $rewritten_value;
49         }
50
51         // If the post-quirk value is still an array after the above, recurse.
52         if (is_array($value)) {
53           $value = $this->applyXmlDecodingQuirks($value);
54         }
55
56         // Store post-quirk value.
57         $normalization[$key] = $value;
58       }
59     }
60     return $normalization;
61   }
62
63 }