diff --git a/src/Link/LinkCollection.php b/src/Link/LinkCollection.php index 343f422..d034cbc 100644 --- a/src/Link/LinkCollection.php +++ b/src/Link/LinkCollection.php @@ -116,4 +116,15 @@ public function remove($relation) unset($this->links[$relation]); return true; } + + /** + * Remove all links + * + * @return self + */ + public function clear() + { + $this->links = array(); + return $this; + } } diff --git a/src/Plugin/Hal.php b/src/Plugin/Hal.php index 8505441..045099e 100644 --- a/src/Plugin/Hal.php +++ b/src/Plugin/Hal.php @@ -552,6 +552,10 @@ public function renderEntity(Entity $halEntity, $renderEntity = true, $depth = 0 $this->getEventManager()->trigger(__FUNCTION__, $this, array('entity' => $halEntity)); $entity = $halEntity->entity; $entityLinks = $halEntity->getLinks(); + + // $entityLinks is modified during rendering, so keep a backup to prevent side effects. + $entityLinksBackup = clone($entityLinks); + $metadataMap = $this->getMetadataMap(); if (is_object($entity)) { @@ -617,6 +621,12 @@ public function renderEntity(Entity $halEntity, $renderEntity = true, $depth = 0 unset($this->entityHashStack[$entityHash]); } + // Restore $entityLinks to its original state + $entityLinks->clear(); + foreach ($entityLinksBackup as $link) { + $entityLinks->add($link); + } + return $entity; } diff --git a/test/Plugin/HalTest.php b/test/Plugin/HalTest.php index e05939b..ce5b365 100644 --- a/test/Plugin/HalTest.php +++ b/test/Plugin/HalTest.php @@ -879,6 +879,25 @@ public function testRouteParamsAllowsCallable() $this->assertEquals('closure-param', $params['test-2']); } + public function testRenderEntityTwice() + { + $link = new Link('resource'); + $link->setRoute('resource', array('id' => 'user')); + + $entity = new Entity( + (object) array( + 'id' => 'user', + 'name' => 'matthew', + 'resource' => $link, + ), + 'user' + ); + + $rendered1 = $this->plugin->renderEntity($entity); + $rendered2 = $this->plugin->renderEntity($entity); + $this->assertEquals($rendered1, $rendered2); + } + /** * @group 79 */