Skip to content

DTO not considered when ObjectMapper is defined #7593

@Spomky

Description

@Spomky

API Platform version(s) affected: 4.2.x

Description
It looks like the output (and maybe input -not tested yet) class is not considered when Object Mapper is used.
Let say I have this resource with DTO for both operations. The DTOs have a #[Map] attribute.

namespace App\Api\Resource;

use ApiPlatform\Doctrine\Orm\State\Options;
use ApiPlatform\Metadata\ApiResource;
use App\Entity\Book as BookEntity;
use Symfony\Component\ObjectMapper\Attribute\Map;

#[ApiResource(
    stateOptions: new Options(entityClass: BookEntity::class),
    operations: [
        new Get(
            output: BookItem::class
        ),
        new GetCollection(
            output: BookCollection::class
        ),
    ]
)]
#[Map(source: BookEntity::class)]
final class Book
{
    public int $id;
    public string $name;
}

The data returned by the API endpoints are not the DTOs, but the Book resource.

How to reproduce
Use the example above.

Possible Solution
From my understanding, the ObjectMappedProvider and the ObjectMapperProcessor use the $operation->getClass() method to perform the mapping.
getClass returns the class that holds the operation and not the DTO to be used.

A new method getMappedClass should exist and be used by the Provider and Processor.
This method should return the output/input DTO class if it has a #[Map] attribute or the resource class. In the example, getClass will return Book::class (current behavior) and getMappedClass should return BookItem::class or BookCollection::class.

canMap should be modified accordingly

Additional Context

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions