/** * @param ResourceCollection $collection * @param array $data * @return ResourceCollection */ protected function hydrateCollection(ResourceCollection $collection, array $data) { foreach ($data['data'] as $resourceData) { $instance = clone $collection->getHydrationResource(); // if (!isset($resourceData[self::KEY_RECURSION])) { $instance = $this->hydrateResource($instance, $resourceData); // } $collection->add($instance); } return $collection; }
/** * Expects the depth of the dehydration to be respected. * * @test */ public function validateDehydrateRespectsDepthLevel() { $artist = ArtistResourceMock::create(1); $artist->setName('Fightstar'); $artist->setAlbums($albums = new ResourceCollection()); $albums->add($album = AlbumResourceMock::create(100)); $album->setName('One Day Son'); $album->setArtist($artist); $album->setSongs($songs = new ResourceCollection()); $album->setArtwork($artwork = ArtworkResourceMock::create(20)); $artwork->setImage('ryohei-hase.jpg'); $artwork->setMime('image/jpg'); $artwork->setAlbum($album); $songs->add($song = SongResourceMock::create(1000)); $song->setName('Deathcar'); $song->setDescription('Heavy'); $song->setAlbum($album); // Make sure that the unit of work we are testing is hardcoded. // Other areas of the test that are covered can make use of the resource getters. $expected = ['id' => $artist->getId(), 'name' => $artist->getName(), 'albums' => ['data' => []]]; $array = $this->transformer->dehydrate($artist, 1); $this->assertEquals($expected, $array, 'Depth level: 1'); // At depth level 2 the albums collection should be dehydrated. $expected['albums']['data'] = [['id' => $album->getId(), 'name' => $album->getName(), 'artist' => [ArrayTransformer::KEY_RECURSION => true, 'id' => $artist->getId()], 'songs' => ['data' => []], 'artwork' => ['id' => $artwork->getId()]]]; $array = $this->transformer->dehydrate($artist, 2); $this->assertEquals($expected, $array, 'Depth level: 2'); // At depth level 3 the artwork resource should be dehydrated .. $expected['albums']['data'][0]['artwork'] = ['id' => $artwork->getId(), 'image' => $artwork->getImage(), 'type' => $artwork->getMime(), 'album' => [ArrayTransformer::KEY_RECURSION => true, 'id' => $album->getId()]]; // .. and also the songs collection. $expected['albums']['data'][0]['songs']['data'] = [['id' => $song->getId(), 'name' => $song->getName(), 'description' => $song->getDescription(), 'album' => [ArrayTransformer::KEY_RECURSION => true, 'id' => $album->getId()]]]; $array = $this->transformer->dehydrate($artist, 3); $this->assertEquals($expected, $array, 'Depth level: 3'); }