]> git.immae.eu Git - github/wallabag/wallabag.git/blobdiff - src/Wallabag/ApiBundle/Controller/WallabagRestController.php
Merge pull request #2393 from wallabag/api-urls-exist
[github/wallabag/wallabag.git] / src / Wallabag / ApiBundle / Controller / WallabagRestController.php
index 6dd03c1b6495564371cb96673b3efd3e311d71e5..ed31c536aa161c790a86ffb3984fd466fd0d139b 100644 (file)
@@ -420,6 +420,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);
@@ -460,6 +462,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);
@@ -484,6 +488,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);
@@ -505,6 +511,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.