• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In
You are now the owner of this repo.

api-platform / core / 14754902837

30 Apr 2025 12:46PM UTC coverage: 7.015%. First build
14754902837

Pull #6904

github

web-flow
Merge 1789149e5 into 4d70f6fc3
Pull Request #6904: feat(graphql): added support for graphql subscriptions to work for actions

55 of 228 new or added lines in 8 files covered. (24.12%)

11200 of 159658 relevant lines covered (7.01%)

6.28 hits per line

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

0.77
/src/GraphQl/Subscription/SubscriptionManager.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\GraphQl\Subscription;
15

16
use ApiPlatform\GraphQl\Resolver\Util\IdentifierTrait;
17
use ApiPlatform\Metadata\GraphQl\Operation;
18
use ApiPlatform\Metadata\GraphQl\Subscription;
19
use ApiPlatform\Metadata\IriConverterInterface;
20
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
21
use ApiPlatform\Metadata\Util\ResourceClassInfoTrait;
22
use ApiPlatform\Metadata\Util\SortTrait;
23
use ApiPlatform\State\ProcessorInterface;
24
use GraphQL\Type\Definition\ResolveInfo;
25
use Psr\Cache\CacheItemPoolInterface;
26

27
/**
28
 * Manages all the queried subscriptions by creating their ID
29
 * and saving to a cache the information needed to publish updated data.
30
 *
31
 * @author Alan Poulain <contact@alanpoulain.eu>
32
 */
