Skip to content

feat(symfony): object mapper with state options #6801

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 2 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
6 changes: 4 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@
"symfony/cache": "^6.4 || ^7.0",
"symfony/config": "^6.4 || ^7.0",
"symfony/console": "^6.4 || ^7.0",
"symfony/object-mapper": "v7.3.0-RC1",
"symfony/css-selector": "^6.4 || ^7.0",
"symfony/dependency-injection": "^6.4 || ^7.0",
"symfony/doctrine-bridge": "^6.4.2 || ^7.1",
Expand All @@ -172,7 +173,7 @@
"symfony/expression-language": "^6.4 || ^7.0",
"symfony/finder": "^6.4 || ^7.0",
"symfony/form": "^6.4 || ^7.0",
"symfony/framework-bundle": "^6.4 || ^7.0",
"symfony/framework-bundle": "v7.3.0-RC1",
"symfony/http-client": "^6.4 || ^7.0",
"symfony/intl": "^6.4 || ^7.0",
"symfony/maker-bundle": "^1.24",
Expand Down Expand Up @@ -212,5 +213,6 @@
"type": "library",
"repositories": [
{"type": "vcs", "url": "https://github.com/soyuka/phpunit"}
]
],
"minimum-stability": "RC"
}
38 changes: 38 additions & 0 deletions src/Laravel/ApiPlatformDeferredProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@
use ApiPlatform\State\Pagination\Pagination;
use ApiPlatform\State\ParameterProviderInterface;
use ApiPlatform\State\ProcessorInterface;
use ApiPlatform\State\Processor\ObjectMapperProcessor;
use ApiPlatform\State\Provider\ObjectMapperProvider;
use ApiPlatform\State\Provider\ParameterProvider;
use ApiPlatform\State\Provider\ReadProvider;
use ApiPlatform\State\Provider\SecurityParameterProvider;
use ApiPlatform\State\ProviderInterface;
use Illuminate\Contracts\Debug\ExceptionHandler as ExceptionHandlerInterface;
Expand All @@ -89,6 +92,12 @@
use Illuminate\Support\ServiceProvider;
use Negotiation\Negotiator;
use Psr\Log\LoggerInterface;
use Symfony\Component\ObjectMapper\ConditionCallableInterface;
use Symfony\Component\ObjectMapper\Metadata\ReflectionObjectMapperMetadataFactory;
use Symfony\Component\ObjectMapper\ObjectMapper;
use Symfony\Component\ObjectMapper\ObjectMapperInterface;
use Symfony\Component\ObjectMapper\TransformCallableInterface;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

Expand Down Expand Up @@ -190,6 +199,34 @@

$this->autoconfigure($classes, ProviderInterface::class, [ItemProvider::class, CollectionProvider::class, ErrorProvider::class]);

$this->app->singleton(ObjectMapperInterface::class, function (Application $app) {
return new ObjectMapper(
new ReflectionObjectMapperMetadataFactory(),
$app->make(PropertyAccessorInterface::class),
new ServiceLocator(iterator_to_array($app->tagged(TransformCallableInterface::class))),
new ServiceLocator(iterator_to_array($app->tagged(ConditionCallableInterface::class))),
);
});

Check warning on line 209 in src/Laravel/ApiPlatformDeferredProvider.php

View check run for this annotation

Codecov / codecov/patch

src/Laravel/ApiPlatformDeferredProvider.php#L202-L209

Added lines #L202 - L209 were not covered by tests

$this->autoconfigure($classes, TransformCallableInterface::class, []);
$this->autoconfigure($classes, ConditionCallableInterface::class, []);

Check warning on line 212 in src/Laravel/ApiPlatformDeferredProvider.php

View check run for this annotation

Codecov / codecov/patch

src/Laravel/ApiPlatformDeferredProvider.php#L211-L212

Added lines #L211 - L212 were not covered by tests

$this->app->extend(ReadProvider::class, function (ReadProvider $service, Application $app) {
return new ObjectMapperProvider(
$app->make(ObjectMapperInterface::class),
$service
);
});

Check warning on line 219 in src/Laravel/ApiPlatformDeferredProvider.php

View check run for this annotation

Codecov / codecov/patch

src/Laravel/ApiPlatformDeferredProvider.php#L214-L219

Added lines #L214 - L219 were not covered by tests

$this->app->extend(CallableProcessor::class, function (CallableProcessor $service, Application $app) {
return new ObjectMapperProcessor(
$app->make(ObjectMapperInterface::class),
$service
);
});

Check warning on line 226 in src/Laravel/ApiPlatformDeferredProvider.php

View check run for this annotation

Codecov / codecov/patch

src/Laravel/ApiPlatformDeferredProvider.php#L221-L226

Added lines #L221 - L226 were not covered by tests

$this->autoconfigure($classes, ProviderInterface::class, [ItemProvider::class, CollectionProvider::class, ErrorProvider::class]);

