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

Conversation

soyuka
Copy link
Member

@soyuka soyuka commented Nov 15, 2024

Q A
Branch? main
License MIT

Still a few things left to be done but this is a first approach. This makes API Platform compatible with the Object Mapper component: symfony/symfony#51741

Demo:

composer create-project symfony/skeleton test-objectmapper2
cd test-objectmapper2
composer req debug api-platform/symfony api-platform/doctrine-orm make orm symfony/asset 
nvim .env # uncomment sqlite
nvim composer.json # change extra.symfony to 7.3.*
composer config minimum-stability RC
composer req symfony/object-mapper:^7.3.0-RC1 symfony/type-info:v7.3.0-RC1 symfony/framework-bundle:v7.3.0-RC1 -W 
# clone my pr https://github.com/api-platform/core/pull/6801 to a parent directory:
# example with gh in a api-platform/core clone: `gh pr checkout 6801`
composer link ../core-6801 # if link is not available `composer global require soyuka/pmu`
bin/console make:entity # create an entity Book with id/title
bin/console d:s:u --force 
frankenphp php-server --listen :8080 -r public

Example:

<?php

namespace App\Entity;

use App\ApiResource\Book as AppBook;
use App\Repository\BookRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\ObjectMapper\Attribute\Map;

#[ORM\Entity(repositoryClass: BookRepository::class)]
#[Map(target: AppBook::class)]
class Book
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 255)]
    #[Map(transform: 'ucfirst')] // example of transformation to the dto
    private ?string $title = null;

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

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): static
    {
        $this->title = $title;

        return $this;
    }
}
<?php

namespace App\ApiResource;

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))]
#[Map(target: BookEntity::class)]
class Book
{
    #[Map(if: false)] // do not map the id from the dto to the entity
    public string $id;
    #[Map(transform: 'strtolower')] // example of transformation
    public string $title;
}

Copy link

stale bot commented Jan 15, 2025

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Copy link
Contributor

@GromNaN GromNaN left a comment

Choose a reason for hiding this comment

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

I think these provider and processor are Doctrine-specific. They should be moved to the Doctrine namespace and we can consider injecting the ObjectManager of ORM or ODM to retrieve the attached object.

Unless the new symfony/mapper component is able to use a factory to create the Entity class from the DTO. It would use the Id field of the DTO to retreive the attached entity from the entity manager.

composer.json Outdated
Comment on lines 213 to 216
"repositories": [
{ "type": "path", "url": "../symfony/src/Symfony/Component/ObjectMapper" },
{ "type": "path", "url": "../symfony/src/Symfony/Bundle/FrameworkBundle" }
],
Copy link
Contributor

Choose a reason for hiding this comment

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

If that can help, I use this script to link external directories in my project vendors: https://gist.github.com/GromNaN/020dd50fc3ed71d31ebc548bb75845e7

Copy link
Member Author

Choose a reason for hiding this comment

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

I built https://github.com/soyuka/pmu for that now :p

return $this->decorated->process($data, $operation, $uriVariables, $context);
}

return $this->objectMapper->map($this->decorated->process($this->objectMapper->map($data), $operation, $uriVariables, $context));
Copy link
Contributor

Choose a reason for hiding this comment

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

In PATCH and DELETE operations, you must map into the entity attached to the EntityManager when retrieved in the provider.

Otherwise the decorated doctrine processor will try to persist a new object (and maybe fail on duplicate primary key), or skip removing the non-persisted entity.

Copy link
Contributor

Choose a reason for hiding this comment

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

Isn't it necessary to include the entity in the context for PUT operations?
Here’s an example of what I had done for a DtoToEntityProcessor:

$this->validator->validate($data);
$entity = $this->mapDtoToEntity($data, $entityClass, $context);

$context['previous_data'] = $entity;
$entity = $this->persistProcessor->process($entity, $operation, $uriVariables, $context);
$data->id = $entity->getId();

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

@soyuka soyuka force-pushed the feat/automapper branch from 6e954d5 to ff46774 Compare May 27, 2025 15:52
@soyuka soyuka force-pushed the feat/automapper branch from ff46774 to 280ee15 Compare May 27, 2025 15:57
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?

@soyuka
Copy link
Member Author

soyuka commented May 28, 2025

I'll fix the tests once the component is released

@soyuka soyuka marked this pull request as ready for review May 28, 2025 08:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants