• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 14635100171

24 Apr 2025 06:39AM UTC coverage: 8.271% (+0.02%) from 8.252%
14635100171

Pull #6904

github

web-flow
Merge c9cefd82e into a3e5e53ea
Pull Request #6904: feat(graphql): added support for graphql subscriptions to work for actions

0 of 73 new or added lines in 3 files covered. (0.0%)

1999 existing lines in 144 files now uncovered.

13129 of 158728 relevant lines covered (8.27%)

13.6 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.39
/src/Symfony/Doctrine/EventListener/PublishMercureUpdatesListener.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
declare(strict_types=1);
13

14
namespace ApiPlatform\Symfony\Doctrine\EventListener;
15

16
use ApiPlatform\Doctrine\Common\Messenger\DispatchTrait;
17
use ApiPlatform\GraphQl\Subscription\MercureSubscriptionIriGeneratorInterface as GraphQlMercureSubscriptionIriGeneratorInterface;
18
use ApiPlatform\GraphQl\Subscription\SubscriptionManagerInterface as GraphQlSubscriptionManagerInterface;
19
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
20
use ApiPlatform\Metadata\Exception\OperationNotFoundException;
21
use ApiPlatform\Metadata\Exception\RuntimeException;
22
use ApiPlatform\Metadata\HttpOperation;
23
use ApiPlatform\Metadata\IriConverterInterface;
24
use ApiPlatform\Metadata\Operation;
25
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
26
use ApiPlatform\Metadata\ResourceClassResolverInterface;
27
use ApiPlatform\Metadata\UrlGeneratorInterface;
28
use ApiPlatform\Metadata\Util\ResourceClassInfoTrait;
29
use Doctrine\Common\EventArgs;
30
use Doctrine\ODM\MongoDB\Event\OnFlushEventArgs as MongoDbOdmOnFlushEventArgs;
31
use Doctrine\ORM\Event\OnFlushEventArgs as OrmOnFlushEventArgs;
32
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
33
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
34
use Symfony\Component\HttpFoundation\JsonResponse;
35
use Symfony\Component\Mercure\HubRegistry;
36
use Symfony\Component\Mercure\Update;
37
use Symfony\Component\Messenger\MessageBusInterface;
38
use Symfony\Component\Serializer\SerializerInterface;
39

40
/**
41
 * Publishes resources updates to the Mercure hub.
42
 *
43
 * @author Kévin Dunglas <dunglas@gmail.com>
44
 */
