Ensure orphan tag are remove in API

When the association between a tag and an entry is removed, if the tag doesn’t have other entries, we can remove it.

Also add more tests for that part and ensure TagControllerTest is isolated from the rest of the test suite (finally!)
This commit is contained in:
Jeremy Benoist
2016-10-07 23:31:53 +02:00
parent 3049afe190
commit ac8cf632bb
6 changed files with 78 additions and 27 deletions

View File

@ -400,6 +400,8 @@ class WallabagRestController extends FOSRestController
->getRepository('WallabagCoreBundle:Entry')
->removeTag($this->getUser()->getId(), $tag);
$this->cleanOrphanTag($tag);
$json = $this->get('serializer')->serialize($tag, 'json');
return (new JsonResponse())->setJson($json);
@ -440,6 +442,8 @@ class WallabagRestController extends FOSRestController
->getRepository('WallabagCoreBundle:Entry')
->removeTags($this->getUser()->getId(), $tags);
$this->cleanOrphanTag($tags);
$json = $this->get('serializer')->serialize($tags, 'json');
return (new JsonResponse())->setJson($json);
@ -464,6 +468,8 @@ class WallabagRestController extends FOSRestController
->getRepository('WallabagCoreBundle:Entry')
->removeTag($this->getUser()->getId(), $tag);
$this->cleanOrphanTag($tag);
$json = $this->get('serializer')->serialize($tag, 'json');
return (new JsonResponse())->setJson($json);
@ -485,6 +491,28 @@ class WallabagRestController extends FOSRestController
return (new JsonResponse())->setJson($json);
}
/**
* Remove orphan tag in case no entries are associated to it.
*
* @param Tag|array $tags
*/
private function cleanOrphanTag($tags)
{
if (!is_array($tags)) {
$tags = [$tags];
}
$em = $this->getDoctrine()->getManager();
foreach ($tags as $tag) {
if (count($tag->getEntries()) === 0) {
$em->remove($tag);
}
}
$em->flush();
}
/**
* Validate that the first id is equal to the second one.
* If not, throw exception. It means a user try to access information from an other user.