-
-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathGenerateBatchHandler.php
More file actions
306 lines (254 loc) · 11.8 KB
/
GenerateBatchHandler.php
File metadata and controls
306 lines (254 loc) · 11.8 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
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
<?php
declare(strict_types=1);
namespace Setono\SyliusFeedPlugin\Message\Handler;
use Doctrine\Persistence\ObjectManager;
use InvalidArgumentException;
use const JSON_INVALID_UTF8_IGNORE;
use const JSON_PRESERVE_ZERO_FRACTION;
use const JSON_PRETTY_PRINT;
use const JSON_UNESCAPED_SLASHES;
use const JSON_UNESCAPED_UNICODE;
use League\Flysystem\FilesystemInterface;
use League\Flysystem\FilesystemOperator;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Setono\SyliusFeedPlugin\Event\BatchGeneratedEvent;
use Setono\SyliusFeedPlugin\Event\GenerateBatchItemEvent;
use Setono\SyliusFeedPlugin\Event\GenerateBatchViolationEvent;
use Setono\SyliusFeedPlugin\Exception\GenerateBatchException;
use Setono\SyliusFeedPlugin\Factory\ViolationFactoryInterface;
use Setono\SyliusFeedPlugin\Generator\FeedPathGeneratorInterface;
use Setono\SyliusFeedPlugin\Generator\TemporaryFeedPathGenerator;
use Setono\SyliusFeedPlugin\Message\Command\GenerateBatch;
use Setono\SyliusFeedPlugin\Model\FeedInterface;
use Setono\SyliusFeedPlugin\Model\ViolationInterface;
use Setono\SyliusFeedPlugin\Registry\FeedTypeRegistryInterface;
use Setono\SyliusFeedPlugin\Repository\FeedRepositoryInterface;
use Setono\SyliusFeedPlugin\Workflow\FeedGraph;
use Sylius\Component\Channel\Model\ChannelInterface;
use Sylius\Component\Channel\Repository\ChannelRepositoryInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\Workflow\WorkflowInterface;
use Throwable;
use Twig\Environment;
use Webmozart\Assert\Assert;
final class GenerateBatchHandler implements MessageHandlerInterface
{
use GetChannelTrait;
use GetFeedTrait;
use GetLocaleTrait;
private RequestContext $initialRequestContext;
private FilesystemInterface|FilesystemOperator $filesystem;
public function __construct(
FeedRepositoryInterface $feedRepository,
ChannelRepositoryInterface $channelRepository,
RepositoryInterface $localeRepository,
private readonly ObjectManager $feedManager,
private readonly FeedTypeRegistryInterface $feedTypeRegistry,
private readonly Environment $twig,
$filesystem,
private readonly FeedPathGeneratorInterface $temporaryFeedPathGenerator,
private readonly EventDispatcherInterface $eventDispatcher,
private readonly Registry $workflowRegistry,
private readonly ValidatorInterface $validator,
private readonly ViolationFactoryInterface $violationFactory,
private readonly SerializerInterface $serializer,
private readonly UrlGeneratorInterface $urlGenerator,
private readonly LoggerInterface $logger,
) {
$this->feedRepository = $feedRepository;
$this->channelRepository = $channelRepository;
$this->localeRepository = $localeRepository;
if (interface_exists(FilesystemInterface::class) && $filesystem instanceof FilesystemInterface) {
$this->filesystem = $filesystem;
} elseif ($filesystem instanceof FilesystemOperator) {
$this->filesystem = $filesystem;
} else {
throw new InvalidArgumentException(sprintf(
'The filesystem must be an instance of %s or %s',
FilesystemInterface::class,
FilesystemOperator::class,
));
}
}
public function __invoke(GenerateBatch $message): void
{
$feed = $this->getFeed($message->getFeedId());
if ($feed->isErrored()) {
return;
}
$channel = $this->getChannel($message->getChannelId());
$locale = $this->getLocale($message->getLocaleId());
$this->setTemporaryRequestContext($channel);
$workflow = $this->getWorkflow($feed);
try {
$feedType = $this->feedTypeRegistry->get((string) $feed->getFeedType());
$items = $feedType->getDataProvider()->getItems($message->getBatch());
$itemContext = $feedType->getItemContext();
$template = $this->twig->load($feedType->getTemplate());
$stream = $this->openStream();
foreach ($items as $item) {
try {
/** @phpstan-ignore arguments.count */
$contextList = $itemContext->getContextList($item, $channel, $locale, $feed);
/** @var array|object $context */
foreach ($contextList as $context) {
$this->eventDispatcher->dispatch(new GenerateBatchItemEvent(
$feed,
$feedType,
$channel,
$locale,
$context,
$item,
));
$constraintViolationList = $this->validator->validate(
$context,
null,
$feedType->getValidationGroups(),
);
$hasErrorViolation = false;
if ($constraintViolationList->count() > 0) {
/** @var ConstraintViolationInterface $constraintViolation */
foreach ($constraintViolationList as $constraintViolation) {
$violation = $this->violationFactory->createFromConstraintViolation(
$constraintViolation,
$channel,
$locale,
$this->serializer->serialize($context, 'json', [
JsonEncode::OPTIONS => JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_INVALID_UTF8_IGNORE,
'setono_sylius_feed_data' => true,
]),
);
if ($violation->getSeverity() === ViolationInterface::SEVERITY_ERROR) {
$hasErrorViolation = true;
}
$feed->addViolation($violation);
}
$this->eventDispatcher->dispatch(new GenerateBatchViolationEvent(
$feed,
$feedType,
$channel,
$locale,
$context,
$constraintViolationList,
));
}
// do not write the item to the stream if a violation has severity error
if ($hasErrorViolation) {
continue;
}
fwrite($stream, $template->renderBlock('item', ['item' => $context]));
}
} catch (Throwable $e) {
$newException = new GenerateBatchException($e->getMessage(), $e);
$newException->setResourceId($item->getId());
throw $newException;
}
}
$dir = $this->temporaryFeedPathGenerator->generate($feed, (string) $channel->getCode(), (string) $locale->getCode());
$filesystem = $this->filesystem;
$path = TemporaryFeedPathGenerator::getPartialFile($dir, $filesystem);
if (interface_exists(FilesystemInterface::class) && $filesystem instanceof FilesystemInterface) {
$res = $filesystem->writeStream((string) $path, $stream);
fclose($stream);
Assert::true($res, 'An error occurred when trying to write a feed item');
} else {
$filesystem->writeStream((string) $path, $stream);
fclose($stream);
}
$this->feedManager->flush();
$this->feedManager->clear();
$this->eventDispatcher->dispatch(new BatchGeneratedEvent($feed));
} catch (GenerateBatchException $e) {
$e->setFeedId((int) $feed->getId());
$e->setChannelCode((string) $channel->getCode());
$e->setLocaleCode((string) $locale->getCode());
$this->logger->critical($e->getMessage(), [
'resourceId' => $e->getResourceId(),
'feedId' => $feed->getId(),
'channelCode' => $channel->getCode(),
'localeCode' => $locale->getCode(),
]);
$this->applyErrorTransition($workflow, $feed);
$this->feedManager->flush();
throw $e;
} catch (Throwable $e) {
$this->logger->critical($e->getMessage(), [
'feedId' => $feed->getId(),
'channelCode' => $channel->getCode(),
'localeCode' => $locale->getCode(),
]);
$this->applyErrorTransition($workflow, $feed);
$this->feedManager->flush();
$newException = new GenerateBatchException($e->getMessage(), $e);
$newException->setFeedId((int) $feed->getId());
$newException->setChannelCode((string) $channel->getCode());
$newException->setLocaleCode((string) $locale->getCode());
throw $newException;
} finally {
$this->resetRequestContext();
}
}
private function setTemporaryRequestContext(ChannelInterface $channel): void
{
$this->initialRequestContext = $this->urlGenerator->getContext();
$requestContext = new RequestContext();
$requestContext->setScheme('https')
->setHost((string) $channel->getHostname())
;
$this->urlGenerator->setContext($requestContext);
}
private function resetRequestContext(): void
{
$this->urlGenerator->setContext($this->initialRequestContext);
}
private function getWorkflow(FeedInterface $feed): WorkflowInterface
{
try {
$workflow = $this->workflowRegistry->get($feed, FeedGraph::GRAPH);
} catch (InvalidArgumentException $e) {
throw new UnrecoverableMessageHandlingException(
'An error occurred when trying to get the workflow for the feed',
0,
$e,
);
}
return $workflow;
}
/**
* @return resource
*/
private function openStream()
{
// needs to be w+ since we use the same stream later to read from
$resource = fopen('php://temp', 'w+b');
if (!is_resource($resource)) {
throw new \RuntimeException('Could not open the stream');
}
return $resource;
}
private function applyErrorTransition(WorkflowInterface $workflow, FeedInterface $feed): void
{
// if the feed is already errored we won't want to throw an exception
if ($feed->isErrored()) {
return;
}
if (!$workflow->can($feed, FeedGraph::TRANSITION_ERRORED)) {
throw new InvalidArgumentException(sprintf(
'The transition "%s" could not be applied. State was: "%s"',
FeedGraph::TRANSITION_ERRORED,
$feed->getState(),
));
}
$workflow->apply($feed, FeedGraph::TRANSITION_ERRORED);
}
}