core icon indicating copy to clipboard operation
core copied to clipboard

feat(symfony): object mapper with state options

Open soyuka opened this issue 1 year ago • 2 comments

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: https://github.com/symfony/symfony/pull/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;
}

soyuka avatar Nov 15 '24 15:11 soyuka

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.

stale[bot] avatar Jan 15 '25 03:01 stale[bot]

I'll fix the tests once the component is released

soyuka avatar May 28 '25 08:05 soyuka