]> git.immae.eu Git - github/wallabag/wallabag.git/blobdiff - src/Wallabag/ApiBundle/Controller/WallabagRestController.php
Ensure orphan tag are remove in API
[github/wallabag/wallabag.git] / src / Wallabag / ApiBundle / Controller / WallabagRestController.php
index a0d9d4f3a144336735468ad3fd4f04b67eda8087..cc6923a043cc1d8c818893e03d8c43edbae1d956 100644 (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.