Skip to content

fix(state): operation argument in provide/process #4712

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

Merged
merged 6 commits into from
Apr 19, 2022
Merged
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
10 changes: 9 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
# Changelog

## 2.7.0
## 2.7.0-alpha.2

* Review interfaces (ProcessorInterface, ProviderInterface, TypeConverterInterface, ResolverFactoryInterface etc.) to use `ApiPlatform\Metadata\Operation` instead of `operationName` (#4712)
* Introduce `CollectionOperationInterface` instead of the `collection` flag (#4712)
* Introduce `DeleteOperationInterface` instead of the `delete` flag (#4712)
* The `compositeIdentifier` flag only lives under the `uriVariables` property (#4712)
* The `provider` or `processor` property is specified within the `Operation` and we removed the chain pattern (#4712)

## 2.7.0-alpha.1

* Swagger UI: Add `usePkceWithAuthorizationCodeGrant` to Swagger UI initOAuth (#4649)
* **BC**: `mapping.paths` in configuration should override bundles configuration (#4465)
Expand Down
2 changes: 1 addition & 1 deletion src/Api/IdentifiersExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function getIdentifiersFromItem($item, string $operationName = null, arra
{
$identifiers = [];
$resourceClass = $this->getResourceClass($item, true);
$operation = $context['operation'] ?? $this->resourceMetadataFactory->create($resourceClass)->getOperation($operationName);
$operation = $context['operation'] ?? $this->resourceMetadataFactory->create($resourceClass)->getOperation($operationName, false, true);

$links = $operation instanceof GraphQlOperation ? $operation->getLinks() : $operation->getUriVariables();
foreach ($links ?? [] as $link) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace ApiPlatform\Core\Bridge\Symfony\Bundle\Command;

use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Operation\Factory\SubresourceOperationFactoryInterface;
use ApiPlatform\Core\Upgrade\ColorConsoleDiffFormatter;
Expand Down Expand Up @@ -42,15 +43,17 @@ final class UpgradeApiResourceCommand extends Command
private $subresourceOperationFactory;
private $subresourceTransformer;
private $reader;
private $identifiersExtractor;
private $localCache = [];

public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, SubresourceOperationFactoryInterface $subresourceOperationFactory, SubresourceTransformer $subresourceTransformer, AnnotationReader $reader)
public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, SubresourceOperationFactoryInterface $subresourceOperationFactory, SubresourceTransformer $subresourceTransformer, AnnotationReader $reader, IdentifiersExtractorInterface $identifiersExtractor)
{
$this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->subresourceOperationFactory = $subresourceOperationFactory;
$this->subresourceTransformer = $subresourceTransformer;
$this->reader = $reader;
$this->identifiersExtractor = $identifiersExtractor;

parent::__construct();
}
Expand Down Expand Up @@ -204,7 +207,7 @@ private function transformApiResource(InputInterface $input, OutputInterface $ou
continue;
}

$traverser->addVisitor(new UpgradeApiResourceVisitor($attribute, $isAnnotation));
$traverser->addVisitor(new UpgradeApiResourceVisitor($attribute, $isAnnotation, $this->identifiersExtractor, $resourceClass));

$oldCode = file_get_contents($fileName);
$oldStmts = $parser->parse($oldCode);
Expand Down
3 changes: 2 additions & 1 deletion src/Core/EventListener/ReadListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,9 @@ public function onKernelRequest(RequestEvent $event): void
if (
!($attributes = RequestAttributesExtractor::extractAttributes($request))
|| !$attributes['receive']
|| $request->isMethod('POST') && isset($attributes['collection_operation_name'])
|| ($request->isMethod('POST') && isset($attributes['collection_operation_name']))
|| ($operation && !($operation->getExtraProperties()['is_legacy_resource_metadata'] ?? false) && !($operation->getExtraProperties()['is_legacy_subresource'] ?? false))
|| ($operation && false === $operation->canRead())
|| $this->isOperationAttributeDisabled($attributes, self::OPERATION_ATTRIBUTE_KEY)
) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
namespace ApiPlatform\Core\Metadata\Resource;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\HttpOperation;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;

/**
Expand All @@ -37,12 +39,14 @@ private function transformResourceToResourceMetadata(ApiResource $resource): Res
}

$arrayOperation['openapi_context']['operationId'] = $name;
$arrayOperation['composite_identifier'] = $this->hasCompositeIdentifier($operation);

if ($operation->getExtraProperties()['is_alternate_resource_metadata'] ?? false) {
$arrayOperation['composite_identifier'] = $operation->getCompositeIdentifier() ?? false;
if (HttpOperation::METHOD_POST === $operation->getMethod() && !$operation->getUriVariables()) {
$collectionOperations[$name] = $arrayOperation;
continue;
}

if ($operation->isCollection()) {
if ($operation instanceof CollectionOperationInterface) {
$collectionOperations[$name] = $arrayOperation;
continue;
}
Expand Down Expand Up @@ -108,4 +112,15 @@ private function transformUriVariablesToIdentifiers(array $arrayOperation): arra

return $arrayOperation;
}

private function hasCompositeIdentifier(HttpOperation $operation): bool
{
foreach ($operation->getUriVariables() ?? [] as $parameterName => $uriVariable) {
if ($uriVariable->getCompositeIdentifier()) {
return true;
}
}

return false;
}
}
6 changes: 3 additions & 3 deletions src/Core/Swagger/Serializer/DocumentationNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ private function updatePostOperation(bool $v3, \ArrayObject $pathOperation, arra
$identifiers = (array) $resourceMetadata
->getTypedOperationAttribute($operationType, $operationName, 'identifiers', [], false);

$pathOperation = $this->addItemOperationParameters($v3, $pathOperation, $operationType, $operationName, $resourceMetadata, $resourceClass);
$pathOperation = $this->addItemOperationParameters($v3, $pathOperation, $operationType, $operationName, $resourceMetadata, $resourceClass, OperationType::ITEM === $operationType ? false : true);

$successResponse = ['description' => sprintf('%s resource created', $resourceShortName)];
[$successResponse, $defined] = $this->addSchemas($v3, $successResponse, $definitions, $resourceClass, $operationType, $operationName, $responseMimeTypes);
Expand Down Expand Up @@ -677,14 +677,14 @@ private function updateDeleteOperation(bool $v3, \ArrayObject $pathOperation, st
return $this->addItemOperationParameters($v3, $pathOperation, $operationType, $operationName, $resourceMetadata, $resourceClass);
}

private function addItemOperationParameters(bool $v3, \ArrayObject $pathOperation, string $operationType, string $operationName, ResourceMetadata $resourceMetadata, string $resourceClass): \ArrayObject
private function addItemOperationParameters(bool $v3, \ArrayObject $pathOperation, string $operationType, string $operationName, ResourceMetadata $resourceMetadata, string $resourceClass, bool $isPost = false): \ArrayObject
{
$identifiers = (array) $resourceMetadata
->getTypedOperationAttribute($operationType, $operationName, 'identifiers', [], false);

// Auto-generated routes in API Platform < 2.7 are considered as collection, hotfix this as the OpenApi Factory supports new operations anyways.
// this also fixes a bug where we could not create POST item operations in API P 2.6
if (OperationType::ITEM === $operationType && 'post' === substr($operationName, -4)) {
if (OperationType::ITEM === $operationType && $isPost) {
$operationType = OperationType::COLLECTION;
}

Expand Down
46 changes: 45 additions & 1 deletion src/Core/Upgrade/UpgradeApiResourceVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
use ApiPlatform\Api\UrlGeneratorInterface;
use ApiPlatform\Core\Annotation\ApiResource as LegacyApiResource;
use ApiPlatform\Core\Annotation\ApiSubresource;
use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\GraphQl\Mutation;
use ApiPlatform\Metadata\GraphQl\Query;
use ApiPlatform\Metadata\GraphQl\QueryCollection;
use ApiPlatform\Metadata\Link;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
Expand All @@ -36,12 +38,16 @@ final class UpgradeApiResourceVisitor extends NodeVisitorAbstract
use RemoveAnnotationTrait;

private LegacyApiResource $resourceAnnotation;
private IdentifiersExtractorInterface $identifiersExtractor;
private bool $isAnnotation = false;
private string $resourceClass;

public function __construct(LegacyApiResource $resourceAnnotation, bool $isAnnotation = false)
public function __construct(LegacyApiResource $resourceAnnotation, bool $isAnnotation, IdentifiersExtractorInterface $identifiersExtractor, string $resourceClass)
{
$this->resourceAnnotation = $resourceAnnotation;
$this->isAnnotation = $isAnnotation;
$this->identifiersExtractor = $identifiersExtractor;
$this->resourceClass = $resourceClass;
}

/**
Expand Down Expand Up @@ -80,6 +86,10 @@ public function enterNode(Node $node)
$this->getGraphQlOperationsNamespaces($this->resourceAnnotation->graphql ?? [])
));

if (true === !($this->resourceAnnotation->attributes['composite_identifier'] ?? true)) {
$namespaces[] = Link::class;
}

foreach ($node->stmts as $k => $stmt) {
if (!$stmt instanceof Node\Stmt\Use_) {
break;
Expand Down Expand Up @@ -202,6 +212,40 @@ public function enterNode(Node $node)
continue;
}

if ('compositeIdentifier' === $key) {
if (false !== $value) {
continue;
}

$identifiers = $this->identifiersExtractor->getIdentifiersFromResourceClass($this->resourceClass);
$identifierNodeItems = [];
foreach ($identifiers as $identifier) {
$identifierNodes = [
'compositeIdentifier' => new Node\Expr\ConstFetch(new Node\Name('false')),
'fromClass' => new Node\Expr\ClassConstFetch(
new Node\Name(
'self'
),
'class'
),
'identifiers' => new Node\Expr\Array_(
[
new Node\Expr\ArrayItem(new Node\Scalar\String_($identifier)),
],
['kind' => Node\Expr\Array_::KIND_SHORT]
),
];

$identifierNodeItems[] = new Node\Expr\ArrayItem(
new Node\Expr\New_(new Node\Name('Link'), $this->arrayToArguments($identifierNodes)),
new Node\Scalar\String_($identifier)
);
}

$arguments['uriVariables'] = new Node\Expr\Array_($identifierNodeItems, ['kind' => Node\Expr\Array_::KIND_SHORT]);
continue;
}

$arguments[$key] = $this->valueToNode($value);
}

Expand Down
29 changes: 25 additions & 4 deletions src/Doctrine/Common/State/LinksHandlerTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,22 @@

namespace ApiPlatform\Doctrine\Common\State;

use ApiPlatform\Exception\OperationNotFoundException;
use ApiPlatform\Exception\RuntimeException;
use ApiPlatform\Metadata\GraphQl\Operation as GraphQlOperation;
use ApiPlatform\Metadata\GraphQl\Query;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Link;
use ApiPlatform\Metadata\Operation;

trait LinksHandlerTrait
{
/**
* @param Operation|GraphQlOperation $operation
* @param HttpOperation|GraphQlOperation $operation
*
* @return Link[]
*/
private function getLinks(string $resourceClass, $operation, array $context): array
private function getLinks(string $resourceClass, Operation $operation, array $context): array
{
$links = ($operation instanceof GraphQlOperation ? $operation->getLinks() : $operation->getUriVariables()) ?? [];

Expand All @@ -41,8 +44,26 @@ private function getLinks(string $resourceClass, $operation, array $context): ar
}
}

$operation = $this->resourceMetadataCollectionFactory->create($linkClass)->getOperation($operation->getName());
foreach ($operation instanceof GraphQlOperation ? $operation->getLinks() : $operation->getUriVariables() as $link) {
// Using graphql, it's possible that we won't find a graphql operation of the same type (eg it is disabled).
try {
$resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($linkClass);
$linkedOperation = $resourceMetadataCollection->getOperation($operation->getName());
} catch (OperationNotFoundException $e) {
if (!$operation instanceof GraphQlOperation) {
throw $e;
}

// Instead we'll look for the first Query available
foreach ($resourceMetadataCollection as $resourceMetadata) {
foreach ($resourceMetadata->getGraphQlOperations() as $operation) {
if ($operation instanceof Query) {
$linkedOperation = $operation;
}
}
}
}

foreach ($linkedOperation instanceof GraphQlOperation ? $linkedOperation->getLinks() : $linkedOperation->getUriVariables() as $link) {
if ($resourceClass === $link->getToClass()) {
$newLinks[] = $link;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@

namespace ApiPlatform\Doctrine\Common\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use ApiPlatform\Util\ClassInfoTrait;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\ObjectManager as DoctrineObjectManager;

final class Processor implements ProcessorInterface
final class PersistProcessor implements ProcessorInterface
{
use ClassInfoTrait;

Expand All @@ -31,12 +32,7 @@ public function __construct(ManagerRegistry $managerRegistry)
$this->managerRegistry = $managerRegistry;
}

public function supports($data, array $uriVariables = [], ?string $operationName = null, array $context = []): bool
{
return null !== $this->getManager($data);
}

private function persist($data, array $context = [])
public function process($data, Operation $operation, array $uriVariables = [], array $context = [])
{
if (!$manager = $this->getManager($data)) {
return $data;
Expand All @@ -52,25 +48,6 @@ private function persist($data, array $context = [])
return $data;
}

private function remove($data, array $context = [])
{
if (!$manager = $this->getManager($data)) {
return;
}

$manager->remove($data);
$manager->flush();
}

public function process($data, array $uriVariables = [], ?string $operationName = null, array $context = [])
{
if (\array_key_exists('operation', $context) && $context['operation']->isDelete()) {
return $this->remove($data);
}

return $this->persist($data);
}

/**
* Gets the Doctrine object manager associated with given data.
*
Expand Down
52 changes: 52 additions & 0 deletions src/Doctrine/Common/State/RemoveProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Common\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use ApiPlatform\Util\ClassInfoTrait;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\ObjectManager as DoctrineObjectManager;

final class RemoveProcessor implements ProcessorInterface
{
use ClassInfoTrait;

private $managerRegistry;

public function __construct(ManagerRegistry $managerRegistry)
{
$this->managerRegistry = $managerRegistry;
}

public function process($data, Operation $operation, array $uriVariables = [], array $context = [])
{
if (!$manager = $this->getManager($data)) {
return;
}

$manager->remove($data);
$manager->flush();
}

/**
* Gets the Doctrine object manager associated with given data.
*
* @param mixed $data
*/
private function getManager($data): ?DoctrineObjectManager
{
return \is_object($data) ? $this->managerRegistry->getManagerForClass($this->getObjectClass($data)) : null;
}
}
Loading