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

Merged
merged 1 commit into from
Jun 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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@
"symfony/maker-bundle": "^1.24",
"symfony/mercure-bundle": "*",
"symfony/messenger": "^6.4 || ^7.0",
"symfony/object-mapper": "^7.3",
"symfony/routing": "^6.4 || ^7.0",
"symfony/security-bundle": "^6.4 || ^7.0",
"symfony/security-core": "^6.4 || ^7.0",
Expand Down
47 changes: 47 additions & 0 deletions src/State/Processor/ObjectMapperProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?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\State\Processor;

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

/**
* @implements ProcessorInterface<mixed,mixed>
*/
final class ObjectMapperProcessor implements ProcessorInterface
{
/**
* @param ProcessorInterface<mixed,mixed> $decorated
*/
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 (!$this->objectMapper || !$operation->canWrite()) {
return $this->decorated->process($data, $operation, $uriVariables, $context);

Check warning on line 38 in src/State/Processor/ObjectMapperProcessor.php

View check run for this annotation

Codecov / codecov/patch

src/State/Processor/ObjectMapperProcessor.php#L38

Added line #L38 was not covered by tests
}

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), $operation, $uriVariables, $context));

Choose a reason for hiding this comment

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

Hi @soyuka , thanks for your work on this!

The map method is called without the $target parameter, even though we could extract the expected output class via:

$outputClass = $operation->getOutput()['class'] ?? null;

Would it make sense to pass this as the $target to improve mapping clarity ?

Same idea could apply to the mapping for ORM entity conversion — the target class could be extracted from stateOptions.

Copy link
Member Author

Choose a reason for hiding this comment

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

IMO the mapping should be defined with the Map attribute, as you could Map and have a different output.

Choose a reason for hiding this comment

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

To ensure the output matches the generated OpenAPI documentation, wouldn’t it make more sense to use the class specified in output, if it has been provided?
In cases where multiple target classes are possible, how should we determine which one should be used?

Copy link
Member Author

Choose a reason for hiding this comment

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

Indeed I need to think about this but its best that your resource is your output. Could you please open a new issue with your use case ?

}
}
77 changes: 77 additions & 0 deletions src/State/Provider/ObjectMapperProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?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\State\Provider;

use ApiPlatform\Doctrine\Odm\State\Options as OdmOptions;
use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Util\CloneTrait;
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;

/**
* @implements ProviderInterface<object>
*/
final class ObjectMapperProvider implements ProviderInterface
{
use CloneTrait;

/**
* @param ProviderInterface<object> $decorated
*/
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 (!$this->objectMapper || !\is_object($data)) {
return $data;
}

$request = $context['request'] ?? null;
$entityClass = null;
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 57 in src/State/Provider/ObjectMapperProvider.php

View check run for this annotation

Codecov / codecov/patch

src/State/Provider/ObjectMapperProvider.php#L57

Added line #L57 was not covered by tests
}

$entityClass ??= $data::class;

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

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

$request?->attributes->set('data', $data);
$request?->attributes->set('previous_data', $this->clone($data));

return $data;
}
}
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\ObjectMapper;
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(ObjectMapper::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" on-invalid="null" />
<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" on-invalid="null" />
<argument type="service" id="api_platform.state_processor.object_mapper.inner" />
</service>
</services>
</container>
45 changes: 45 additions & 0 deletions tests/Fixtures/TestBundle/ApiResource/MappedResource.php
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\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];
}

public static function toLastName(string $v): string
{
return explode(' ', $v)[1];
}
}
45 changes: 45 additions & 0 deletions tests/Fixtures/TestBundle/ApiResource/MappedResourceOdm.php
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\Tests\Fixtures\TestBundle\ApiResource;

use ApiPlatform\Doctrine\Odm\State\Options;
use ApiPlatform\JsonLd\ContextBuilder;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Tests\Fixtures\TestBundle\Document\MappedDocument;
use Symfony\Component\ObjectMapper\Attribute\Map;

#[ApiResource(
stateOptions: new Options(documentClass: MappedDocument::class),
normalizationContext: [ContextBuilder::HYDRA_CONTEXT_HAS_PREFIX => false],
)]
#[Map(target: MappedDocument::class)]
final class MappedResourceOdm
{
#[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];
}

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

use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedResourceOdm;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Symfony\Component\ObjectMapper\Attribute\Map;

/**
* MappedEntity to MappedResource.
*/
#[ODM\Document]
#[Map(target: MappedResourceOdm::class)]
class MappedDocument
{
#[ODM\Id(strategy: 'INCREMENT', type: 'int')]
private ?int $id = null;

#[ODM\Field(type: 'string')]
#[Map(if: false)]
private string $firstName;

#[Map(target: 'username', transform: [self::class, 'toUsername'])]
#[ODM\Field(type: 'string')]
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;
}
}
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 <[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\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