45
final class PublishMercureUpdatesListener
46
{
47
    use DispatchTrait;
48
    use ResourceClassInfoTrait;
49
    private const ALLOWED_KEYS = [
50
        'topics' => true,
51
        'data' => true,
52
        'private' => true,
53
        'private_fields' => true,
54
        'id' => true,
55
        'type' => true,
56
        'retry' => true,
57
        'normalization_context' => true,
58
        'hub' => true,
59
        'enable_async_update' => true,
60
    ];
61
    private readonly ?ExpressionLanguage $expressionLanguage;
62
    private \SplObjectStorage $createdObjects;
63
    private \SplObjectStorage $updatedObjects;
64
    private \SplObjectStorage $deletedObjects;
65

66
    /**
67
     * @param array<string, string[]|string> $formats
68
     */
69
    public function __construct(ResourceClassResolverInterface $resourceClassResolver, private readonly IriConverterInterface $iriConverter, ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly SerializerInterface $serializer, private readonly array $formats, ?MessageBusInterface $messageBus = null, private readonly ?HubRegistry $hubRegistry = null, private readonly ?GraphQlSubscriptionManagerInterface $graphQlSubscriptionManager = null, private readonly ?GraphQlMercureSubscriptionIriGeneratorInterface $graphQlMercureSubscriptionIriGenerator = null, ?ExpressionLanguage $expressionLanguage = null, private bool $includeType = false)
70
    {
71
        if (null === $messageBus && null === $hubRegistry) {
575✔
72
            throw new InvalidArgumentException('A message bus or a hub registry must be provided.');
×
73
        }
74

75
        $this->resourceClassResolver = $resourceClassResolver;
575✔
76

77
        $this->resourceMetadataFactory = $resourceMetadataFactory;
575✔
78
        $this->messageBus = $messageBus;
575✔
79
        $this->expressionLanguage = $expressionLanguage ?? (class_exists(ExpressionLanguage::class) ? new ExpressionLanguage() : null);
575✔
80
        $this->reset();
575✔
81

82
        if ($this->expressionLanguage) {
575✔
83
            $rawurlencode = ExpressionFunction::fromPhp('rawurlencode', 'escape');
575✔
84
            $this->expressionLanguage->addFunction($rawurlencode);
575✔
85

86
            $this->expressionLanguage->addFunction(
575✔
87
                new ExpressionFunction('get_operation', static fn (string $apiResource, string $name): string => \sprintf('getOperation(%s, %s)', $apiResource, $name), static fn (array $arguments, $apiResource, string $name): Operation => $resourceMetadataFactory->create($resourceClassResolver->getResourceClass($apiResource))->getOperation($name))
575✔
88
            );
575✔
89
            $this->expressionLanguage->addFunction(
575✔
90
                new ExpressionFunction('iri', static fn (string $apiResource, int $referenceType = UrlGeneratorInterface::ABS_URL, ?string $operation = null): string => \sprintf('iri(%s, %d, %s)', $apiResource, $referenceType, $operation), static fn (array $arguments, $apiResource, int $referenceType = UrlGeneratorInterface::ABS_URL, $operation = null): string => $iriConverter->getIriFromResource($apiResource, $referenceType, $operation))
575✔
91
            );
575✔
92
        }
93

94
        if (false === $this->includeType) {
575✔
95
            trigger_deprecation('api-platform/core', '3.1', 'Having mercure.include_type (always include @type in Mercure updates, even delete ones) set to false in the configuration is deprecated. It will be true by default in API Platform 4.0.');
×
96
        }
97
    }
98

99
    /**
100
     * Collects created, updated and deleted objects.
101
     */
102
    public function onFlush(EventArgs $eventArgs): void
103
    {
104
        if ($eventArgs instanceof OrmOnFlushEventArgs) {
575✔
105
            // @phpstan-ignore-next-line
106
            $uow = method_exists($eventArgs, 'getObjectManager') ? $eventArgs->getObjectManager()->getUnitOfWork() : $eventArgs->getEntityManager()->getUnitOfWork();
220✔
UNCOV
107
        } elseif ($eventArgs instanceof MongoDbOdmOnFlushEventArgs) {
355✔
UNCOV
108
            $uow = $eventArgs->getDocumentManager()->getUnitOfWork();
355✔
109
        } else {
110
            return;
×
111
        }
112

113
        $methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityInsertions' : 'getScheduledDocumentInsertions';
575✔
114
        foreach ($uow->{$methodName}() as $object) {
575✔
115
            $this->storeObjectToPublish($object, 'createdObjects');
534✔
116
        }
117

118
        $methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityUpdates' : 'getScheduledDocumentUpdates';
575✔
119
        foreach ($uow->{$methodName}() as $object) {
575✔
UNCOV
120
            $this->storeObjectToPublish($object, 'updatedObjects');
37✔
121
        }
122

123
        $methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityDeletions' : 'getScheduledDocumentDeletions';
575✔
124
        foreach ($uow->{$methodName}() as $object) {
575✔
UNCOV
125
            $this->storeObjectToPublish($object, 'deletedObjects');
6✔
126
        }
127
    }
128

129
    /**
130
     * Publishes updates for changes collected on flush, and resets the store.
131
     */
132
    public function postFlush(): void
133
    {
134
        try {
135
            $creatingObjects = clone $this->createdObjects;
575✔
136
            foreach ($creatingObjects as $object) {
575✔
UNCOV
137
                if ($this->createdObjects->contains($object)) {
3✔
UNCOV
138
                    $this->createdObjects->detach($object);
3✔
139
                }
UNCOV
140
                $this->publishUpdate($object, $creatingObjects[$object], 'create');
3✔
141
            }
142

143
            $updatingObjects = clone $this->updatedObjects;
575✔
144
            foreach ($updatingObjects as $object) {
575✔
UNCOV
145
                if ($this->updatedObjects->contains($object)) {
1✔
UNCOV
146
                    $this->updatedObjects->detach($object);
1✔
147
                }
UNCOV
148
                $this->publishUpdate($object, $updatingObjects[$object], 'update');
1✔
149
            }
150

151
            $deletingObjects = clone $this->deletedObjects;
575✔
152
            foreach ($deletingObjects as $object) {
575✔
153
                $options = $this->deletedObjects[$object];
×
154
                if ($this->deletedObjects->contains($object)) {
×
155
                    $this->deletedObjects->detach($object);
×
156
                }
157
                $this->publishUpdate($object, $deletingObjects[$object], 'delete');
×
158
            }
159
        } finally {
160
            $this->reset();
575✔
161
        }
162
    }
163

164
    private function reset(): void
165
    {
166
        $this->createdObjects = new \SplObjectStorage();
575✔
167
        $this->updatedObjects = new \SplObjectStorage();
575✔
168
        $this->deletedObjects = new \SplObjectStorage();
575✔
169
    }
170

171
    private function storeObjectToPublish(object $object, string $property): void
172
    {
173
        if (null === $resourceClass = $this->getResourceClass($object)) {
564✔
174
            return;
73✔
175
        }
176

177
        $operation = $this->resourceMetadataFactory->create($resourceClass)->getOperation();
557✔
178
        try {
179
            $options = $operation->getMercure() ?? false;
557✔
180
        } catch (OperationNotFoundException) {
×
181
            return;
×
182
        }
183

184
        if (\is_string($options)) {
557✔
185
            if (null === $this->expressionLanguage) {
×
186
                throw new RuntimeException('The Expression Language component is not installed. Try running "composer require symfony/expression-language".');
×
187
            }
188

189
            $options = $this->expressionLanguage->evaluate($options, ['object' => $object]);
×
190
        }
191

192
        if (false === $options) {
557✔
193
            return;
554✔
194
        }
195

UNCOV
196
        if (true === $options) {
4✔
UNCOV
197
            $options = [];
2✔
198
        }
199

UNCOV
200
        if (!\is_array($options)) {
4✔
201
            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)));
