|
21 | 21 | class SaveAssetsKeywords implements SaveAssetsKeywordsInterface
|
22 | 22 | {
|
23 | 23 | private const TABLE_KEYWORD = 'media_gallery_keyword';
|
| 24 | + private const TABLE_ASSET_KEYWORD = 'media_gallery_asset_keyword'; |
24 | 25 | private const ID = 'id';
|
25 | 26 | private const KEYWORD = 'keyword';
|
26 | 27 |
|
@@ -71,6 +72,8 @@ public function execute(array $assetKeywords): void
|
71 | 72 | }
|
72 | 73 | }
|
73 | 74 |
|
| 75 | + $this->deleteObsoleteKeywords(); |
| 76 | + |
74 | 77 | if (!empty($failedAssetIds)) {
|
75 | 78 | throw new CouldNotSaveException(
|
76 | 79 | __('Could not save keywords for asset ids: %ids', ['ids' => implode(' ,', $failedAssetIds)])
|
@@ -125,4 +128,60 @@ private function getKeywordIds(array $keywords): array
|
125 | 128 |
|
126 | 129 | return $connection->fetchCol($select);
|
127 | 130 | }
|
| 131 | + |
| 132 | + /** |
| 133 | + * Delete keywords which has |
| 134 | + * no relation to any asset |
| 135 | + * |
| 136 | + * @return void |
| 137 | + */ |
| 138 | + private function deleteObsoleteKeywords(): void |
| 139 | + { |
| 140 | + $connection = $this->resourceConnection->getConnection(); |
| 141 | + $select = $connection->select() |
| 142 | + ->from( |
| 143 | + ['k' => self::TABLE_KEYWORD], |
| 144 | + ['k.id'] |
| 145 | + ) |
| 146 | + ->joinLeft( |
| 147 | + ['ak' => self::TABLE_ASSET_KEYWORD], |
| 148 | + 'k.id = ak.keyword_id' |
| 149 | + ) |
| 150 | + ->where('ak.asset_id IS NULL'); |
| 151 | + |
| 152 | + $obsoleteKeywords = $connection->fetchCol($select); |
| 153 | + |
| 154 | + if (!empty($obsoleteKeywords)) { |
| 155 | + try { |
| 156 | + $this->deleteKeywordsByIds($obsoleteKeywords); |
| 157 | + } catch (\Exception $exception) { |
| 158 | + $this->logger->critical($exception); |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + /** |
| 164 | + * Delete keywords by ids |
| 165 | + * |
| 166 | + * @param array $keywordIds |
| 167 | + * @return void |
| 168 | + */ |
| 169 | + private function deleteKeywordsByIds(array $keywordIds): void |
| 170 | + { |
| 171 | + $connection = $this->resourceConnection->getConnection(); |
| 172 | + |
| 173 | + $whereConditions = [ |
| 174 | + $connection->prepareSqlCondition( |
| 175 | + self::ID, |
| 176 | + ['in' => [$keywordIds]] |
| 177 | + ), |
| 178 | + ]; |
| 179 | + |
| 180 | + $connection->delete( |
| 181 | + $connection->getTableName( |
| 182 | + self::TABLE_KEYWORD |
| 183 | + ), |
| 184 | + $whereConditions |
| 185 | + ); |
| 186 | + } |
128 | 187 | }
|
0 commit comments