/
SearchKeywordUpdater.php
332 lines (269 loc) · 12.6 KB
/
SearchKeywordUpdater.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
<?php declare(strict_types=1);
namespace Shopware\Core\Content\Product\DataAbstractionLayer;
use Doctrine\DBAL\Connection;
use Shopware\Core\Content\Product\Aggregate\ProductKeywordDictionary\ProductKeywordDictionaryDefinition;
use Shopware\Core\Content\Product\Aggregate\ProductSearchKeyword\ProductSearchKeywordDefinition;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Content\Product\SearchKeyword\ProductSearchKeywordAnalyzerInterface;
use Shopware\Core\Defaults;
use Shopware\Core\Framework\Api\Context\SystemSource;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Dbal\Common\RepositoryIterator;
use Shopware\Core\Framework\DataAbstractionLayer\Dbal\EntityDefinitionQueryHelper;
use Shopware\Core\Framework\DataAbstractionLayer\Doctrine\MultiInsertQueryQueue;
use Shopware\Core\Framework\DataAbstractionLayer\Doctrine\RetryableQuery;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Field\AssociationField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\Field;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\NandFilter;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Core\System\Language\LanguageCollection;
use Shopware\Core\System\Language\LanguageEntity;
class SearchKeywordUpdater
{
private Connection $connection;
private EntityRepositoryInterface $languageRepository;
private EntityRepositoryInterface $productRepository;
private ProductSearchKeywordAnalyzerInterface $analyzer;
private EntityRepositoryInterface $productSearchConfigFieldRepository;
/**
* @var array[]
*/
private $config = [];
public function __construct(
Connection $connection,
EntityRepositoryInterface $languageRepository,
EntityRepositoryInterface $productRepository,
ProductSearchKeywordAnalyzerInterface $analyzer,
EntityRepositoryInterface $productSearchConfigFieldRepository
) {
$this->connection = $connection;
$this->languageRepository = $languageRepository;
$this->productRepository = $productRepository;
$this->analyzer = $analyzer;
$this->productSearchConfigFieldRepository = $productSearchConfigFieldRepository;
}
public function update(array $ids, Context $context): void
{
if (empty($ids)) {
return;
}
$criteria = new Criteria();
$criteria->addFilter(new NandFilter([new EqualsFilter('salesChannelDomains.id', null)]));
/** @var LanguageCollection $languages */
$languages = $this->languageRepository->search($criteria, Context::createDefaultContext())->getEntities();
$languages = $this->sortLanguages($languages);
$products = [];
foreach ($languages as $language) {
$languageContext = new Context(
new SystemSource(),
[],
Defaults::CURRENCY,
[$language->getId(), $language->getParentId(), Defaults::LANGUAGE_SYSTEM],
$context->getVersionId()
);
$existingProducts = $products[$language->getParentId() ?? Defaults::LANGUAGE_SYSTEM] ?? [];
$products[$language->getId()] = $this->updateLanguage($ids, $languageContext, $existingProducts);
}
}
/**
* @return ProductEntity[]
*/
private function updateLanguage(array $ids, Context $context, array $existingProducts): array
{
$configFields = [];
if ($this->productSearchConfigFieldRepository !== null) {
$configFields = $this->getConfigFields($context->getLanguageId());
}
$versionId = Uuid::fromHexToBytes($context->getVersionId());
$languageId = Uuid::fromHexToBytes($context->getLanguageId());
$now = (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT);
$this->delete($ids, $context->getLanguageId(), $context->getVersionId());
$keywords = [];
$dictionary = [];
$iterator = $this->getIterator($ids, $context, $configFields);
while ($products = $iterator->fetch()) {
/** @var ProductEntity $product */
foreach ($products as $product) {
// overwrite fetched products if translations for that product exists
// otherwise we use the already fetched product from the parent language
$existingProducts[$product->getId()] = $product;
}
}
foreach ($existingProducts as $product) {
$analyzed = $this->analyzer->analyze($product, $context, $configFields);
$productId = Uuid::fromHexToBytes($product->getId());
foreach ($analyzed as $keyword) {
$keywords[] = [
'id' => Uuid::randomBytes(),
'version_id' => $versionId,
'product_version_id' => $versionId,
'language_id' => $languageId,
'product_id' => $productId,
'keyword' => $keyword->getKeyword(),
'ranking' => $keyword->getRanking(),
'created_at' => $now,
];
$key = $keyword->getKeyword() . $languageId;
$dictionary[$key] = [
'id' => Uuid::randomBytes(),
'language_id' => $languageId,
'keyword' => $keyword->getKeyword(),
];
}
}
$this->insertKeywords($keywords);
$this->insertDictionary($dictionary);
return $existingProducts;
}
private function getIterator(array $ids, Context $context, array $configFields): RepositoryIterator
{
$context->setConsiderInheritance(true);
$criteria = new Criteria($ids);
$criteria->setLimit(50);
$this->buildCriteria(array_column($configFields, 'field'), $criteria, $context);
return new RepositoryIterator($this->productRepository, $context, $criteria);
}
private function delete(array $ids, string $languageId, string $versionId): void
{
$bytes = Uuid::fromHexToBytesList($ids);
$params = [
'ids' => $bytes,
'language' => Uuid::fromHexToBytes($languageId),
'versionId' => Uuid::fromHexToBytes($versionId),
];
RetryableQuery::retryable(function () use ($params): void {
$this->connection->executeUpdate(
'DELETE FROM product_search_keyword WHERE product_id IN (:ids) AND language_id = :language AND version_id = :versionId',
$params,
['ids' => Connection::PARAM_STR_ARRAY]
);
});
}
private function insertKeywords(array $keywords): void
{
$queue = new MultiInsertQueryQueue($this->connection, 50);
foreach ($keywords as $insert) {
$queue->addInsert(ProductSearchKeywordDefinition::ENTITY_NAME, $insert);
}
// try batch insert
try {
$queue->execute();
} catch (\Exception $e) {
// catch deadlock exception and retry with single insert
$query = new RetryableQuery(
$this->connection->prepare('
INSERT IGNORE INTO `product_search_keyword` (`id`, `version_id`, `product_version_id`, `language_id`, `product_id`, `keyword`, `ranking`, `created_at`)
VALUES (:id, :version_id, :product_version_id, :language_id, :product_id, :keyword, :ranking, :created_at)
')
);
foreach ($keywords as $keyword) {
$query->execute($keyword);
}
}
}
private function insertDictionary(array $dictionary): void
{
$queue = new MultiInsertQueryQueue($this->connection, 50, false, true);
foreach ($dictionary as $insert) {
$queue->addInsert(ProductKeywordDictionaryDefinition::ENTITY_NAME, $insert);
}
// try batch insert
try {
$queue->execute();
} catch (\Exception $e) {
// catch deadlock exception and retry with single insert
$query = new RetryableQuery(
$this->connection->prepare('INSERT IGNORE INTO `product_keyword_dictionary` (`id`, `language_id`, `keyword`) VALUES (:id, :language_id, :keyword)')
);
foreach ($dictionary as $insert) {
$query->execute($insert);
}
}
}
private function buildCriteria(array $accessors, Criteria $criteria, Context $context): void
{
$definition = $this->productRepository->getDefinition();
// Filter for products that have translations in the given language
// if there are no translations, we copy the keywords of the parent language without fetching the product
$filters = [
new EqualsFilter('translations.languageId', $context->getLanguageId()),
new EqualsFilter('parent.translations.languageId', $context->getLanguageId()),
];
foreach ($accessors as $accessor) {
$fields = EntityDefinitionQueryHelper::getFieldsOfAccessor($definition, $accessor);
$fields = array_filter($fields, function (Field $field) {
return $field instanceof AssociationField;
});
if (empty($fields)) {
continue;
}
$lastAssociationField = $fields[\count($fields) - 1];
$path = array_map(function (Field $field) {
return $field->getPropertyName();
}, $fields);
$association = implode('.', $path);
if ($criteria->hasAssociation($association)) {
continue;
}
$criteria->addAssociation($association);
$translationField = $lastAssociationField->getReferenceDefinition()->getTranslationField();
if (!$translationField) {
continue;
}
// filter the associations that have no translations in given language,
// as we automatically use the parent languages keywords for those
$translationLanguageAccessor = sprintf(
'%s.%s.languageId',
$association,
$translationField->getPropertyName()
);
$filters[] = new EqualsFilter($translationLanguageAccessor, $context->getLanguageId());
}
$criteria->addFilter(new MultiFilter(MultiFilter::CONNECTION_OR, $filters));
}
private function getConfigFields(string $languageId): array
{
if (isset($this->config[$languageId])) {
return $this->config[$languageId];
}
$query = $this->connection->createQueryBuilder();
$query->select('configField.field', 'configField.tokenize', 'configField.ranking', 'LOWER(HEX(config.language_id)) as language_id');
$query->from('product_search_config', 'config');
$query->join('config', 'product_search_config_field', 'configField', 'config.id = configField.product_search_config_id');
$query->andWhere('config.language_id IN (:languageIds)');
$query->andWhere('configField.searchable = 1');
$query->setParameter('languageIds', Uuid::fromHexToBytesList([$languageId, Defaults::LANGUAGE_SYSTEM]), Connection::PARAM_STR_ARRAY);
$all = $query->execute()->fetchAll();
$fields = array_filter($all, function (array $field) use ($languageId) {
return $field['language_id'] === $languageId;
});
if (!empty($fields)) {
return $this->config[$languageId] = $fields;
}
$fields = array_filter($all, function (array $field) {
return $field['language_id'] === Defaults::LANGUAGE_SYSTEM;
});
return $this->config[$languageId] = $fields;
}
/**
* Sort languages so default language comes first, then languages that don't inherit and last inherited languages
*
* @return LanguageEntity[]
*/
private function sortLanguages(LanguageCollection $languages): array
{
$defaultLanguage = $languages->get(Defaults::LANGUAGE_SYSTEM);
$languages->remove(Defaults::LANGUAGE_SYSTEM);
return array_filter(array_merge(
[$defaultLanguage],
$languages->filterByProperty('parentId', null)->getElements(),
$languages->filter(function (LanguageEntity $language) {
return $language->getParentId() !== null;
})->getElements()
));
}
}