×
202
        }
203

UNCOV
204
        foreach ($options as $key => $value) {
4✔
UNCOV
205
            if (!isset(self::ALLOWED_KEYS[$key])) {
2✔
206
                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('", "', array_keys(self::ALLOWED_KEYS))));
×
207
            }
208
        }
209

UNCOV
210
        $options['enable_async_update'] ??= true;
4✔
211

UNCOV
212
        if ('deletedObjects' === $property) {
4✔
213
            $types = $operation instanceof HttpOperation ? $operation->getTypes() : null;
×
214
            if (null === $types) {
×
215
                $types = [$operation->getShortName()];
×
216
            }
217

218
            // We need to evaluate it here, because in publishUpdate() the resource would be already deleted
219
            $this->evaluateTopics($options, $object);
×
220

221
            $this->deletedObjects[(object) [
×
222
                'id' => $this->iriConverter->getIriFromResource($object),
×
223
                'iri' => $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL),
×
224
                'type' => 1 === \count($types) ? $types[0] : $types,
×
225
            ]] = $options;
×
226

227
            return;
×
228
        }
229

UNCOV
230
        $this->{$property}[$object] = $options;
4✔
231
    }
232

233
    private function publishUpdate(object $object, array $options, string $type): void
234
    {
UNCOV
235
        if ($object instanceof \stdClass) {
4✔
236
            // By convention, if the object has been deleted, we send only its IRI and its type.
237
            // This may change in the feature, because it's not JSON Merge Patch compliant,
238
            // and I'm not a fond of this approach.
239
            $iri = $options['topics'] ?? $object->iri;
×
240
            /** @var string $data */
241
            $data = json_encode(['@id' => $object->id] + ($this->includeType ? ['@type' => $object->type] : []), \JSON_THROW_ON_ERROR);
×
242
        } else {
UNCOV
243
            $resourceClass = $this->getObjectClass($object);
4✔
UNCOV
244
            $context = $options['normalization_context'] ?? $this->resourceMetadataFactory->create($resourceClass)->getOperation()->getNormalizationContext() ?? [];
4✔
245

246
            // We need to evaluate it here, because in storeObjectToPublish() the resource would not have been persisted yet
UNCOV
247
            $this->evaluateTopics($options, $object);
4✔
248

UNCOV
249
            $iri = $options['topics'] ?? $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL);
4✔
UNCOV
250
            $data = $options['data'] ?? $this->serializer->serialize($object, key($this->formats), $context);
4✔
251
        }
