Skip to content
This repository has been archived by the owner on Jan 21, 2020. It is now read-only.

Fix bug causing duplicate links when entity contains links and is rendered twice #102

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/Link/LinkCollection.php
Expand Up @@ -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;
}
}
10 changes: 10 additions & 0 deletions src/Plugin/Hal.php
Expand Up @@ -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)) {
Expand Down Expand Up @@ -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;
}

Expand Down
19 changes: 19 additions & 0 deletions test/Plugin/HalTest.php
Expand Up @@ -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
*/
Expand Down