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

api-platform / core / 10681662455

03 Sep 2024 11:02AM UTC coverage: 70.804% (-1.7%) from 72.507%
10681662455

push

github

soyuka
fix(symfony): register doctrine common event listeners

3075 of 4343 relevant lines covered (70.8%)

75.56 hits per line

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

0.0
/src/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\Doctrine\EventListener;
15

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

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

69
    /**
70
     * @param array<string, string[]|string> $formats
71
     */
72
    public function __construct(LegacyResourceClassResolverInterface|ResourceClassResolverInterface $resourceClassResolver, private readonly LegacyIriConverterInterface|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)
73
    {
74
        if (null === $messageBus && null === $hubRegistry) {
×
75
            throw new InvalidArgumentException('A message bus or a hub registry must be provided.');
×
76
        }
77

78
        $this->resourceClassResolver = $resourceClassResolver;
×
79

80
        $this->resourceMetadataFactory = $resourceMetadataFactory;
×
81
        $this->messageBus = $messageBus;
×
82
        $this->expressionLanguage = $expressionLanguage ?? (class_exists(ExpressionLanguage::class) ? new ExpressionLanguage() : null);
×
83
        $this->reset();
×
84

85
        if ($this->expressionLanguage) {
×
86
            $rawurlencode = ExpressionFunction::fromPhp('rawurlencode', 'escape');
×
87
            $this->expressionLanguage->addFunction($rawurlencode);
×
88

89
            $this->expressionLanguage->addFunction(
×
90
                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))
×
91
            );
×
92
            $this->expressionLanguage->addFunction(
×
93
                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))
×
94
            );
×
95
        }
96

97
        if (false === $this->includeType) {
×
98
            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.');
×
99
        }
100
    }
101

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

116
        $methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityInsertions' : 'getScheduledDocumentInsertions';
×
117
        foreach ($uow->{$methodName}() as $object) {
×
118
            $this->storeObjectToPublish($object, 'createdObjects');
×
119
        }
120

121
        $methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityUpdates' : 'getScheduledDocumentUpdates';
×
122
        foreach ($uow->{$methodName}() as $object) {
×
123
            $this->storeObjectToPublish($object, 'updatedObjects');
×
124
        }
125

126
        $methodName = $eventArgs instanceof OrmOnFlushEventArgs ? 'getScheduledEntityDeletions' : 'getScheduledDocumentDeletions';
×
127
        foreach ($uow->{$methodName}() as $object) {
×
128
            $this->storeObjectToPublish($object, 'deletedObjects');
×
129
        }
130
    }
131

132
    /**
133
     * Publishes updates for changes collected on flush, and resets the store.
134
     */
135
    public function postFlush(): void
136
    {
137
        try {
138
            foreach ($this->createdObjects as $object) {
×
139
                $this->publishUpdate($object, $this->createdObjects[$object], 'create');
×
140
            }
141

142
            foreach ($this->updatedObjects as $object) {
×
143
                $this->publishUpdate($object, $this->updatedObjects[$object], 'update');
×
144
            }
145

146
            foreach ($this->deletedObjects as $object) {
×
147
                $this->publishUpdate($object, $this->deletedObjects[$object], 'delete');
×
148
            }
149
        } finally {
150
            $this->reset();
×
151
        }
152
    }
153

154
    private function reset(): void
155
    {
156
        $this->createdObjects = new \SplObjectStorage();
×
157
        $this->updatedObjects = new \SplObjectStorage();
×
158
        $this->deletedObjects = new \SplObjectStorage();
×
159
    }
160

161
    private function storeObjectToPublish(object $object, string $property): void
162
    {
163
        if (null === $resourceClass = $this->getResourceClass($object)) {
×
164
            return;
×
165
        }
166

167
        $operation = $this->resourceMetadataFactory->create($resourceClass)->getOperation();
×
168
        try {
169
            $options = $operation->getMercure() ?? false;
×
170
        } catch (OperationNotFoundException) {
×
171
            return;
×
172
        }
173

174
        if (\is_string($options)) {
×
175
            if (null === $this->expressionLanguage) {
×
176
                throw new RuntimeException('The Expression Language component is not installed. Try running "composer require symfony/expression-language".');
×
177
            }
178

179
            $options = $this->expressionLanguage->evaluate($options, ['object' => $object]);
×
180
        }
181

182
        if (false === $options) {
×
183
            return;
×
184
        }
185

186
        if (true === $options) {
×
187
            $options = [];
×
188
        }
189

190
        if (!\is_array($options)) {
×
191
            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)));
×
192
        }
193

194
        foreach ($options as $key => $value) {
×
195
            if (!isset(self::ALLOWED_KEYS[$key])) {
×
196
                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)));
×
197
            }
198
        }
199

200
        $options['enable_async_update'] ??= true;
×
201

202
        if ('deletedObjects' === $property) {
×
203
            $types = $operation instanceof HttpOperation ? $operation->getTypes() : null;
×
204
            if (null === $types) {
×
205
                $types = [$operation->getShortName()];
×
206
            }
207

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

211
            $this->deletedObjects[(object) [
×
212
                'id' => $this->iriConverter->getIriFromResource($object),
×
213
                'iri' => $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL),
×
214
                'type' => 1 === \count($types) ? $types[0] : $types,
×
215
            ]] = $options;
×
216

217
            return;
×
218
        }
219

220
        $this->{$property}[$object] = $options;
×
221
    }
222

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

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

239
            $iri = $options['topics'] ?? $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL);
×
240
            $data = $options['data'] ?? $this->serializer->serialize($object, key($this->formats), $context);
×
241
        }
242

243
        $updates = array_merge([$this->buildUpdate($iri, $data, $options)], $this->getGraphQlSubscriptionUpdates($object, $options, $type));
×
244

245
        foreach ($updates as $update) {
×
246
            if ($options['enable_async_update'] && $this->messageBus) {
×
247
                $this->dispatch($update);
×
248
                continue;
×
249
            }
250

251
            $this->hubRegistry->getHub($options['hub'] ?? null)->publish($update);
×
252
        }
253
    }
254

255
    private function evaluateTopics(array &$options, object $object): void
256
    {
257
        if (!($options['topics'] ?? false)) {
×
258
            return;
×
259
        }
260

261
        $topics = [];
×
262
        foreach ((array) $options['topics'] as $topic) {
×
263
            if (!\is_string($topic)) {
×
264
                $topics[] = $topic;
×
265
                continue;
×
266
            }
267

268
            if (!str_starts_with($topic, '@=')) {
×
269
                $topics[] = $topic;
×
270
                continue;
×
271
            }
272

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

277
            $topics[] = $this->expressionLanguage->evaluate(substr($topic, 2), ['object' => $object]);
×
278
        }
279

280
        $options['topics'] = $topics;
×
281
    }
282

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

292
        $payloads = $this->graphQlSubscriptionManager->getPushPayloads($object);
×
293

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

303
        return $updates;
×
304
    }
305

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