Skip to content

refactor(metadata): no default graphql operation name #5348

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

Closed
wants to merge 2 commits into from
Closed
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
2 changes: 1 addition & 1 deletion src/GraphQl/Resolver/Factory/ItemResolverFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public function __invoke(?string $resourceClass = null, ?string $rootClass = nul
$resolverContext = ['source' => $source, 'args' => $args, 'info' => $info, 'is_collection' => false, 'is_mutation' => false, 'is_subscription' => false];

if (!$operation) {
$operation = new Query();
$operation = new Query(name: 'item_query');
}

$item = ($this->readStage)($resourceClass, $rootClass, $operation, $resolverContext);
Expand Down
2 changes: 1 addition & 1 deletion src/GraphQl/Subscription/SubscriptionManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public function getPushPayloads(object $object): array
foreach ($subscriptions as [$subscriptionId, $subscriptionFields, $subscriptionResult]) {
$resolverContext = ['fields' => $subscriptionFields, 'is_collection' => false, 'is_mutation' => false, 'is_subscription' => true];
/** @var Operation */
$operation = (new Subscription())->withName('update_subscription')->withShortName($shortName);
$operation = new Subscription(name: 'update', shortName: $shortName);
$data = ($this->serializeStage)($object, $resourceClass, $operation, $resolverContext);
unset($data['clientSubscriptionId']);

Expand Down
7 changes: 2 additions & 5 deletions src/GraphQl/Type/FieldsBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ public function getItemQueryFields(string $resourceClass, Operation $operation,
return [];
}

// TODO: it'd be nice to get rid of this hard coded name
Copy link
Member

Choose a reason for hiding this comment

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

Why not using instanceof here?

$fieldName = lcfirst('item_query' === $operation->getName() ? $operation->getShortName() : $operation->getName().$operation->getShortName());

if ($fieldConfiguration = $this->getResourceFieldConfiguration(null, $operation->getDescription(), $operation->getDeprecationReason(), new Type(Type::BUILTIN_TYPE_OBJECT, true, $resourceClass), $resourceClass, false, $operation)) {
Expand Down Expand Up @@ -147,10 +148,6 @@ public function getSubscriptionFields(string $resourceClass, Operation $operatio
}

$subscriptionName = $operation->getName();
// TODO: 3.0 change this
if ('update_subscription' === $subscriptionName) {
$subscriptionName = 'update';
}

$subscriptionFields[$subscriptionName.$operation->getShortName().'Subscribe'] = $fieldConfiguration;

Expand Down Expand Up @@ -291,7 +288,7 @@ private function getResourceFieldConfiguration(?string $property, ?string $field
$resourceOperation = $rootOperation;
if ($resourceClass && $depth >= 1 && $this->resourceClassResolver->isResourceClass($resourceClass)) {
$resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
$resourceOperation = $resourceMetadataCollection->getOperation($isCollectionType ? 'collection_query' : 'item_query');
$resourceOperation = $resourceMetadataCollection->getGraphQlOperation(null, $isCollectionType);
}

if (!$resourceOperation instanceof Operation) {
Expand Down
19 changes: 10 additions & 9 deletions src/GraphQl/Type/TypeBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use ApiPlatform\Metadata\GraphQl\Mutation;
use ApiPlatform\Metadata\GraphQl\Operation;
use ApiPlatform\Metadata\GraphQl\Query;
use ApiPlatform\Metadata\GraphQl\QueryCollection;
use ApiPlatform\Metadata\GraphQl\Subscription;
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
use ApiPlatform\State\Pagination\Pagination;
Expand Down Expand Up @@ -73,10 +74,12 @@ public function getResourceObjectType(?string $resourceClass, ResourceMetadataCo
$shortName .= 'Payload';
}

if ('item_query' === $operationName || 'collection_query' === $operationName) {
if (!$operation->getResolver() && ($operation instanceof Query || $operation instanceof QueryCollection)) {
// Test if the collection/item has different groups
if ($resourceMetadataCollection->getOperation($operation instanceof CollectionOperationInterface ? 'item_query' : 'collection_query')->getNormalizationContext() !== $operation->getNormalizationContext()) {
$shortName .= $operation instanceof CollectionOperationInterface ? 'Collection' : 'Item';
$isCollection = $operation instanceof CollectionOperationInterface;
$otherOperation = $resourceMetadataCollection->getGraphQlOperation(null, !$isCollection);
if ($otherOperation->getNormalizationContext() !== $operation->getNormalizationContext()) {
$shortName .= $isCollection ? 'Collection' : 'Item';
}
}

Expand Down Expand Up @@ -104,27 +107,25 @@ public function getResourceObjectType(?string $resourceClass, ResourceMetadataCo
'name' => $shortName,
'description' => $operation->getDescription(),
'resolveField' => $this->defaultFieldResolver,
'fields' => function () use ($resourceClass, $operation, $operationName, $resourceMetadataCollection, $input, $wrapData, $depth, $ioMetadata) {
'fields' => function () use ($resourceClass, $operation, $resourceMetadataCollection, $input, $wrapData, $depth, $ioMetadata) {
if ($wrapData) {
$queryNormalizationContext = $this->getQueryOperation($resourceMetadataCollection)?->getNormalizationContext() ?? [];

try {
$mutationNormalizationContext = $operation instanceof Mutation || $operation instanceof Subscription ? ($resourceMetadataCollection->getOperation($operationName)->getNormalizationContext() ?? []) : [];
$mutationNormalizationContext = $operation instanceof Mutation || $operation instanceof Subscription ? ($operation->getNormalizationContext() ?? []) : [];
} catch (OperationNotFoundException) {
$mutationNormalizationContext = [];
}
// Use a new type for the wrapped object only if there is a specific normalization context for the mutation or the subscription.
// If not, use the query type in order to ensure the client cache could be used.
$useWrappedType = $queryNormalizationContext !== $mutationNormalizationContext;

$wrappedOperationName = $operationName;
$wrappedOperation = $operation;

if (!$useWrappedType) {
$wrappedOperationName = $operation instanceof Query ? $operationName : 'item_query';
$wrappedOperation = $resourceMetadataCollection->getGraphQlOperation(null, forceCollection: $operation instanceof Query);
Copy link
Member

Choose a reason for hiding this comment

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

Why using a named argument here and not elsewhere?

Copy link
Member Author

Choose a reason for hiding this comment

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

I want to start using them I can revert for the codestyle

Copy link
Member

@alanpoulain alanpoulain Jan 20, 2023

Choose a reason for hiding this comment

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

Personally I think it's better like this indeed. But you should uniformize the call.

}

$wrappedOperation = $resourceMetadataCollection->getOperation($wrappedOperationName);

$fields = [
lcfirst($wrappedOperation->getShortName()) => $this->getResourceObjectType($resourceClass, $resourceMetadataCollection, $wrappedOperation instanceof Operation ? $wrappedOperation : null, $input, true, $depth),
];
Expand Down
23 changes: 9 additions & 14 deletions src/GraphQl/Type/TypeConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,7 @@ public function convertType(Type $type, bool $input, Operation $rootOperation, s
} catch (ResourceClassNotFoundException|OperationNotFoundException) {
}
/** @var Query $enumOperation */
$enumOperation = (new Query())
->withClass($type->getClassName())
->withShortName($operation?->getShortName() ?? (new \ReflectionClass($type->getClassName()))->getShortName())
->withDescription($operation?->getDescription());
$enumOperation = new Query(name: 'item_query', class: $type->getClassName(), shortName: $operation?->getShortName() ?? (new \ReflectionClass($type->getClassName()))->getShortName(), description: $operation?->getDescription());
Copy link
Member

Choose a reason for hiding this comment

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

name is not necessary, isn't it?

Copy link
Member Author

Choose a reason for hiding this comment

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

we do need a name


return $this->typeBuilder->getEnumType($enumOperation);
}
Expand Down Expand Up @@ -170,16 +167,14 @@ private function getResourceType(Type $type, bool $input, Operation $rootOperati

// We're retrieving the type of a property which is a relation to the root resource.
if ($resourceClass !== $rootResource && $rootOperation instanceof Query) {
$operationName = $isCollection ? 'collection_query' : 'item_query';
}

try {
$operation = $resourceMetadataCollection->getOperation($operationName);
} catch (OperationNotFoundException) {
$operation = $resourceMetadataCollection->getOperation($isCollection ? 'collection_query' : 'item_query');
}
if (!$operation instanceof Operation) {
throw new OperationNotFoundException();
$operation = $resourceMetadataCollection->getGraphQlOperation(null, $isCollection);
} else {
try {
$operation = $resourceMetadataCollection->getGraphQlOperation($operationName);
} catch (OperationNotFoundException) {
// try to fetch the default operation in case we didn't found the named one
$operation = $resourceMetadataCollection->getGraphQlOperation(null, $isCollection);
}
}

return $this->typeBuilder->getResourceObjectType($resourceClass, $resourceMetadataCollection, $operation, $input, false, $depth);
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/GraphQl/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ class: $class,
fetchPartial: $fetchPartial,
forceEager: $forceEager,
priority: $priority,
name: $name ?: 'item_query',
name: $name,
Copy link
Member

Choose a reason for hiding this comment

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

Why?

Copy link
Member Author

Choose a reason for hiding this comment

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

because we want to remove logic from our operations

Copy link
Member

Choose a reason for hiding this comment

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

OK, why not.

provider: $provider,
processor: $processor,
stateOptions: $stateOptions,
Expand Down
5 changes: 3 additions & 2 deletions src/Metadata/GraphQl/QueryCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function __construct(
?string $name = null,
$provider = null,
$processor = null,
protected ?OptionsInterface $stateOptions = null,
?OptionsInterface $stateOptions = null,
array $extraProperties = [],

?bool $nested = null,
Expand Down Expand Up @@ -116,10 +116,11 @@ class: $class,
fetchPartial: $fetchPartial,
forceEager: $forceEager,
priority: $priority,
name: $name ?: 'collection_query',
name: $name,
provider: $provider,
processor: $processor,
extraProperties: $extraProperties,
stateOptions: $stateOptions,
nested: $nested,
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Metadata/GraphQl/Subscription.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ class: $class,
fetchPartial: $fetchPartial,
forceEager: $forceEager,
priority: $priority,
name: $name ?: 'update_subscription',
name: $name,
provider: $provider,
processor: $processor,
stateOptions: $stateOptions,
Expand Down
22 changes: 16 additions & 6 deletions src/Metadata/Resource/Factory/OperationDefaultsTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@ private function getDefaultHttpOperations($resource): iterable
private function addDefaultGraphQlOperations(ApiResource $resource): ApiResource
{
$graphQlOperations = [];
foreach ([new QueryCollection(), new Query(), (new Mutation())->withName('update'), (new DeleteMutation())->withName('delete'), (new Mutation())->withName('create')] as $operation) {
foreach ([new QueryCollection(name: 'collection_query'), new Query(name: 'item_query'), new Mutation(name: 'update'), new DeleteMutation(name: 'delete'), new Mutation(name: 'create')] as $operation) {
[$key, $operation] = $this->getOperationWithDefaults($resource, $operation);
$graphQlOperations[$key] = $operation;
}

if ($resource->getMercure()) {
[$key, $operation] = $this->getOperationWithDefaults($resource, (new Subscription())->withDescription("Subscribes to the update event of a {$operation->getShortName()}."));
[$key, $operation] = $this->getOperationWithDefaults($resource, new Subscription(name: 'update', description: "Subscribes to the update event of a {$operation->getShortName()}."));
$graphQlOperations[$key] = $operation;
}

Expand Down Expand Up @@ -127,11 +127,11 @@ private function completeGraphQlOperations(ApiResource $resource): ApiResource
}

if (!$hasQueryOperation) {
$queryOperation = (new Query())->withNested(true);
$queryOperation = new Query(name: 'item_query', nested: true);
$graphQlOperations[$queryOperation->getName()] = $queryOperation;
}
if (!$hasQueryCollectionOperation) {
$queryCollectionOperation = (new QueryCollection())->withNested(true);
$queryCollectionOperation = new QueryCollection(name: 'collection_query', nested: true);
$graphQlOperations[$queryCollectionOperation->getName()] = $queryCollectionOperation;
}

Expand Down Expand Up @@ -168,7 +168,7 @@ private function getOperationWithDefaults(ApiResource $resource, Operation $oper

if ($operation instanceof GraphQlOperation) {
if (!$operation->getName()) {
throw new RuntimeException('No GraphQL operation name.');
$operation = $operation->withName($this->getDefaultGraphQlOperationName($operation));
}

if ($operation instanceof Mutation) {
Expand All @@ -187,7 +187,6 @@ private function getOperationWithDefaults(ApiResource $resource, Operation $oper
$operation = $operation->withName($operation->getRouteName());
}

$path = ($operation->getRoutePrefix() ?? '').($operation->getUriTemplate() ?? '');
$operationName = $operation->getName() ?? $this->getDefaultOperationName($operation, $resource->getClass());

return [
Expand All @@ -211,4 +210,15 @@ private function getDefaultOperationName(HttpOperation $operation, string $resou
strtolower($operation->getMethod()),
$operation instanceof CollectionOperationInterface ? '_collection' : '');
}

private function getDefaultGraphQlOperationName(GraphQlOperation $operation): string
{
return match ($class = \get_class($operation)) {
Query::class => 'item_query',
QueryCollection::class => 'collection_query',
Mutation::class => 'update',
Subscription::class => 'update',
default => '_api_graphql_'.$this->getDefaultShortname($class),
};
}
}
33 changes: 33 additions & 0 deletions src/Metadata/Resource/ResourceMetadataCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use ApiPlatform\Exception\OperationNotFoundException;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\GraphQl\Operation as GraphQlOperation;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Operation;

Expand Down Expand Up @@ -96,6 +97,38 @@ public function getOperation(?string $operationName = null, bool $forceCollectio
$this->handleNotFound($operationName, $metadata);
}

public function getGraphQlOperation(?string $operationName = null, bool $forceCollection = false): GraphQlOperation
{
$operationName ??= '';
$cachePrefix = ($forceCollection ? self::FORCE_COLLECTION : '');
$gqlCacheKey = self::GRAPHQL_PREFIX.$cachePrefix.$operationName;
if (isset($this->operationCache[$gqlCacheKey])) {
return $this->operationCache[$gqlCacheKey];
}

$it = $this->getIterator();

while ($it->valid()) {
/** @var ApiResource $metadata */
$metadata = $it->current();

foreach ($metadata->getGraphQlOperations() ?? [] as $name => $operation) {
$isCollection = $operation instanceof CollectionOperationInterface;
if ('' === $operationName && ($forceCollection ? $isCollection : !$isCollection)) {
return $this->operationCache[$gqlCacheKey] = $operation;
}

if ($name === $operationName) {
return $this->operationCache[$gqlCacheKey] = $operation;
}
}

$it->next();
}

$this->handleNotFound($operationName, $metadata);
}

/**
* @throws OperationNotFoundException
*/
Expand Down