Check warning on line 228 in src/Laravel/ApiPlatformDeferredProvider.php

View check run for this annotation

Codecov / codecov/patch

src/Laravel/ApiPlatformDeferredProvider.php#L228

Added line #L228 was not covered by tests

$this->app->singleton(ResourceMetadataCollectionFactoryInterface::class, function (Application $app) {
/** @var ConfigRepository $config */
$config = $app['config'];
Expand Down Expand Up @@ -355,6 +392,7 @@
'api_platform.graphql.state_provider.parameter',
FieldsBuilderEnumInterface::class,
ExceptionHandlerInterface::class,
ObjectMapperInterface::class

Check warning on line 395 in src/Laravel/ApiPlatformDeferredProvider.php

View check run for this annotation

Codecov / codecov/patch

src/Laravel/ApiPlatformDeferredProvider.php#L395

Added line #L395 was not covered by tests
];
}
}
4 changes: 0 additions & 4 deletions src/Serializer/SerializerContextBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,6 @@ public function createFromRequest(Request $request, bool $normalization, ?array
}
}

if (null === $context['output'] && $this->getStateOptionsClass($operation)) {
$context['force_resource_class'] = $operation->getClass();
}

Copy link
Member Author

Choose a reason for hiding this comment

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

@GromNaN this is probably fixing the issue you commented about the denormalizer.

Could you review again?

if ($this->debug && isset($context['groups']) && $operation instanceof ErrorOperation) {
if (!\is_array($context['groups'])) {
$context['groups'] = (array) $context['groups'];
Expand Down
38 changes: 38 additions & 0 deletions src/State/Processor/ObjectMapperProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?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\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\ObjectMapper\ObjectMapperInterface;

final class ObjectMapperProcessor implements ProcessorInterface
{
public function __construct(
private readonly ObjectMapperInterface $objectMapper,
private readonly ProcessorInterface $decorated,
) {
}

public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
if (!(new \ReflectionClass($operation->getClass()))->getAttributes(Map::class)) {
return $this->decorated->process($data, $operation, $uriVariables, $context);
}

return $this->objectMapper->map($this->decorated->process($this->objectMapper->map($data, $context['data'] ?? null), $operation, $uriVariables, $context));

Check failure on line 36 in src/State/Processor/ObjectMapperProcessor.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Offset 'data' on array{request?: Symfony\Component\HttpFoundation\Request, previous_data?: mixed, resource_class?: string|null, original_data?: mixed} on left side of ?? does not exist.
}
}
60 changes: 60 additions & 0 deletions src/State/Provider/ObjectMapperProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?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\Provider;

use ApiPlatform\Doctrine\Odm\State\Options as OdmOptions;
use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\Pagination\ArrayPaginator;
use ApiPlatform\State\Pagination\PaginatorInterface;
use ApiPlatform\State\ProviderInterface;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\ObjectMapper\ObjectMapperInterface;

final class ObjectMapperProvider implements ProviderInterface
{
public function __construct(
private readonly ObjectMapperInterface $objectMapper,
private readonly ProviderInterface $decorated,
) {
}

public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
$data = $this->decorated->provide($operation, $uriVariables, $context);

if (!\is_object($data)) {
return $data;
}

$entityClass = $operation->getClass();
Copy link
Contributor

@GromNaN GromNaN Mar 15, 2025

Choose a reason for hiding this comment

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

The DenormalizeProvider already create an instance of the operation class. Mapping into the same target class as the source class doesn't seem a valid use case to me. Making this provider useful only with Doctrine.

Copy link
Member Author

Choose a reason for hiding this comment

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

The denormalizer provider is only called on write operations. but indeed they should be doctrine-oriented it would make more sense

if (($options = $operation->getStateOptions()) && $options instanceof Options && $options->getEntityClass()) {
$entityClass = $options->getEntityClass();
}

if (($options = $operation->getStateOptions()) && $options instanceof OdmOptions && $options->getDocumentClass()) {
$entityClass = $options->getDocumentClass();

Check warning on line 47 in src/State/Provider/ObjectMapperProvider.php

View check run for this annotation

Codecov / codecov/patch

src/State/Provider/ObjectMapperProvider.php#L47

Added line #L47 was not covered by tests
}

if (!(new \ReflectionClass($entityClass))->getAttributes(Map::class)) {
return $data;
}

if ($data instanceof PaginatorInterface) {
return new ArrayPaginator(array_map(fn ($v) => $this->objectMapper->map($v), iterator_to_array($data)), 0, \count($data));
}

return $this->objectMapper->map($data);
}
}
3 changes: 2 additions & 1 deletion src/State/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"php": ">=8.2",
"api-platform/metadata": "^4.1.11",
"psr/container": "^1.0 || ^2.0",
"symfony/http-kernel": "^6.4 || ^7.0"
"symfony/http-kernel": "^6.4 || ^7.0",
"symfony/object-mapper": "^7.3.0-RC1"
},
"require-dev": {
"phpunit/phpunit": "11.5.x-dev",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpClient\ScopingHttpClient;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Uid\AbstractUid;
use Symfony\Component\Validator\Validator\ValidatorInterface;
Expand Down Expand Up @@ -169,6 +170,9 @@ public function load(array $configs, ContainerBuilder $container): void
$this->registerArgumentResolverConfiguration($loader);
$this->registerLinkSecurityConfiguration($loader, $config);

if (class_exists(Map::class)) {
$loader->load('state/object_mapper.xml');
}
$container->registerForAutoconfiguration(FilterInterface::class)
->addTag('api_platform.filter');
$container->registerForAutoconfiguration(ProviderInterface::class)
Expand Down
17 changes: 17 additions & 0 deletions src/Symfony/Bundle/Resources/config/state/object_mapper.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="api_platform.state_provider.object_mapper" class="ApiPlatform\State\Provider\ObjectMapperProvider" decorates="api_platform.state_provider.read">
<argument type="service" id="object_mapper" />
<argument type="service" id="api_platform.state_provider.object_mapper.inner" />
</service>

<service id="api_platform.state_processor.object_mapper" class="ApiPlatform\State\Processor\ObjectMapperProcessor" decorates="api_platform.state_processor.locator">
<argument type="service" id="object_mapper" />
<argument type="service" id="api_platform.state_processor.object_mapper.inner" />
</service>
</services>
</container>
6 changes: 3 additions & 3 deletions src/Symfony/Controller/MainController.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,6 @@ public function __invoke(Request $request): Response
}
}

