3 namespace Drupal\Tests\rest\Functional;
6 * Trait for ResourceTestBase subclasses testing $format='xml'.
8 trait XmlNormalizationQuirksTrait {
11 * Applies the XML encoding quirks that remain after decoding.
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
18 * @param array $normalization
22 * The updated normalization.
24 * @see \Symfony\Component\Serializer\Encoder\XmlEncoder
26 protected function applyXmlDecodingQuirks(array $normalization) {
27 foreach ($normalization as $key => $value) {
28 if ($value === [] || $value === NULL) {
29 $normalization[$key] = '';
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])) {
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;
45 $rewritten_value[$child_key] = $child_value;
48 $value = $rewritten_value;
51 // If the post-quirk value is still an array after the above, recurse.
52 if (is_array($value)) {
53 $value = $this->applyXmlDecodingQuirks($value);
56 // Store post-quirk value.
57 $normalization[$key] = $value;
60 return $normalization;