dunglas/doctrine-json-odm

Normalize Collection

jbdelhommeau opened this issue · 1 comments

Hello,
I notice that the collections are also serialized with the bundle formatting.

Do you think it would be interesting to simplify the standardization of doctrine collections?

Before:

  "logCashes": {
    "keys": [
      0
    ],
    "#type": "Doctrine\\Common\\Collections\\ArrayCollection",
    "empty": false,
    "values": [
      {
        "id": 2123,
        "#type": "PepperBay\\CoreBundle\\ValueObject\\Foo",
        "label": "bar",
        "orderNum": "12345",
        "realDate": null,
        "cashStatus": "Ferme",
        "currencyAmount": 240
      }
    ],
    "iterator": {
      "#type": "ArrayIterator",
      "flags": 0,
      "arrayCopy": [
        {
          "id": 2123,
          "#type": "PepperBay\\CoreBundle\\ValueObject\\Foo",
          "label": "bar",
          "orderNum": "12345",
          "realDate": null,
          "cashStatus": "Ferme",
          "currencyAmount": 240
        }
      ]
    }
  },

After:

  "logCashes": {
    "#type": "Doctrine\\Common\\Collections\\ArrayCollection",
      "0":  {
        "id": 2123,
        "#type": "PepperBay\\CoreBundle\\ValueObject\\Foo",
        "label": "bar",
        "orderNum": "12345",
        "realDate": null,
        "cashStatus": "Ferme",
        "currencyAmount": 240
      }
  }

ObjectNormalizer.php

...
    public function normalize($object, $format = null, array $context = [])
    {
        if ($object instanceof Collection) {
            return array_merge(['#type' => ClassUtils::getClass($object)], $this->serializer->normalize(iterator_to_array($object), $format, $context));
        }

        return array_merge(['#type' => ClassUtils::getClass($object)], $this->objectNormalizer->normalize($object, $format, $context));
    }
...

Hey @jbdelhommeau, I don't think it makes sense to have an iterator serialized like that but imho that's more of an issue for the Symfony serializer rather than this type. I'm thus closing the issue, feel free to continue to comment on it and we'll see if we need to reopen :)