$context['previous_data'] = $request->attributes->get('previous_data');
$context['data'] = $request->attributes->get('data');

if (null === $operation->canWrite()) {
$operation = $operation->withWrite(!$request->isMethodSafe());
}
Expand All @@ -120,6 +117,9 @@ public function __invoke(Request $request): Response
$operation = $operation->withSerialize(true);
}

$context['previous_data'] = $request->attributes->get('previous_data');
$context['data'] = $request->attributes->get('data');

return $this->processor->process($body, $operation, $uriVariables, $context);
}
}
1 change: 1 addition & 0 deletions src/Symfony/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"api-platform/parameter-validator": "^3.1",
"phpspec/prophecy-phpunit": "^2.2",
"phpunit/phpunit": "11.5.x-dev",
"symfony/object-mapper": "v7.3.0-RC1",
"symfony/expression-language": "^6.4 || ^7.0",
"symfony/intl": "^6.4 || ^7.0",
"symfony/mercure-bundle": "*",
Expand Down
42 changes: 42 additions & 0 deletions tests/Fixtures/TestBundle/ApiResource/MappedResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?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\Tests\Fixtures\TestBundle\ApiResource;

use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\JsonLd\ContextBuilder;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Tests\Fixtures\TestBundle\Entity\MappedEntity;
use Symfony\Component\ObjectMapper\Attribute\Map;

#[ApiResource(stateOptions: new Options(entityClass: MappedEntity::class), normalizationContext: [ContextBuilder::HYDRA_CONTEXT_HAS_PREFIX => false])]
#[Map(target: MappedEntity::class)]
final class MappedResource
{
#[Map(if: false)]
public ?string $id = null;

#[Map(target: 'firstName', transform: [self::class, 'toFirstName'])]
#[Map(target: 'lastName', transform: [self::class, 'toLastName'])]
public string $username;

public static function toFirstName(string $v): string
{
return explode(' ', $v)[0] ?? null;
}

public static function toLastName(string $v): string
{
return explode(' ', $v)[1] ?? null;
}
}
69 changes: 69 additions & 0 deletions tests/Fixtures/TestBundle/Entity/MappedEntity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?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\Tests\Fixtures\TestBundle\Entity;

use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\ObjectMapper\Attribute\Map;

/**
* MappedEntity to MappedResource.
*/
#[ORM\Entity]
#[Map(target: MappedResource::class)]
class MappedEntity
{
#[ORM\Column(type: 'integer')]
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'AUTO')]
private ?int $id = null;

#[ORM\Column]
#[Map(if: false)]
private string $firstName;

#[Map(target: 'username', transform: [self::class, 'toUsername'])]
#[ORM\Column]
private string $lastName;

public static function toUsername($value, $object): string
{
return $object->getFirstName().' '.$object->getLastName();
}

public function getId(): ?int
{
return $this->id;
}

public function setLastName(string $name): void
{
$this->lastName = $name;
}

public function getLastName(): string
{
return $this->lastName;
}

public function setFirstName(string $name): void
{
$this->firstName = $name;
}

public function getFirstName(): string
{
return $this->firstName;
}
}
Loading
Loading