Skip to content

feat(graphql): added support for graphql subscriptions to work for actions #6904

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/GraphQl/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use ApiPlatform\GraphQl\State\Provider\NoopProvider;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\GraphQl\Query;
use ApiPlatform\Metadata\GraphQl\QueryCollection;
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
use ApiPlatform\Metadata\IriConverterInterface;
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
Expand All @@ -26,6 +27,7 @@
use ApiPlatform\Metadata\Util\ClassInfoTrait;
use ApiPlatform\Serializer\CacheKeyTrait;
use ApiPlatform\Serializer\ItemNormalizer as BaseItemNormalizer;
use Doctrine\Common\Collections\Collection;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
Expand Down Expand Up @@ -106,6 +108,11 @@ public function normalize(mixed $object, ?string $format = null, array $context
$data[self::ITEM_IDENTIFIERS_KEY] = $this->identifiersExtractor->getIdentifiersFromItem($object, $context['operation'] ?? null);
}

if (isset($context['graphql_operation_name']) && 'mercure_subscription' === $context['graphql_operation_name'] && \is_object($object) && isset($data['id']) && !isset($data['_id'])) {
$data['_id'] = $data['id'];
$data['id'] = $this->iriConverter->getIriFromResource($object);
}

return $data;
}

Expand All @@ -120,10 +127,46 @@ protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata,
return [...$attributeValue];
}

// Handle relationships for mercure subscriptions
if ($operation instanceof QueryCollection && 'mercure_subscription' === $context['graphql_operation_name'] && $attributeValue instanceof Collection && !$attributeValue->isEmpty()) {
$relationContext = $context;
// Grab collection attributes
$relationContext['attributes'] = $context['attributes']['collection'];
// Iterate over the collection and normalize each item
$data['collection'] = $attributeValue
->map(fn ($item) => $this->normalize($item, $format, $relationContext))
// Convert the collection to an array
->toArray();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We tend to avoid doing things like this in our code base, prefer a simple foreach, especially if you transform the iterable to an array just fill your $data['collection'] it'll be one less complexity loop.


// Handle pagination if it's enabled in the query
return $this->addPagination($attributeValue, $data, $context);
}

// to-many are handled directly by the GraphQL resolver
return [];
}

private function addPagination(Collection $collection, array $data, array $context): array
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
private function addPagination(Collection $collection, array $data, array $context): array
private function addPagination(float $total, array $data, array $context): array

Use the value of count directly as you're not using anything else from the Collection.

{
if ($context['attributes']['paginationInfo'] ?? false) {
$data['paginationInfo'] = [];
if (\array_key_exists('hasNextPage', $context['attributes']['paginationInfo'])) {
$data['paginationInfo']['hasNextPage'] = $collection->count() > ($context['pagination']['itemsPerPage'] ?? 10);
}
if (\array_key_exists('itemsPerPage', $context['attributes']['paginationInfo'])) {
$data['paginationInfo']['itemsPerPage'] = $context['pagination']['itemsPerPage'] ?? 10;
}
if (\array_key_exists('lastPage', $context['attributes']['paginationInfo'])) {
$data['paginationInfo']['lastPage'] = (int) ceil($collection->count() / ($context['pagination']['itemsPerPage'] ?? 10));
}
if (\array_key_exists('totalCount', $context['attributes']['paginationInfo'])) {
$data['paginationInfo']['totalCount'] = $collection->count();
}
}

return $data;
}

/**
* {@inheritdoc}
*/
Expand Down
6 changes: 5 additions & 1 deletion src/GraphQl/State/Processor/SubscriptionProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use ApiPlatform\GraphQl\Subscription\OperationAwareSubscriptionManagerInterface;
use ApiPlatform\GraphQl\Subscription\SubscriptionManagerInterface;
use ApiPlatform\Metadata\GraphQl\Operation as GraphQlOperation;
use ApiPlatform\Metadata\GraphQl\Subscription;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;

Expand All @@ -32,7 +33,7 @@ public function __construct(private readonly ProcessorInterface $decorated, priv
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = [])
{
$data = $this->decorated->process($data, $operation, $uriVariables, $context);
if (!$operation instanceof GraphQlOperation || !($mercure = $operation->getMercure())) {
if (!$operation instanceof Subscription || !($mercure = $operation->getMercure())) {
return $data;
}

Expand All @@ -49,6 +50,9 @@ public function process(mixed $data, Operation $operation, array $uriVariables =

$hub = \is_array($mercure) ? ($mercure['hub'] ?? null) : null;
$data['mercureUrl'] = $this->mercureSubscriptionIriGenerator->generateMercureUrl($subscriptionId, $hub);
if ($operation instanceof Subscription) {
$data['isCollection'] = $operation->isCollection();
}
}

return $data;
Expand Down
14 changes: 14 additions & 0 deletions src/GraphQl/Subscription/SubscriptionIdentifierGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,21 @@ final class SubscriptionIdentifierGenerator implements SubscriptionIdentifierGen
public function generateSubscriptionIdentifier(array $fields): string
{
unset($fields['mercureUrl'], $fields['clientSubscriptionId']);
$fields = $this->removeTypename($fields);

return hash('sha256', print_r($fields, true));
}

private function removeTypename(array $data): array
{
foreach ($data as $key => $value) {
if ('__typename' === $key) {
unset($data[$key]);
} elseif (\is_array($value)) {
$data[$key] = $this->removeTypename($value);
}
}

return $data;
}
}
Loading