woohoolabs / yang

The efficient and elegant, PSR-7 compliant JSON:API 1.1 client library for PHP
MIT License
168 stars 13 forks source link

Resources with an ID of "0" disappear when using ClassHydrator #9

Closed shrink closed 6 years ago

shrink commented 6 years ago

As far as I can tell from the spec the only requirement for an ID is that it's a string, there are no limitations otherwise, so an ID of 0 is valid.

Example JSON-API response from jsonapi.org where a comment has an ID set to 0.

{
  "links": {
    "self": "http://example.com/articles",
    "next": "http://example.com/articles?page[offset]=2",
    "last": "http://example.com/articles?page[offset]=10"
  },
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON API paints my bikeshed!"
    },
    "relationships": {
      "author": {
        "links": {
          "self": "http://example.com/articles/1/relationships/author",
          "related": "http://example.com/articles/1/author"
        },
        "data": { "type": "people", "id": "9" }
      },
      "comments": {
        "links": {
          "self": "http://example.com/articles/1/relationships/comments",
          "related": "http://example.com/articles/1/comments"
        },
        "data": [
          { "type": "comments", "id": "0" },
          { "type": "comments", "id": "12" }
        ]
      }
    },
    "links": {
      "self": "http://example.com/articles/1"
    }
  }],
  "included": [{
    "type": "people",
    "id": "9",
    "attributes": {
      "first-name": "Dan",
      "last-name": "Gebhardt",
      "twitter": "dgeb"
    },
    "links": {
      "self": "http://example.com/people/9"
    }
  }, {
    "type": "comments",
    "id": "0",
    "attributes": {
      "body": "I am a comment with an ID of 0!"
    },
    "relationships": {
      "author": {
        "data": { "type": "people", "id": "2" }
      }
    },
    "links": {
      "self": "http://example.com/comments/0"
    }
  }, {
    "type": "comments",
    "id": "12",
    "attributes": {
      "body": "I like XML better"
    },
    "relationships": {
      "author": {
        "data": { "type": "people", "id": "9" }
      }
    },
    "links": {
      "self": "http://example.com/comments/12"
    }
  }]
}
$hydrator = new ClassHydrator();
$articles = $hydrator->hydrate($response->document());

foreach ($articles[0]->comments as $comment) {
   echo $comment->body . "\n";
}

You would expect to see:

I am a comment with an ID of 0!
I like XML better

Actually see:

I like XML better
kocsismate commented 6 years ago

Hi!

That was a really nice catch :) My last commit should solve the problem (https://github.com/woohoolabs/yang/commit/6a6ab89ec8592908ae453e383dd39e456852d78f). And a release with the fix is on its way.

Cheers