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

api-platform / core / 16531587208

25 Jul 2025 09:05PM UTC coverage: 0.0% (-22.1%) from 22.07%
16531587208

Pull #7225

github

web-flow
Merge 23f449a58 into 02a764950
Pull Request #7225: feat: json streamer

0 of 294 new or added lines in 31 files covered. (0.0%)

11514 existing lines in 375 files now uncovered.

0 of 51976 relevant lines covered (0.0%)

0.0 hits per line

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

0.0
/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
        'id' => true,
54
        'type' => true,
55
        'retry' => true,
56
        'normalization_context' => true,
57
        'hub' => true,
58
        'enable_async_update' => true,
59
    ];
60
    private readonly ?ExpressionLanguage $expressionLanguage;
61
    private \SplObjectStorage $createdObjects;
62
    private \SplObjectStorage $updatedObjects;
63
    private \SplObjectStorage $deletedObjects;
64

65
    /**
66
     * @param array<string, string[]|string> $formats
67
     */
68
    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)
69
    {
UNCOV
70
        if (null === $messageBus && null === $hubRegistry) {
×
71
            throw new InvalidArgumentException('A message bus or a hub registry must be provided.');
×
72
        }
73

UNCOV
74
        $this->resourceClassResolver = $resourceClassResolver;
×
75

UNCOV
76
        $this->resourceMetadataFactory = $resourceMetadataFactory;
×
UNCOV
77
        $this->messageBus = $messageBus;
×
UNCOV
78
        $this->expressionLanguage = $expressionLanguage ?? (class_exists(ExpressionLanguage::class) ? new ExpressionLanguage() : null);
×
UNCOV
79
        $this->reset();
×
80

UNCOV
81
        if ($this->expressionLanguage) {
×
UNCOV
82
            $rawurlencode = ExpressionFunction::fromPhp('rawurlencode', 'escape');
×
UNCOV
83
            $this->expressionLanguage->addFunction($rawurlencode);
×
84

UNCOV
85
            $this->expressionLanguage->addFunction(
×
UNCOV
86
                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))
×
UNCOV
87
            );
×
UNCOV
88
            $this->expressionLanguage->addFunction(
×
UNCOV
89
                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))
×
UNCOV
90
            );
×
91
        }
92
    }
93

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

UNCOV
108
        $methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityInsertions' : 'getScheduledDocumentInsertions';
×
UNCOV
109
        foreach ($uow->{$methodName}() as $object) {
×
UNCOV
110
            $this->storeObjectToPublish($object, 'createdObjects');
×
111
        }
112

UNCOV
113
        $methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityUpdates' : 'getScheduledDocumentUpdates';
×
UNCOV
114
        foreach ($uow->{$methodName}() as $object) {
×
115
            $this->storeObjectToPublish($object, 'updatedObjects');
×
116
        }
117

UNCOV
118
        $methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityDeletions' : 'getScheduledDocumentDeletions';
×
UNCOV
119
        foreach ($uow->{$methodName}() as $object) {
×
120
            $this->storeObjectToPublish($object, 'deletedObjects');
×
121
        }
122
    }
123

124
    /**
125
     * Publishes updates for changes collected on flush, and resets the store.
126
     */
127
    public function postFlush(): void
128
    {
129
        try {
UNCOV
130
            $creatingObjects = clone $this->createdObjects;
×
UNCOV
131
            foreach ($creatingObjects as $object) {
×
132
                if ($this->createdObjects->contains($object)) {
×
133
                    $this->createdObjects->detach($object);
×
134
                }
135
                $this->publishUpdate($object, $creatingObjects[$object], 'create');
×
136
            }
137

UNCOV
138
            $updatingObjects = clone $this->updatedObjects;
×
UNCOV
139
            foreach ($updatingObjects as $object) {
×
140
                if ($this->updatedObjects->contains($object)) {
×
141
                    $this->updatedObjects->detach($object);
×
142
                }
143
                $this->publishUpdate($object, $updatingObjects[$object], 'update');
×
144
            }
145

UNCOV
146
            $deletingObjects = clone $this->deletedObjects;
×
UNCOV
147
            foreach ($deletingObjects as $object) {
×
148
                $options = $this->deletedObjects[$object];
×
149
                if ($this->deletedObjects->contains($object)) {
×
150
                    $this->deletedObjects->detach($object);
×
151
                }
152
                $this->publishUpdate($object, $deletingObjects[$object], 'delete');
×
153
            }
154
        } finally {
UNCOV
155
            $this->reset();
×
156
        }
157
    }
158

159
    private function reset(): void
160
    {
UNCOV
161
        $this->createdObjects = new \SplObjectStorage();
×
UNCOV
162
        $this->updatedObjects = new \SplObjectStorage();
×
UNCOV
163
        $this->deletedObjects = new \SplObjectStorage();
×
164
    }
165

166
    private function storeObjectToPublish(object $object, string $property): void
167
    {
UNCOV
168
        if (null === $resourceClass = $this->getResourceClass($object)) {
×
UNCOV
169
            return;
×
170
        }
171

UNCOV
172
        $operation = $this->resourceMetadataFactory->create($resourceClass)->getOperation();
×
173
        try {
UNCOV
174
            $options = $operation->getMercure() ?? false;
×
175
        } catch (OperationNotFoundException) {
×
176
            return;
×
177
        }
178

UNCOV
179
        if (\is_string($options)) {
×
180
            if (null === $this->expressionLanguage) {
×
181
                throw new RuntimeException('The Expression Language component is not installed. Try running "composer require symfony/expression-language".');
×
182
            }
183

184
            $options = $this->expressionLanguage->evaluate($options, ['object' => $object]);
×
185
        }
186

UNCOV
187
        if (false === $options) {
×
UNCOV
188
            return;
×
189
        }
190

191
        if (true === $options) {
×
192
            $options = [];
×
193
        }
194

195
        if (!\is_array($options)) {
×
196
            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)));
×
197
        }
198

199
        foreach ($options as $key => $value) {
×
200
            if (!isset(self::ALLOWED_KEYS[$key])) {
×
201
                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))));
×
202
            }
203
        }
204

205
        $options['enable_async_update'] ??= true;
×
206

207
        if ('deletedObjects' === $property) {
×
208
            $types = $operation instanceof HttpOperation ? $operation->getTypes() : null;
×
209
            if (null === $types) {
×
210
                $types = [$operation->getShortName()];
×
211
            }
212

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

216
            $this->deletedObjects[(object) [
×
217
                'id' => $this->iriConverter->getIriFromResource($object),
×
218
                'iri' => $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL),
×
219
                'type' => 1 === \count($types) ? $types[0] : $types,
×
220
            ]] = $options;
×
221

222
            return;
×
223
        }
224

225
        $this->{$property}[$object] = $options;
×
226
    }
227

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

241
            // We need to evaluate it here, because in storeObjectToPublish() the resource would not have been persisted yet
242
            $this->evaluateTopics($options, $object);
×
243

244
            $iri = $options['topics'] ?? $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL);
×
245
            $data = $options['data'] ?? $this->serializer->serialize($object, key($this->formats), $context);
×
246
        }
247

248
        $updates = array_merge([$this->buildUpdate($iri, $data, $options)], $this->getGraphQlSubscriptionUpdates($object, $options, $type));
×
249
        foreach ($updates as $update) {
×
250
            if ($options['enable_async_update'] && $this->messageBus) {
×
251
                $this->dispatch($update);
×
252
                continue;
×
253
            }
254

255
            $this->hubRegistry->getHub($options['hub'] ?? null)->publish($update);
×
256
        }
257
    }
258

259
    private function evaluateTopics(array &$options, object $object): void
260
    {
261
        if (!($options['topics'] ?? false)) {
×
262
            return;
×
263
        }
264

265
        $topics = [];
×
266
        foreach ((array) $options['topics'] as $topic) {
×
267
            if (!\is_string($topic)) {
×
268
                $topics[] = $topic;
×
269
                continue;
×
270
            }
271

272
            if (!str_starts_with($topic, '@=')) {
×
273
                $topics[] = $topic;
×
274
                continue;
×
275
            }
276

277
            if (null === $this->expressionLanguage) {
×
278
                throw new \LogicException('The "@=" expression syntax cannot be used without the Expression Language component. Try running "composer require symfony/expression-language".');
×
279
            }
280

281
            $topics[] = $this->expressionLanguage->evaluate(substr($topic, 2), ['object' => $object]);
×
282
        }
283

284
        $options['topics'] = $topics;
×
285
    }
286

287
    /**
288
     * @return Update[]
289
     */
290
    private function getGraphQlSubscriptionUpdates(object $object, array $options, string $type): array
291
    {
292
        if ('update' !== $type || !$this->graphQlSubscriptionManager || !$this->graphQlMercureSubscriptionIriGenerator) {
×
293
            return [];
×
294
        }
295

296
        $payloads = $this->graphQlSubscriptionManager->getPushPayloads($object);
×
297

298
        $updates = [];
×
299
        foreach ($payloads as [$subscriptionId, $data]) {
×
300
            $updates[] = $this->buildUpdate(
×
301
                $this->graphQlMercureSubscriptionIriGenerator->generateTopicIri($subscriptionId),
×
302
                (string) (new JsonResponse($data))->getContent(),
×
303
                $options
×
304
            );
×
305
        }
306

307
        return $updates;
×
308
    }
309

310
    /**
311
     * @param string|string[] $iri
312
     */
313
    private function buildUpdate(string|array $iri, string $data, array $options): Update
314
    {
315
        return new Update($iri, $data, $options['private'] ?? false, $options['id'] ?? null, $options['type'] ?? null, $options['retry'] ?? null);
×
316
    }
317
}
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