-
-
Notifications
You must be signed in to change notification settings - Fork 839
/
PublishMercureUpdatesListener.php
270 lines (231 loc) · 10.5 KB
/
PublishMercureUpdatesListener.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
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Core\Bridge\Doctrine\EventListener;
use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
use ApiPlatform\Core\Api\UrlGeneratorInterface;
use ApiPlatform\Core\Bridge\Symfony\Messenger\DispatchTrait;
use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\GraphQl\Subscription\MercureSubscriptionIriGeneratorInterface as GraphQlMercureSubscriptionIriGeneratorInterface;
use ApiPlatform\Core\GraphQl\Subscription\SubscriptionManagerInterface as GraphQlSubscriptionManagerInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Util\ResourceClassInfoTrait;
use Doctrine\Common\EventArgs;
use Doctrine\ODM\MongoDB\Event\OnFlushEventArgs as MongoDbOdmOnFlushEventArgs;
use Doctrine\ORM\Event\OnFlushEventArgs as OrmOnFlushEventArgs;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Mercure\Update;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Publishes resources updates to the Mercure hub.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*
* @experimental
*/
final class PublishMercureUpdatesListener
{
use DispatchTrait;
use ResourceClassInfoTrait;
private const ALLOWED_KEYS = [
'topics' => true,
'data' => true,
'private' => true,
'id' => true,
'type' => true,
'retry' => true,
'normalization_context' => true,
];
private $iriConverter;
private $serializer;
private $publisher;
private $expressionLanguage;
private $createdObjects;
private $updatedObjects;
private $deletedObjects;
private $formats;
private $graphQlSubscriptionManager;
private $graphQlMercureSubscriptionIriGenerator;
/**
* @param array<string, string[]|string> $formats
*/
public function __construct(ResourceClassResolverInterface $resourceClassResolver, IriConverterInterface $iriConverter, ResourceMetadataFactoryInterface $resourceMetadataFactory, SerializerInterface $serializer, array $formats, MessageBusInterface $messageBus = null, callable $publisher = null, ?GraphQlSubscriptionManagerInterface $graphQlSubscriptionManager = null, ?GraphQlMercureSubscriptionIriGeneratorInterface $graphQlMercureSubscriptionIriGenerator = null, ExpressionLanguage $expressionLanguage = null)
{
if (null === $messageBus && null === $publisher) {
throw new InvalidArgumentException('A message bus or a publisher must be provided.');
}
$this->resourceClassResolver = $resourceClassResolver;
$this->iriConverter = $iriConverter;
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->serializer = $serializer;
$this->formats = $formats;
$this->messageBus = $messageBus;
$this->publisher = $publisher;
$this->expressionLanguage = $expressionLanguage ?? (class_exists(ExpressionLanguage::class) ? new ExpressionLanguage() : null);
$this->graphQlSubscriptionManager = $graphQlSubscriptionManager;
$this->graphQlMercureSubscriptionIriGenerator = $graphQlMercureSubscriptionIriGenerator;
$this->reset();
}
/**
* Collects created, updated and deleted objects.
*/
public function onFlush(EventArgs $eventArgs): void
{
if ($eventArgs instanceof OrmOnFlushEventArgs) {
$uow = $eventArgs->getEntityManager()->getUnitOfWork();
} elseif ($eventArgs instanceof MongoDbOdmOnFlushEventArgs) {
$uow = $eventArgs->getDocumentManager()->getUnitOfWork();
} else {
return;
}
$methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityInsertions' : 'getScheduledDocumentInsertions';
foreach ($uow->{$methodName}() as $object) {
$this->storeObjectToPublish($object, 'createdObjects');
}
$methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityUpdates' : 'getScheduledDocumentUpdates';
foreach ($uow->{$methodName}() as $object) {
$this->storeObjectToPublish($object, 'updatedObjects');
}
$methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityDeletions' : 'getScheduledDocumentDeletions';
foreach ($uow->{$methodName}() as $object) {
$this->storeObjectToPublish($object, 'deletedObjects');
}
}
/**
* Publishes updates for changes collected on flush, and resets the store.
*/
public function postFlush(): void
{
try {
foreach ($this->createdObjects as $object) {
$this->publishUpdate($object, $this->createdObjects[$object], 'create');
}
foreach ($this->updatedObjects as $object) {
$this->publishUpdate($object, $this->updatedObjects[$object], 'update');
}
foreach ($this->deletedObjects as $object) {
$this->publishUpdate($object, $this->deletedObjects[$object], 'delete');
}
} finally {
$this->reset();
}
}
private function reset(): void
{
$this->createdObjects = new \SplObjectStorage();
$this->updatedObjects = new \SplObjectStorage();
$this->deletedObjects = new \SplObjectStorage();
}
/**
* @param object $object
*/
private function storeObjectToPublish($object, string $property): void
{
if (null === $resourceClass = $this->getResourceClass($object)) {
return;
}
$options = $this->resourceMetadataFactory->create($resourceClass)->getAttribute('mercure', false);
if (\is_string($options)) {
if (null === $this->expressionLanguage) {
throw new RuntimeException('The Expression Language component is not installed. Try running "composer require symfony/expression-language".');
}
$options = $this->expressionLanguage->evaluate($options, ['object' => $object]);
}
if (false === $options) {
return;
}
if (true === $options) {
$options = [];
}
if (!\is_array($options)) {
throw new InvalidArgumentException(sprintf('The value of the "mercure" attribute of the "%s" resource class must be a boolean, an array of options or an expression returning this array, "%s" given.', $resourceClass, \gettype($options)));
}
foreach ($options as $key => $value) {
if (0 === $key) {
if (method_exists(Update::class, 'isPrivate')) {
throw new \InvalidArgumentException('Targets do not exist anymore since Mercure 0.10. Mark the update as private instead or downgrade the Mercure Component to version 0.3');
}
@trigger_error('Targets do not exist anymore since Mercure 0.10. Mark the update as private instead.', \E_USER_DEPRECATED);
break;
}
if (!isset(self::ALLOWED_KEYS[$key])) {
throw new InvalidArgumentException(sprintf('The option "%s" set in the "mercure" attribute of the "%s" resource does not exist. Existing options: "%s"', $key, $resourceClass, implode('", "', self::ALLOWED_KEYS)));
}
}
if ('deletedObjects' === $property) {
$this->deletedObjects[(object) [
'id' => $this->iriConverter->getIriFromItem($object),
'iri' => $this->iriConverter->getIriFromItem($object, UrlGeneratorInterface::ABS_URL),
]] = $options;
return;
}
$this->{$property}[$object] = $options;
}
/**
* @param object $object
*/
private function publishUpdate($object, array $options, string $type): void
{
if ($object instanceof \stdClass) {
// By convention, if the object has been deleted, we send only its IRI.
// This may change in the feature, because it's not JSON Merge Patch compliant,
// and I'm not a fond of this approach.
$iri = $options['topics'] ?? $object->iri;
/** @var string $data */
$data = json_encode(['@id' => $object->id]);
} else {
$resourceClass = $this->getObjectClass($object);
$context = $options['normalization_context'] ?? $this->resourceMetadataFactory->create($resourceClass)->getAttribute('normalization_context', []);
$iri = $options['topics'] ?? $this->iriConverter->getIriFromItem($object, UrlGeneratorInterface::ABS_URL);
$data = $options['data'] ?? $this->serializer->serialize($object, key($this->formats), $context);
}
$updates = array_merge([$this->buildUpdate($iri, $data, $options)], $this->getGraphQlSubscriptionUpdates($object, $options, $type));
foreach ($updates as $update) {
$this->messageBus ? $this->dispatch($update) : ($this->publisher)($update);
}
}
/**
* @param object $object
*
* @return Update[]
*/
private function getGraphQlSubscriptionUpdates($object, array $options, string $type): array
{
if ('update' !== $type || !$this->graphQlSubscriptionManager || !$this->graphQlMercureSubscriptionIriGenerator) {
return [];
}
$payloads = $this->graphQlSubscriptionManager->getPushPayloads($object);
$updates = [];
foreach ($payloads as [$subscriptionId, $data]) {
$updates[] = $this->buildUpdate(
$this->graphQlMercureSubscriptionIriGenerator->generateTopicIri($subscriptionId),
(string) (new JsonResponse($data))->getContent(),
$options
);
}
return $updates;
}
/**
* @param string|string[] $iri
*/
private function buildUpdate($iri, string $data, array $options): Update
{
if (method_exists(Update::class, 'isPrivate')) {
return new Update($iri, $data, $options['private'] ?? false, $options['id'] ?? null, $options['type'] ?? null, $options['retry'] ?? null);
}
// Mercure Component < 0.4.
/* @phpstan-ignore-next-line */
return new Update($iri, $data, $options);
}
}