api-platform / core

The server component of API Platform: hypermedia and GraphQL APIs in minutes
https://api-platform.com
MIT License
2.39k stars 846 forks source link

Conflict between `original_data` cloning and application cloning in WriteListener #6362

Closed ZZromanZZ closed 1 month ago

ZZromanZZ commented 1 month ago

API Platform version(s) affected: 3.3.2

Description

I noticed that in PR #6102 was added feature to clone original data in Symfony WriteListener. This orignal data are further used to generate Content-Location header. However when someone already use __clone() on Entity (original data object) to provide some other bussiness functionality and resets id property (for example):

public function __clone()
{
    $this->id = null;
}

Generating Content Location header fails with Metadata RuntimeException No identifier value found, did you forget to persist the entity?

image

How to reproduce
Simple GET /api/entity/{id} with __clone() method setting ID property to null results to RuntimeException Of course, this issue applies only for Symfony (use_symfony_listeners: true)

Possible Solution

I'm not sure why is cloning original data even needed.

amyAMeQ commented 1 month ago

This is definitely a problem for us. My API uses entities from a shared library, and several entities have __clone functions that intentionally do not copy over the id. Things would be ok if the IRI wasn't generated based on previous data, but on current data.

amyAMeQ commented 1 month ago

OK. I have a work around for those of us who stubbornly wanted to update. You can decorate the WriteListener Here is my quick implementation. (I've just banged it out and not put it through any significant tests yet)

<?php

namespace App\EventListener;

use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Throwable;

#[AsDecorator('api_platform.listener.view.write')]
class WriteListener
{
    public function __construct(private \ApiPlatform\Symfony\EventListener\WriteListener $decorated)
    {
    }

    public function onKernelView(ViewEvent $event): void
    {
        $this->decorated->onKernelView($event);
        $data = $event->getControllerResult();
        $request = $event->getRequest();
        $method = $request->getMethod();
        if ('GET' === $method) {
            try {
                $originalData = $request->attributes->get('original_data');
                if ($data->getId() && !$originalData->getId()) {
                    $request->attributes->set('original_data', $data);
                }
            } catch (Throwable) {
            }
        }
    }
}
soyuka commented 1 month ago

I'm not sure why is cloning original data even needed.

Thanks for the detailed report I'll fix this, indeed it looks like cloning is not needed there, can you confirm the patch solves your issue? Thanks.

ZZromanZZ commented 1 month ago

@soyuka Works, thank you.