33
final class SubscriptionManager implements OperationAwareSubscriptionManagerInterface
34
{
35
    use IdentifierTrait;
36
    use ResourceClassInfoTrait;
37
    use SortTrait;
38

39
    public function __construct(private readonly CacheItemPoolInterface $subscriptionsCache, private readonly SubscriptionIdentifierGeneratorInterface $subscriptionIdentifierGenerator, private readonly ProcessorInterface $normalizeProcessor, private readonly IriConverterInterface $iriConverter, private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory)
40
    {
41
    }
240✔
42

43
    public function retrieveSubscriptionId(array $context, ?array $result, ?Operation $operation = null): ?string
44
    {
NEW
45
        $iri = $operation ? $this->getIdentifierFromOperation($operation, $context['args'] ?? []) : $this->getIdentifierFromContext($context);
×
NEW
46
        if (empty($iri)) {
×
NEW
47
            return null;
×
48
        }
49

50
        /** @var ResolveInfo $info */
51
        $info = $context['info'];
×
52
        $fields = $info->getFieldSelection(\PHP_INT_MAX);
×
53
        $this->arrayRecursiveSort($fields, 'ksort');
×
54

NEW
55
        $options = $operation ? ($operation->getMercure() ?? false) : false;
×
NEW
56
        $private = $options['private'] ?? false;
×
NEW
57
        $privateFields = $options['private_fields'] ?? [];
×
NEW
58
        $previousObject = $context['graphql_context']['previous_object'] ?? null;
×
NEW
59
        $privateFieldData = [];
×
NEW
60
        if ($private && $privateFields && $previousObject) {
×
NEW
61
            foreach ($options['private_fields'] as $privateField) {
×
NEW
62
                $fieldData = $this->getResourceId($privateField, $previousObject);
×
NEW
63
                $fields['__private_field_'.$privateField] = $fieldData;
×
NEW
64
                $privateFieldData[] = $fieldData;
×
65
            }
66
        }
NEW
67
        if ($operation instanceof Subscription && $operation->isCollection()) {
×
NEW
68
            $subscriptionId = $this->updateSubscriptionCollectionCacheData(
×
NEW
69
                $iri,
×
NEW
70
                $fields,
×
NEW
71
                $privateFieldData
×
NEW
72
            );
×
73
        } else {
NEW
74
            $subscriptionId = $this->updateSubscriptionItemCacheData(
×
NEW
75
                $iri,
×
NEW
76
                $fields,
×
NEW
77
                $result,
×
NEW
78
                $private,
×
NEW
79
                $privateFields,
×
NEW
80
                $previousObject
×
NEW
81
            );
×
82
        }
83

NEW
84
        return $subscriptionId;
×
85
    }
86

87
    public function getPushPayloads(object $object, string $type): array
88
    {
NEW
89
        if ('delete' === $type) {
×
NEW
90
            $payloads = $this->getDeletePushPayloads($object);
×
91
        } else {
NEW
92
            $payloads = $this->getCreatedOrUpdatedPayloads($object);
×
93
        }
94

NEW
95
        return $payloads;
×
96
    }
97

98
    /**
99
     * @return array<array>
100
     */
101
    private function getSubscriptionsFromIri(string $iri, array $fields = []): array
102
    {
NEW
103
        $subscriptionsCacheItem = $this->subscriptionsCache->getItem(
×
NEW
104
            $this->generatePrivateCacheKeyPart(
×
NEW
105
                $this->encodeIriToCacheKey($iri),
×
NEW
106
                $fields
×
NEW
107
            )
×
108

NEW
109
        );
×
110

111
        if ($subscriptionsCacheItem->isHit()) {
×
NEW
112
            return $subscriptionsCacheItem->get();
×
113
        }
114

NEW
115
        return [];
×
116
    }
117

118
    private function removeItemFromSubscriptionCache(string $iri): void
119
    {
NEW
120
        $cacheKey = $this->encodeIriToCacheKey($iri);
×
NEW
121
        if ($this->subscriptionsCache->hasItem($cacheKey)) {
×
NEW
122
            $this->subscriptionsCache->deleteItem($cacheKey);
×
123
        }
124
    }
125

126
    private function encodeIriToCacheKey(string $iri): string
127
    {
NEW
128
        return str_replace('/', '_', $iri);
×
129
    }
130

131
    private function getResourceId(mixed $privateField, object $previousObject): string
132
    {
NEW
133
        $id = $previousObject->{'get'.ucfirst($privateField)}()->getId();
×
NEW
134
        if ($id instanceof \Stringable) {
×
NEW
135
            return (string) $id;
×
136
        }
137

NEW
138
        return $id;
×
139
    }
140

141
    private function getCollectionIri(string $iri): string
142
    {
NEW
143
        return substr($iri, 0, strrpos($iri, '/'));
×
144
    }
145

146
    private function getCreatedOrUpdatedPayloads(object $object): array
147
    {
148
        $resourceClass = $this->getObjectClass($object);
×
149
        $resourceMetadata = $this->resourceMetadataCollectionFactory->create($resourceClass);
×
150
        $shortName = $resourceMetadata->getOperation()->getShortName();
×
151

NEW
152
        $mercure = $resourceMetadata->getOperation()->getMercure() ?? false;
×
NEW
153
        $private = $mercure['private'] ?? false;
×
NEW
154
        $privateFieldsConfig = $mercure['private_fields'] ?? [];
×
NEW
155
        $privateFieldData = [];
×
NEW
156
        if ($private && $privateFieldsConfig) {
×
NEW
157
            foreach ($privateFieldsConfig as $privateField) {
×
NEW
158
                $privateFieldData['__private_field_'.$privateField] = $this->getResourceId($privateField, $object);
×
159
            }
160
        }
161

NEW
162
        $iri = $this->iriConverter->getIriFromResource($object);
×
163
        // Add collection subscriptions
NEW
164
        $subscriptions = array_merge(
×
NEW
165
            $this->getSubscriptionsFromIri($this->getCollectionIri($iri), $privateFieldData),
×
NEW
166
            $this->getSubscriptionsFromIri($iri)
×
NEW
167
        );
×
168

169
        $payloads = [];
×
170
        foreach ($subscriptions as [$subscriptionId, $subscriptionFields, $subscriptionResult]) {
×
NEW
171
            if ($privateFieldData) {
×
NEW
172
                $fieldDiff = array_intersect_assoc($subscriptionFields, $privateFieldData);
×
NEW
173
                if ($fieldDiff !== $privateFieldData) {
×
NEW
174
                    continue;
×
175
                }
176
            }
177
            $resolverContext = ['fields' => $subscriptionFields, 'is_collection' => false, 'is_mutation' => false, 'is_subscription' => true];
×
NEW
178
            $operation = (new Subscription())->withName('mercure_subscription')->withShortName($shortName);
×
179
            $data = $this->normalizeProcessor->process($object, $operation, [], $resolverContext);
×
180

181
            unset($data['clientSubscriptionId']);
×
182

183
            if ($data !== $subscriptionResult) {
×
184
                $payloads[] = [$subscriptionId, $data];
×
185
            }
186
        }
187

188
        return $payloads;
×
189
    }
190

191
    private function getDeletePushPayloads(object $object): array
192
    {
NEW
193
        $iri = $object->id;
×
NEW
194
        $subscriptions = array_merge(
×
NEW
195
            $this->getSubscriptionsFromIri($iri),
×
NEW
196
            $this->getSubscriptionsFromIri($this->getCollectionIri($iri), $object->private),
×
NEW
197
        );
×
198

NEW
199
        $payloads = [];
×
NEW
200
        $payload = ['type' => 'delete', 'payload' => ['id' => $object->id, 'iri' => $object->iri, 'type' => $object->type]];
×
NEW
201
        foreach ($subscriptions as [$subscriptionId, $subscriptionFields, $subscriptionResult]) {
×
NEW
202
            $payloads[] = [$subscriptionId, $payload];
×
203
        }
NEW
204
        $this->removeItemFromSubscriptionCache($iri);
×
205

NEW
206
        return $payloads;
×
207
    }
208

209
    private function updateSubscriptionItemCacheData(
210
        string $iri,
211
        array $fields,
212
        ?array $result,
213
        bool $private,
214
        array $privateFields,
215
        ?object $previousObject,
216
    ): string {
NEW
217
        $subscriptionsCacheItem = $this->subscriptionsCache->getItem($this->encodeIriToCacheKey($iri));
×
NEW
218
        $subscriptions = [];
×
219
        if ($subscriptionsCacheItem->isHit()) {
×
220
            /*
221
             * @var array<array{string, array<string, string|array>, array<string, string|array>}>
222
             */
NEW
223
            $subscriptions = $subscriptionsCacheItem->get();
×
NEW
224
            foreach ($subscriptions as [$subscriptionId, $subscriptionFields, $subscriptionResult]) {
×
NEW
225
                if ($subscriptionFields === $fields) {
×
NEW
226
                    return $subscriptionId;
×
227
                }
228
            }
229
        }
230

NEW
231
        unset($result['clientSubscriptionId']);
×
NEW
232
        if ($private && $privateFields && $previousObject) {
×
NEW
233
            $subscriptionId = $this->subscriptionIdentifierGenerator->generateSubscriptionIdentifier($fields);
×
NEW
234
            foreach ($privateFields as $privateField) {
×
NEW
235
                unset($result['__private_field_'.$privateField]);
×
236
            }
237
        } else {
NEW
238
            $subscriptionId = $this->subscriptionIdentifierGenerator->generateSubscriptionIdentifier($fields);
×
239
        }
NEW
240
        $subscriptions[] = [$subscriptionId, $fields, $result];
×
NEW
241
        $subscriptionsCacheItem->set($subscriptions);
×
NEW
242
        $this->subscriptionsCache->save($subscriptionsCacheItem);
×
243

NEW
244
        return $subscriptionId;
×
245
    }
246

247
    private function updateSubscriptionCollectionCacheData(
248
        string $iri,
249
        array  $fields,
250
        array  $privateFieldData,
251
    ): string {
252

NEW
253
        $subscriptionCollectionCacheItem = $this->subscriptionsCache->getItem(
×
NEW
254
            $this->generatePrivateCacheKeyPart(
×
NEW
255
                $this->encodeIriToCacheKey($this->getCollectionIri($iri)),
×
NEW
256
                $privateFieldData
×
NEW
257
            ),
×
NEW
258
        );
×
NEW
259
        $collectionSubscriptions = [];
×
NEW
260
        if ($subscriptionCollectionCacheItem->isHit()) {
×
NEW
261
            $collectionSubscriptions = $subscriptionCollectionCacheItem->get();
×
NEW
262
            foreach ($collectionSubscriptions as [$subscriptionId, $subscriptionFields, $result]) {
×
NEW
263
                if ($subscriptionFields === $fields) {
×
NEW
264
                    return $subscriptionId;
×
265
                }
266
            }
267
        }
NEW
268
        $subscriptionId = $this->subscriptionIdentifierGenerator->generateSubscriptionIdentifier($fields + ['__collection' => true]);
×
NEW
269
        $collectionSubscriptions[] = [$subscriptionId, $fields, []];
×
NEW
270
        $subscriptionCollectionCacheItem->set($collectionSubscriptions);
×
NEW
271
        $this->subscriptionsCache->save($subscriptionCollectionCacheItem);
×
272

NEW
273
        return $subscriptionId;
×
274
    }
275

276
    private function generatePrivateCacheKeyPart(string $iriKey, array $fields = []): string
277
    {
NEW
278
        if (empty($fields)) {
×
NEW
279
            return $iriKey;
×
280
        }
NEW
281
        return $iriKey.'_'.implode('_', $fields);
×
282
    }
283

284
}
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

© 2026 Coveralls, Inc