Skip to content
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
25 changes: 25 additions & 0 deletions src/Metadata/ApiOperation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* 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\Metadata;

/**
* Runs an API Platform operation on a controller method bound to the application's own route.
*/
#[\Attribute(\Attribute::TARGET_METHOD)]
final class ApiOperation
{
public function __construct(public readonly HttpOperation $operation)
{
}
}
70 changes: 70 additions & 0 deletions src/State/Util/OperationStageDefaults.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* 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\State\Util;

use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\State\SerializerContextBuilderInterface;
use Symfony\Component\HttpFoundation\Request;

/**
* Resolves the stage flags left unset on an operation to their request-dependent defaults.
*
* @internal
*/
final class OperationStageDefaults
{
private function __construct()
{
}

public static function forProvider(HttpOperation $operation, Request $request): HttpOperation
{
if (null === $operation->canValidate()) {
$operation = $operation->withValidate(!$request->isMethodSafe() && !$request->isMethod('DELETE'));
}

if (null === $operation->canRead()) {
$operation = $operation->withRead($operation->getUriVariables() || $request->isMethodSafe());
}

if (null === $operation->canDeserialize()) {
$operation = $operation->withDeserialize(\in_array($operation->getMethod(), ['POST', 'PUT', 'PATCH'], true));
}

$denormalizationContext = $operation->getDenormalizationContext() ?? [];
if ($operation->canDeserialize() && !isset($denormalizationContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE])) {
$method = $operation->getMethod();
$assignObjectToPopulate = 'POST' === $method
|| 'PATCH' === $method
|| ('PUT' === $method && !($operation->getExtraProperties()['standard_put'] ?? true));

$operation = $operation->withDenormalizationContext($denormalizationContext + [SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE => $assignObjectToPopulate]);
}

return $operation;
}

public static function forProcessor(HttpOperation $operation, Request $request): HttpOperation
{
if (null === $operation->canWrite()) {
$operation = $operation->withWrite(!$request->isMethodSafe());
}

if (null === $operation->canSerialize()) {
$operation = $operation->withSerialize(true);
}

return $operation;
}
}
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/ApiPlatformBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use ApiPlatform\Symfony\Bundle\DependencyInjection\Compiler\AttributeFilterPass;
use ApiPlatform\Symfony\Bundle\DependencyInjection\Compiler\AttributeResourcePass;
use ApiPlatform\Symfony\Bundle\DependencyInjection\Compiler\AuthenticatorManagerPass;
use ApiPlatform\Symfony\Bundle\DependencyInjection\Compiler\ControllerApiOperationPass;
use ApiPlatform\Symfony\Bundle\DependencyInjection\Compiler\ElasticsearchClientPass;
use ApiPlatform\Symfony\Bundle\DependencyInjection\Compiler\ErrorResourceAttributeLoaderPass;
use ApiPlatform\Symfony\Bundle\DependencyInjection\Compiler\FilterPass;
Expand Down Expand Up @@ -51,6 +52,7 @@ public function build(ContainerBuilder $container): void
// Run the compiler pass before the {@see ResolveInstanceofConditionalsPass} to allow autoconfiguration of generated filter definitions.
$container->addCompilerPass(new AttributeFilterPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 101);
$container->addCompilerPass(new AttributeResourcePass());
$container->addCompilerPass(new ControllerApiOperationPass());
$container->addCompilerPass(new FilterPass());
$container->addCompilerPass(new ElasticsearchClientPass());
$container->addCompilerPass(new GraphQlTypePass());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,9 @@ private function registerCommonConfiguration(ContainerBuilder $container, array
if (!$container->hasParameter('serializer.default_context')) {
$container->setParameter('serializer.default_context', $container->getParameter('api_platform.serializer.default_context'));
}
$container->setParameter('api_platform.controller_operations', []);
$container->setParameter('api_platform.controller_operation_resources', []);
$loader->load('symfony/controller_operation.php');
if ($config['use_symfony_listeners']) {
$loader->load('symfony/events.php');
} else {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* 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\Symfony\Bundle\DependencyInjection\Compiler;

use ApiPlatform\Metadata\ApiOperation;
use ApiPlatform\Metadata\HttpOperation;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;

/**
* Discovers the controller methods carrying {@see ApiOperation} and registers their resource classes.
*
* @internal
*/
final class ControllerApiOperationPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
$controllerOperations = [];
$resources = [];

foreach (array_keys($container->findTaggedServiceIds('controller.service_arguments')) as $id) {
$definition = $container->getDefinition($id);
if ($definition->isAbstract()) {
continue;
}

$class = $container->getParameterBag()->resolveValue($definition->getClass() ?? $id);
if (!\is_string($class) || !($reflectionClass = $container->getReflectionClass($class, false))) {
continue;
}

foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
foreach ($method->getAttributes(ApiOperation::class) as $attribute) {
$controller = $reflectionClass->getName().'::'.$method->getName();
$resourceClass = $this->getResourceClass($attribute->newInstance()->operation);
Comment thread
soyuka marked this conversation as resolved.

if (null === $resourceClass) {
throw new InvalidArgumentException(\sprintf('The "#[%s]" on "%s" must define a "class" or an "output": an "input" alone does not define a resource.', ApiOperation::class, $controller));
}

$controllerOperations[$resourceClass][] = $controller;
$resources[$resourceClass] = true;
}
}
}

$container->setParameter('api_platform.controller_operations', $controllerOperations);
$container->setParameter('api_platform.controller_operation_resources', $resources);
}

