/**
  * Add Tag id to error message
  *
  * @param \Mageplaza\Blog\Model\Tag $tag
  * @param string $errorText
  * @return string
  */
 protected function getErrorWithTagId(\Mageplaza\Blog\Model\Tag $tag, $errorText)
 {
     return '[Tag ID: ' . $tag->getId() . '] ' . $errorText;
 }
 /**
  * @param \Mageplaza\Blog\Model\Tag $tag
  * @return $this
  */
 protected function savePostRelation(\Mageplaza\Blog\Model\Tag $tag)
 {
     $tag->setIsChangedPostList(false);
     $id = $tag->getId();
     $posts = $tag->getPostsData();
     if ($posts === null) {
         return $this;
     }
     $oldPosts = $tag->getPostsPosition();
     $insert = array_diff_key($posts, $oldPosts);
     $delete = array_diff_key($oldPosts, $posts);
     $update = array_intersect_key($posts, $oldPosts);
     $_update = [];
     foreach ($update as $key => $settings) {
         if (isset($oldPosts[$key]) && $oldPosts[$key] != $settings['position']) {
             $_update[$key] = $settings;
         }
     }
     $update = $_update;
     $adapter = $this->getConnection();
     if (!empty($delete)) {
         $condition = ['post_id IN(?)' => array_keys($delete), 'tag_id=?' => $id];
         $adapter->delete($this->tagPostTable, $condition);
     }
     if (!empty($insert)) {
         $data = [];
         foreach ($insert as $postId => $position) {
             $data[] = ['tag_id' => (int) $id, 'post_id' => (int) $postId, 'position' => (int) $position['position']];
         }
         $adapter->insertMultiple($this->tagPostTable, $data);
     }
     if (!empty($update)) {
         foreach ($update as $postId => $position) {
             $where = ['tag_id = ?' => (int) $id, 'post_id = ?' => (int) $postId];
             $bind = ['position' => (int) $position['position']];
             $adapter->update($this->tagPostTable, $bind, $where);
         }
     }
     if (!empty($insert) || !empty($delete)) {
         $postIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
         $this->eventManager->dispatch('mageplaza_blog_tag_change_posts', ['tag' => $tag, 'post_ids' => $postIds]);
     }
     if (!empty($insert) || !empty($update) || !empty($delete)) {
         $tag->setIsChangedPostList(true);
         $postIds = array_keys($insert + $delete + $update);
         $tag->setAffectedPostIds($postIds);
     }
     return $this;
 }