diff --git a/extensions/tags/src/Listener/SaveTagsToDatabase.php b/extensions/tags/src/Listener/SaveTagsToDatabase.php index 19e271db9..71ac3b24e 100755 --- a/extensions/tags/src/Listener/SaveTagsToDatabase.php +++ b/extensions/tags/src/Listener/SaveTagsToDatabase.php @@ -57,25 +57,46 @@ class SaveTagsToDatabase $discussion = $event->discussion; $actor = $event->actor; - // TODO: clean up, prevent discussion from being created without tags - if (isset($event->data['relationships']['tags']['data'])) { - if ($discussion->exists) { - $actor->assertCan('tag', $discussion); - } + $newTagIds = []; + $newTags = []; + $primaryCount = 0; + $secondaryCount = 0; + + if (isset($event->data['relationships']['tags']['data'])) { $linkage = (array) $event->data['relationships']['tags']['data']; - $newTagIds = []; foreach ($linkage as $link) { $newTagIds[] = (int) $link['id']; } $newTags = Tag::whereIn('id', $newTagIds)->get(); - $primaryCount = 0; - $secondaryCount = 0; + } + + if ($discussion->exists && isset($event->data['relationships']['tags']['data'])) { + $actor->assertCan('tag', $discussion); + + $oldTags = $discussion->tags()->get(); + $oldTagIds = $oldTags->pluck('id')->all(); + + if ($oldTagIds == $newTagIds) { + return; + } foreach ($newTags as $tag) { - if ($actor->cannot('startDiscussion', $tag)) { + if (! in_array($tag->id, $oldTagIds) && $actor->cannot('addToDiscussion', $tag)) { + throw new PermissionDeniedException; + } + } + + $discussion->raise( + new DiscussionWasTagged($discussion, $actor, $oldTags->all()) + ); + } + + if (! $discussion->exists || isset($event->data['relationships']['tags']['data'])) { + foreach ($newTags as $tag) { + if (! $discussion->exists && $actor->cannot('startDiscussion', $tag)) { throw new PermissionDeniedException; } @@ -89,30 +110,9 @@ class SaveTagsToDatabase $this->validateTagCount('primary', $primaryCount); $this->validateTagCount('secondary', $secondaryCount); - if ($discussion->exists) { - $oldTags = $discussion->tags()->get(); - $oldTagIds = $oldTags->pluck('id')->all(); - - if ($oldTagIds == $newTagIds) { - return; - } - - foreach ($newTags as $tag) { - if (! in_array($tag->id, $oldTagIds) && $actor->cannot('addToDiscussion', $tag)) { - throw new PermissionDeniedException; - } - } - - $discussion->raise( - new DiscussionWasTagged($discussion, $actor, $oldTags->all()) - ); - } - $discussion->afterSave(function ($discussion) use ($newTagIds) { $discussion->tags()->sync($newTagIds); }); - } elseif (! $discussion->exists && ! $actor->hasPermission('startDiscussion')) { - throw new PermissionDeniedException; } }