-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCategoryTreeSyncProcessor.php
More file actions
257 lines (214 loc) · 9.09 KB
/
CategoryTreeSyncProcessor.php
File metadata and controls
257 lines (214 loc) · 9.09 KB
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
<?php
declare(strict_types=1);
namespace Ergonode\IntegrationShopware\Processor;
use Ergonode\IntegrationShopware\Api\CategoryTreeStreamResultsProxy;
use Ergonode\IntegrationShopware\Api\Client\ErgonodeGqlClientInterface;
use Ergonode\IntegrationShopware\DTO\SyncCounterDTO;
use Ergonode\IntegrationShopware\Manager\ErgonodeCursorManager;
use Ergonode\IntegrationShopware\Persistor\CategoryTreePersistor;
use Ergonode\IntegrationShopware\Persistor\Helper\CategoryOrderHelper;
use Ergonode\IntegrationShopware\QueryBuilder\CategoryQueryBuilder;
use Ergonode\IntegrationShopware\Service\ConfigService;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Shopware\Core\Framework\Context;
use Symfony\Component\Stopwatch\Stopwatch;
use Throwable;
use function count;
class CategoryTreeSyncProcessor implements CategoryProcessorInterface
{
public const DEFAULT_LEAF_COUNT = 25;
private ErgonodeGqlClientInterface $gqlClient;
private CategoryQueryBuilder $categoryQueryBuilder;
private CategoryTreePersistor $categoryTreePersistor;
private ErgonodeCursorManager $cursorManager;
private LoggerInterface $logger;
private CategoryOrderHelper $categoryOrderHelper;
private ConfigService $configService;
public function __construct(
ErgonodeGqlClientInterface $gqlClient,
CategoryQueryBuilder $categoryQueryBuilder,
CategoryTreePersistor $categoryTreePersistor,
ErgonodeCursorManager $cursorManager,
LoggerInterface $ergonodeSyncLogger,
CategoryOrderHelper $categoryOrderHelper,
ConfigService $configService
) {
$this->gqlClient = $gqlClient;
$this->categoryQueryBuilder = $categoryQueryBuilder;
$this->categoryTreePersistor = $categoryTreePersistor;
$this->cursorManager = $cursorManager;
$this->logger = $ergonodeSyncLogger;
$this->categoryOrderHelper = $categoryOrderHelper;
$this->configService = $configService;
}
/**
* @inheritDoc
*/
public function processStream(
array $treeCodes,
Context $context
): SyncCounterDTO {
$counter = new SyncCounterDTO();
$stopwatch = new Stopwatch();
$leafCursor = $this->cursorManager->getCursor(
CategoryTreeStreamResultsProxy::TREE_LEAF_LIST_CURSOR,
$context
);
$stopwatch->start('query');
$query = $this->categoryQueryBuilder->buildTreeStream(
self::DEFAULT_LEAF_COUNT,
$leafCursor
);
/** @var CategoryTreeStreamResultsProxy|null $result */
$result = $this->gqlClient->query($query, CategoryTreeStreamResultsProxy::class);
$stopwatch->stop('query');
if (null === $result) {
throw new RuntimeException('Request failed.');
}
$leafEdges = $result->getEdges()[0]['node']['categoryTreeLeafList']['edges'] ?? [];
if (0 === count($result->getEdges()) && 0 === count($leafEdges)) {
$this->logger->info('End of stream reached.');
$counter->setHasNextPage(false);
return $counter;
}
$treeEndCursor = $result->getEndCursor();
if (null === $treeEndCursor) {
throw new RuntimeException('Could not retrieve end cursor from the response.');
}
$leafHasNextPage = false;
$leafEndCursor = null;
$processedKeys = [];
$this->fetchCategoryRootId($context);
foreach ($result->getEdges() as $edge) {
$node = $edge['node'] ?? null;
$currentTreeCode = $node['code'];
if (false === \in_array($currentTreeCode, $treeCodes)) {
continue;
}
$stopwatch->start('process');
try {
$leafEdges = $this->normalizeCategoryTreeEdges($edge);
$primaryKeys = $this->categoryTreePersistor->persistLeaves($leafEdges, $currentTreeCode, $context);
$this->categoryTreePersistor->markCategoriesAsActive($primaryKeys);
$processedKeys[] = $primaryKeys;
if (!$leafHasNextPage) {
$leafHasNextPage = $edge['node']['categoryTreeLeafList']['pageInfo']['hasNextPage'] ?? false;
$leafEndCursor = $edge['node']['categoryTreeLeafList']['pageInfo']['endCursor'] ?? null;
// Restore code removed in SWERG-174.
// fix for SWERG-169. The issue is that removeOrphanedCategories adds 1 second to the
// last sync time and when the sync is ran for the first time some trees can be processed under
// 1 second resulting in them being completely removed because they have updated_at time before
// the new lastSyncTime
sleep(2);
}
$this->logger->info('Persisted category leaves', [
'count' => count($primaryKeys),
'treeCode' => $currentTreeCode
]);
} catch (Throwable $e) {
$this->logger->error('Error while persisting category leaves.', [
'message' => $e->getMessage(),
'file' => $e->getFile() . ':' . $e->getLine(),
'code' => $node['code'],
]);
} finally {
$stopwatch->stop('process');
}
}
$processedKeys = array_merge(...$processedKeys);
$entityCount = \count($processedKeys);
$counter->incrProcessedEntityCount($entityCount);
$counter->setPrimaryKeys($processedKeys);
$this->cursorManager->persist(
$treeEndCursor,
CategoryTreeStreamResultsProxy::MAIN_FIELD,
$context
);
if ($leafHasNextPage) {
$this->logger->info('Category leaves have next page', [
'leafCursor' => $leafEndCursor,
]);
$this->cursorManager->persist(
$leafEndCursor,
CategoryTreeStreamResultsProxy::TREE_LEAF_LIST_CURSOR,
$context
);
} else {
$this->cursorManager->deleteCursor(
CategoryTreeStreamResultsProxy::TREE_LEAF_LIST_CURSOR,
$context
);
}
$counter->setHasNextPage($result->hasNextPage() || $leafHasNextPage);
$counter->setStopwatch($stopwatch);
return $counter;
}
/**
* devEcommerce change
*/
private function normalizeCategoryTreeEdges(mixed $edge): mixed
{
$leafEdges = $edge['node']['categoryTreeLeafList']['edges'] ?? [];
$categoryTreeCode = $edge['node']['code'];
$categoryTreeNames = $edge['node']['name'];
$mainEdgeKeys = array_keys(array_filter(
$leafEdges,
fn($row) => empty($row['node']['parentCategory'])
));
if(!empty($mainEdgeKeys)) {
$firstCategory = [
'node' => [
'category' => [
'code' => $categoryTreeCode,
'name' => $categoryTreeNames,
],
'parentCategory' => null,
]
];
array_unshift($leafEdges,$firstCategory);
foreach ($mainEdgeKeys as $key) {
$leafEdges[$key+1]['node']['parentCategory'] = ['code' => $categoryTreeCode];
}
}
file_put_contents('../custom/plugins/ergo_graph.log', print_r($mainEdgeKeys, true) . "\n-----\n" ,FILE_APPEND);
file_put_contents('../custom/plugins/ergo_graph.log', print_r($leafEdges, true) . "\n-----\n" ,FILE_APPEND);
return $leafEdges;
}
/**
* Gets ID of last existing top level category
*
* @param Context $context
* @return void
*/
private function fetchCategoryRootId(Context $context): void
{
$this->categoryTreePersistor->resetLastRootCategoryId();
$lastRootCategoryId = $this->categoryOrderHelper->getLastRootCategoryId($context);
if ($lastRootCategoryId) {
$this->categoryTreePersistor->setLastRootCategoryId($lastRootCategoryId);
}
}
public function removeOrphanedCategories(Context $context): void
{
$lastSync = $this->configService->getLastCategorySyncTimestamp();
$categoriesToDelete = $this->categoryTreePersistor->fetchCategoriesToDelete();
try {
$this->categoryTreePersistor->removeCategoriesById(
array_values($categoriesToDelete),
$context
);
} catch (Throwable $ex) {
$this->logger->error('One of categories marked to delete is mapped in Sales Channel navigation. ' .
'Cannot delete as long as it is set in sales channel navigation', [
'categories' => $categoriesToDelete,
'message' => $ex->getMessage(),
]);
}
$this->categoryTreePersistor->clearCategoriesAsActive();
$this->logger->info('Removed orphaned Ergonode categories', [
'count' => count($categoriesToDelete),
'time' => (new \DateTime('@' . $lastSync))->format(DATE_ATOM),
]);
}
}