Hateoas icon indicating copy to clipboard operation
Hateoas copied to clipboard

Associative Array created in Collection Representation

Open wodka opened this issue 9 years ago • 5 comments

Hi,

when in PagerfantaFactory::createRepresentation() a new CollectionRepresentation for the current results is created.

If the current results are a Traversabe Object then it will use the function iterator_to_array -> which used the second default parameter true to include the object keys.

{
  "total": 3,
  "page": 1,
  "pages": 1,
  "limit": 100,
  "_embedded": {
    "items": {
      "document_id_1": "serialized document 1",
      "document_id_2": "serialized document 2",
      "document_id_3": "serialized document 3"
    }
  }
}

whereas I expected it to return the following:

{
  "total": 3,
  "page": 1,
  "pages": 1,
  "limit": 100,
  "_embedded": {
    "items": [
      "serialized document 1",
      "serialized document 2",
      "serialized document 3"
    ]
  }
}

change would be fairly simple:

// Hateoas/Representation/CollectionRepresentation.php:60-62
        if ($resources instanceof \Traversable) {
            $resources = iterator_to_array($resources, false);
        }

wodka avatar Mar 24 '15 11:03 wodka

I agree with this suggestion.

binidini avatar Jul 06 '15 19:07 binidini

:+1:

willdurand avatar Jul 07 '15 14:07 willdurand

I think the current behaviour is fine. If you pass an associate array, you get an json object. If you need a json array, you can do array_values(iterator_to_array($collection)).

For example, I think this will break the code of people using pomm https://github.com/chanmix51/Pomm/blob/master/Pomm/Object/BaseObject.php

adrienbrault avatar Jul 07 '15 14:07 adrienbrault

Ok, then the other way round would be to check in PagerfantaFactory:

// Hateoas/Representation/Factory/PagerfantaFactory.php:40-42
        if (null === $inline) {
            $data = $pager->getCurrentPageResults();
            if ($data instanceof \Traversable) {
                $data = iterator_to_array($data, false);
            }
            $inline = new CollectionRepresentation($data);
        }

wodka avatar Jul 08 '15 15:07 wodka

Has there been any progress on this issue? I'm hitting this problem at the moment. Is there a good workaround?

lopsided avatar May 12 '16 15:05 lopsided