Skip to content

Commit a3e9fea

Browse files
committed
magento/adobe-stock-integration#1391: SaveAssetsKeywordsInterface to delete obsolete keywords - Add method to delete keywords which has no relation to assets
1 parent cc7f549 commit a3e9fea

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

app/code/Magento/MediaGallery/Model/ResourceModel/Keyword/SaveAssetsKeywords.php

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
class SaveAssetsKeywords implements SaveAssetsKeywordsInterface
2222
{
2323
private const TABLE_KEYWORD = 'media_gallery_keyword';
24+
private const TABLE_ASSET_KEYWORD = 'media_gallery_asset_keyword';
2425
private const ID = 'id';
2526
private const KEYWORD = 'keyword';
2627

@@ -71,6 +72,8 @@ public function execute(array $assetKeywords): void
7172
}
7273
}
7374

75+
$this->deleteObsoleteKeywords();
76+
7477
if (!empty($failedAssetIds)) {
7578
throw new CouldNotSaveException(
7679
__('Could not save keywords for asset ids: %ids', ['ids' => implode(' ,', $failedAssetIds)])
@@ -125,4 +128,60 @@ private function getKeywordIds(array $keywords): array
125128

126129
return $connection->fetchCol($select);
127130
}
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+
}
128187
}

0 commit comments

Comments
 (0)