From 7b453225ed54442307ff51e8298513e9ab1f4300 Mon Sep 17 00:00:00 2001
From: Guillaume Heurtier <guillaume.heurtier@maarch.org>
Date: Wed, 12 Feb 2020 11:02:40 +0100
Subject: [PATCH] FEAT #12471 TIME 0:10 unlink tags when delete + prevent
 delete if tag has children

---
 src/app/tag/controllers/TagController.php | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)

diff --git a/src/app/tag/controllers/TagController.php b/src/app/tag/controllers/TagController.php
index 82adfc9ec36..dc13fcf61b6 100644
--- a/src/app/tag/controllers/TagController.php
+++ b/src/app/tag/controllers/TagController.php
@@ -190,11 +190,31 @@ class TagController
         }
 
 
-        $tag = TagModel::getById(['select' => ['label'], 'id' => $args['id']]);
+        $tag = TagModel::getById(['select' => ['label', 'links'], 'id' => $args['id']]);
         if (empty($tag)) {
             return $response->withStatus(400)->withJson(['errors' => 'Tag does not exist']);
         }
 
+        $children = TagModel::get([
+           'select' => ['count(1)'],
+           'where'  => ['parent_id = ?'],
+           'data'   => [$args['id']]
+        ]);
+        if ($children[0]['count'] > 0) {
+            return $response->withStatus(400)->withJson(['errors' => 'Tag has children']);
+        }
+
+        $links = json_decode($tag['links'], true);
+        if (!empty($links)) {
+            foreach ($links as $link) {
+                TagModel::update([
+                    'postSet'   => ['links' => "links - '{$args['id']}'"],
+                    'where'     => ['id = ?'],
+                    'data'      => [$link]
+                ]);
+            }
+        }
+
         TagModel::delete([
             'where' => ['id = ?'],
             'data'  => [$args['id']]
-- 
GitLab