private function getResourceClass(HttpOperation $operation): ?string
{
foreach ([$operation->getClass(), $operation->getOutput()] as $candidate) {
if (\is_array($candidate)) {
$candidate = $candidate['class'] ?? null;
}

if (\is_string($candidate) && '' !== $candidate) {
return $candidate;
}
}

return null;
}
}
10 changes: 10 additions & 0 deletions src/Symfony/Bundle/Resources/config/metadata/resource.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\Resource\Factory\UriTemplateResourceMetadataCollectionFactory;
use ApiPlatform\Symfony\Metadata\Resource\Factory\ContainerParameterResourceMetadataCollectionFactory;
use ApiPlatform\Symfony\Metadata\Resource\Factory\ControllerApiOperationResourceMetadataCollectionFactory;

return function (ContainerConfigurator $container) {
$services = $container->services();
Expand Down Expand Up @@ -151,6 +152,15 @@
->decorate('api_platform.metadata.resource.metadata_collection_factory', null, 200)
->args([service('api_platform.metadata.resource.metadata_collection_factory.alternate_uri.inner')]);

$services->set('api_platform.metadata.resource.metadata_collection_factory.controller_api_operation', ControllerApiOperationResourceMetadataCollectionFactory::class)
->decorate('api_platform.metadata.resource.metadata_collection_factory', null, 1100)
->args([
'%api_platform.controller_operations%',
service('api_platform.metadata.resource.metadata_collection_factory.controller_api_operation.inner'),
service('logger')->nullOnInvalid(),
'%api_platform.defaults%',
]);

$services->set('api_platform.metadata.resource.metadata_collection_factory.parameter', ParameterResourceMetadataCollectionFactory::class)
->decorate('api_platform.metadata.resource.metadata_collection_factory', null, 1000)
->args([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use ApiPlatform\Metadata\Resource\Factory\ExtractorResourceNameCollectionFactory;
use ApiPlatform\Metadata\Resource\Factory\PhpFileResourceNameCollectionFactory;
use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
use ApiPlatform\Symfony\Metadata\Resource\Factory\ControllerApiOperationResourceNameCollectionFactory;

return function (ContainerConfigurator $container) {
$services = $container->services();
Expand Down Expand Up @@ -69,4 +70,11 @@
'%api_platform.class_name_resources%',
service('api_platform.metadata.resource.name_collection_factory.class_name.inner'),
]);

$services->set('api_platform.metadata.resource.name_collection_factory.controller_api_operation', ControllerApiOperationResourceNameCollectionFactory::class)
->decorate('api_platform.metadata.resource.name_collection_factory', null, 0)
->args([
service('api_platform.metadata.resource.name_collection_factory.controller_api_operation.inner'),
'%api_platform.controller_operation_resources%',
]);
};
11 changes: 11 additions & 0 deletions src/Symfony/Bundle/Resources/config/symfony/controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use ApiPlatform\Symfony\Action\DocumentationAction;
use ApiPlatform\Symfony\Action\EntrypointAction;
use ApiPlatform\Symfony\Controller\MainController;
use ApiPlatform\Symfony\EventListener\ControllerApiOperationPipelineListener;

return static function (ContainerConfigurator $container) {
$services = $container->services();
Expand All @@ -30,6 +31,16 @@
service('logger')->ignoreOnInvalid(),
]);