252

UNCOV
253
        $updates = array_merge([$this->buildUpdate($iri, $data, $options)], $this->getGraphQlSubscriptionUpdates($object, $options, $type));
4✔
UNCOV
254
        foreach ($updates as $update) {
4✔
UNCOV
255
            if ($options['enable_async_update'] && $this->messageBus) {
4✔
UNCOV
256
                $this->dispatch($update);
4✔
UNCOV
257
                continue;
4✔
258
            }
259

260
            $this->hubRegistry->getHub($options['hub'] ?? null)->publish($update);
×
261
        }
262
    }
263

264
    private function evaluateTopics(array &$options, object $object): void
265
    {
UNCOV
266
        if (!($options['topics'] ?? false)) {
4✔
UNCOV
267
            return;
2✔
268
        }
269

UNCOV
270
        $topics = [];
2✔
UNCOV
271
        foreach ((array) $options['topics'] as $topic) {
2✔
UNCOV
272
            if (!\is_string($topic)) {
2✔
273
                $topics[] = $topic;
×
274
                continue;
×
275
            }
276

UNCOV
277
            if (!str_starts_with($topic, '@=')) {
2✔
278
                $topics[] = $topic;
×
279
                continue;
×
280
            }
281

UNCOV
282
            if (null === $this->expressionLanguage) {
2✔
283
                throw new \LogicException('The "@=" expression syntax cannot be used without the Expression Language component. Try running "composer require symfony/expression-language".');
×
284
            }
285

UNCOV
286
            $topics[] = $this->expressionLanguage->evaluate(substr($topic, 2), ['object' => $object]);
2✔
287
        }
288

UNCOV
289
        $options['topics'] = $topics;
2✔
290
    }
291

292
    /**
293
     * @return Update[]
294
     */
295
    private function getGraphQlSubscriptionUpdates(object $object, array $options, string $type): array
296
    {
NEW
297
        if (!$this->graphQlSubscriptionManager || !$this->graphQlMercureSubscriptionIriGenerator) {
4✔
UNCOV
298
            return [];
×
299
        }
300

NEW
301
        $payloads = $this->graphQlSubscriptionManager->getPushPayloads($object, $type);
4✔
302

UNCOV
303
        $updates = [];
4✔
UNCOV
304
        foreach ($payloads as [$subscriptionId, $data]) {
4✔
UNCOV
305
            $updates[] = $this->buildUpdate(
1✔
UNCOV
306
                $this->graphQlMercureSubscriptionIriGenerator->generateTopicIri($subscriptionId),
1✔
UNCOV
307
                (string) (new JsonResponse($data))->getContent(),
1✔
UNCOV
308
                $options
1✔
UNCOV
309
            );
1✔
310
        }
311

UNCOV
312
        return $updates;
4✔
313
    }
314

315
    /**
316
     * @param string|string[] $iri
317
     */
318
    private function buildUpdate(string|array $iri, string $data, array $options): Update
319
    {
UNCOV
320
        return new Update($iri, $data, $options['private'] ?? false, $options['id'] ?? null, $options['type'] ?? null, $options['retry'] ?? null);
4✔
321
    }
322
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc