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

api-platform / core / 15133993414

20 May 2025 09:30AM UTC coverage: 26.313% (-1.2%) from 27.493%
15133993414

Pull #7161

github

web-flow
Merge e2c03d45f into 5459ba375
Pull Request #7161: fix(metadata): infer parameter string type from schema

0 of 2 new or added lines in 1 file covered. (0.0%)

11019 existing lines in 363 files now uncovered.

12898 of 49018 relevant lines covered (26.31%)

34.33 hits per line

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

74.19
/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) {
470✔
71
            throw new InvalidArgumentException('A message bus or a hub registry must be provided.');
×
72
        }
73

UNCOV
74
        $this->resourceClassResolver = $resourceClassResolver;
470✔
75

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

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

UNCOV
85
            $this->expressionLanguage->addFunction(
470✔
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))
470✔
UNCOV
87
            );
470✔
UNCOV
88
            $this->expressionLanguage->addFunction(
470✔
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))
470✔
UNCOV
90
            );
470✔
91
        }
92

UNCOV
93
        if (false === $this->includeType) {
470✔
94
            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.');
×
95
        }
96
    }
97

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
191
        if (false === $options) {
454✔
UNCOV
192
            return;
451✔
193
        }
194

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

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

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

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

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

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

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

226
            return;
×
227
        }
228

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

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

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

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

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

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

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

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

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

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

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

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

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

300
        $payloads = $this->graphQlSubscriptionManager->getPushPayloads($object);
1✔
301

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

311
        return $updates;
1✔
312
    }
313

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