$services->set('api_platform.listener.controller_api_operation.pipeline', ControllerApiOperationPipelineListener::class)
->args([
service('api_platform.state_provider.main'),
service('api_platform.state_processor.main'),
service('api_platform.metadata.resource.metadata_collection_factory'),
service('api_platform.uri_variables.converter')->ignoreOnInvalid(),
])
->tag('kernel.event_listener', ['event' => 'kernel.request', 'method' => 'onKernelRequest', 'priority' => 27])
->tag('kernel.event_listener', ['event' => 'kernel.view', 'method' => 'onKernelView']);

$services->set('api_platform.action.entrypoint', EntrypointAction::class)
->public()
->args([
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

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

declare(strict_types=1);

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use ApiPlatform\Symfony\EventListener\ControllerApiOperationListener;

return static function (ContainerConfigurator $container) {
$services = $container->services();

$services->set('api_platform.listener.request.controller_api_operation', ControllerApiOperationListener::class)
->args([
service('api_platform.metadata.resource.metadata_collection_factory'),
'%api_platform.controller_operations%',
])
->tag('kernel.event_listener', ['event' => 'kernel.request', 'method' => 'onKernelRequest', 'priority' => 30]);
};
32 changes: 3 additions & 29 deletions src/Symfony/Controller/MainController.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
use ApiPlatform\Metadata\UriVariablesConverterInterface;
use ApiPlatform\State\ProcessorInterface;
use ApiPlatform\State\ProviderInterface;
use ApiPlatform\State\SerializerContextBuilderInterface;
use ApiPlatform\State\UriVariablesResolverTrait;
use ApiPlatform\State\Util\OperationRequestInitiatorTrait;
use ApiPlatform\State\Util\OperationStageDefaults;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
Expand Down Expand Up @@ -69,27 +69,7 @@ public function __invoke(Request $request): Response
'resource_class' => $operation->getClass(),
];

if (null === $operation->canValidate()) {
$operation = $operation->withValidate(!$request->isMethodSafe() && !$request->isMethod('DELETE'));
}

if (null === $operation->canRead()) {
$operation = $operation->withRead($operation->getUriVariables() || $request->isMethodSafe());
}

if (null === $operation->canDeserialize()) {
$operation = $operation->withDeserialize(\in_array($operation->getMethod(), ['POST', 'PUT', 'PATCH'], true));
}

$denormalizationContext = $operation->getDenormalizationContext() ?? [];
if ($operation->canDeserialize() && !isset($denormalizationContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE])) {
$method = $operation->getMethod();
$assignObjectToPopulate = 'POST' === $method
|| 'PATCH' === $method
|| ('PUT' === $method && !($operation->getExtraProperties()['standard_put'] ?? true));

$operation = $operation->withDenormalizationContext($denormalizationContext + [SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE => $assignObjectToPopulate]);
}
$operation = OperationStageDefaults::forProvider($operation, $request);

$body = $this->provider->provide($operation, $uriVariables, $context);

Expand All @@ -114,13 +94,7 @@ public function __invoke(Request $request): Response
$context['read_data'] = $request->attributes->get('read_data');
$context['mapped_data'] = $request->attributes->get('mapped_data');

if (null === $operation->canWrite()) {
$operation = $operation->withWrite(!$request->isMethodSafe());
}

if (null === $operation->canSerialize()) {
$operation = $operation->withSerialize(true);
}
$operation = OperationStageDefaults::forProcessor($operation, $request);

return $this->processor->process($body, $operation, $uriVariables, $context);
}
Expand Down
Loading
Loading