Skip to content

feat(symfony): Autoconfigure classes using #[ApiResource] attribute #6943

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 3 commits into from
Apr 29, 2025
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
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/ApiPlatformBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace ApiPlatform\Symfony\Bundle;

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\DataProviderPass;
use ApiPlatform\Symfony\Bundle\DependencyInjection\Compiler\ElasticsearchClientPass;
Expand Down Expand Up @@ -47,6 +48,7 @@ public function build(ContainerBuilder $container): void
$container->addCompilerPass(new DataProviderPass());
// 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 FilterPass());
$container->addCompilerPass(new ElasticsearchClientPass());
$container->addCompilerPass(new GraphQlTypePass());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
use Ramsey\Uuid\Uuid;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Resource\DirectoryResource;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
Expand Down Expand Up @@ -169,6 +170,11 @@ public function load(array $configs, ContainerBuilder $container): void
->addTag('api_platform.uri_variables.transformer');
$container->registerForAutoconfiguration(ParameterProviderInterface::class)
->addTag('api_platform.parameter_provider');
$container->registerAttributeForAutoconfiguration(ApiResource::class, static function (ChildDefinition $definition): void {
$definition->setAbstract(true)
->addTag('api_platform.resource')
->addTag('container.excluded', ['source' => 'by #[ApiResource] attribute']);
});

if (!$container->has('api_platform.state.item_provider')) {
$container->setAlias('api_platform.state.item_provider', 'api_platform.state_provider.object');
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?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\Symfony\Bundle\DependencyInjection\Compiler;

use ApiPlatform\Metadata\ApiResource;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
* Registers resource classes from {@see ApiResource} attribute.
*
* @internal
*
* @author Jérôme Tamarelle <[email protected]>
*/
final class AttributeResourcePass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container): void
{
$classes = $container->getParameter('api_platform.class_name_resources');

// findTaggedServiceIds cannot be used, as the services are excluded
foreach ($container->getDefinitions() as $definition) {
if ($definition->hasTag('api_platform.resource')) {
$classes[] = $definition->getClass();
}
}

$container->setParameter('api_platform.class_name_resources', array_unique($classes));
}
}
1 change: 1 addition & 0 deletions src/Symfony/Bundle/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ public function getConfigTreeBuilder(): TreeBuilder
->end()
->arrayNode('resource_class_directories')
->prototype('scalar')->end()
->setDeprecated('api-platform/symfony', '4.1', 'The "resource_class_directories" configuration is deprecated, classes using #[ApiResource] attribute are autoconfigured by the dependency injection container.')

Choose a reason for hiding this comment

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

@soyuka @GromNaN

I think, this feature break some functionality.

If this option was deprecated, and planned to be removed in future, this will break any additional features like filters (sorting/filtering) on the same level as #[ApiResource] in resource - this means they are not loaded with all the operations they are should be.

Simple reproducer:
api-platform/core:4.2.x-dev

<?php

use ApiPlatform\Doctrine\Common\Filter\SearchFilterInterface;
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
use ApiPlatform\Metadata\ApiFilter;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\OpenApi\Model\Operation;
use App\Expense\Application\Controller\GetCollectionCostController;
use App\Shared\Domain\Entity\AbstractEntity;

#[ApiResource(
    operations: [
        new GetCollection(
            uriTemplate: 'expense/cost',
            inputFormats: ['jsonld' => ['application/ld+json']],
            outputFormats: ['jsonld' => ['application/ld+json']],
            controller: GetCollectionCostController::class,
            openapi: new Operation(tags: ['Expense'], summary: 'Returns the collection of Cost resources.', description: 'Returns the collection of Cost resources.'),
            normalizationContext: ['groups' => ['api:read']],
            denormalizationContext: ['groups' => ['api:write']],
            output: Cost::class,
            priority: 2,
        ),
    ],
)]
#[ApiFilter(filterClass: SearchFilter::class, properties: ['comment' => SearchFilterInterface::STRATEGY_IPARTIAL])]
class Cost extends AbstractEntity
{
}

With setting resource_class_directories:
obraz

and deprecated message:
Since api-platform/symfony 4.1: The "resource_class_directories" configuration is deprecated, classes using #[ApiResource] attribute are autoconfigured by the dependency injection container.

Without setting resource_class_directories:
obraz

I don't know how to fix it. Unless there is some other way to fix it?

Choose a reason for hiding this comment

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

Settings the #[ApiFilter] attribute directly on property (like in https://api-platform.com/docs/core/filters/#apifilter-attribute) also not works.

Copy link
Member

Choose a reason for hiding this comment

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

Interesting thanks I'll investigate

Choose a reason for hiding this comment

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

Do you have any information about that @soyuka ?

Copy link
Contributor Author

@GromNaN GromNaN Jul 7, 2025

Choose a reason for hiding this comment

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

Should other attributes such as #[ApiFilter] be added to the AutoConfiguration?

Choose a reason for hiding this comment

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

@GromNaN I think, yes.

->end()
->arrayNode('serializer')
->addDefaultsIfNotSet()
Expand Down
2 changes: 2 additions & 0 deletions tests/Symfony/Bundle/ApiPlatformBundleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use ApiPlatform\Symfony\Bundle\ApiPlatformBundle;
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\DataProviderPass;
use ApiPlatform\Symfony\Bundle\DependencyInjection\Compiler\ElasticsearchClientPass;
Expand Down Expand Up @@ -45,6 +46,7 @@ public function testBuild(): void
$containerProphecy = $this->prophesize(ContainerBuilder::class);
$containerProphecy->addCompilerPass(Argument::type(DataProviderPass::class))->willReturn($containerProphecy->reveal())->shouldBeCalled();
$containerProphecy->addCompilerPass(Argument::type(AttributeFilterPass::class), PassConfig::TYPE_BEFORE_OPTIMIZATION, 101)->willReturn($containerProphecy->reveal())->shouldBeCalled();
$containerProphecy->addCompilerPass(Argument::type(AttributeResourcePass::class))->shouldBeCalled()->willReturn($containerProphecy->reveal())->shouldBeCalled();
$containerProphecy->addCompilerPass(Argument::type(FilterPass::class))->willReturn($containerProphecy->reveal())->shouldBeCalled();
$containerProphecy->addCompilerPass(Argument::type(ElasticsearchClientPass::class))->willReturn($containerProphecy->reveal())->shouldBeCalled();
$containerProphecy->addCompilerPass(Argument::type(GraphQlTypePass::class))->willReturn($containerProphecy->reveal())->shouldBeCalled();
Expand Down
Loading