Cloning an entity with an Uploadable field from VichUploaderBundle

92 views Asked by At

I have a Symfony 6.2.6 application running on PHP 8.2.

What's the best way to clone an entity that has an Uploadable field?


I have created a MediaObject class, using API Platform docs for reference:

#[Vich\Uploadable]
#[ORM\Entity]
class MediaObject
{
    #[ORM\Id, ORM\Column, ORM\GeneratedValue]
    private ?int $id = null;

    #[ApiProperty(types: ['https://schema.org/contentUrl'])]
    public ?string $contentUrl = null;

    #[Vich\UploadableField(mapping: "media_object", fileNameProperty: "filePath")]
    public ?File $file = null;

    #[ORM\Column(nullable: true)]
    public ?string $filePath = null;

// ...
}

The MediaObject is then in turn linked to multiple entities using Many to Many relationships.

My problem arised when I tried to clone an entity that has a Many to Many relationship with MediaObject. I used the myclabs/DeepCopy package, which did the trick. It created a copy of the MediaObject entity with the same filePath. Here's the problem:

Let's assume you have an Offer A, which is linked to MediaObject A (image.png). After cloning it, you now have an Offer B, which is linked to MediaObject B (image.png).

Once you delete one of the MediaObjects, the other remains intact, but the file is deleted on disk. This leads to data loss.


What's the best way to approach this problem? I see two viable options:

  1. Cloning the file on disk - would work, as copying in my use case isn't too frequent. For other use cases it might lead to overwhelming storage use.
  2. Checking if MediaObjects exist prior to deleting - also would work, but I couldn't find how do I get this working for VichUploaderBundle. Would probably need an index on the filePath column.

I would appreciate input and/or code samples! Thanks in advance for your help.

0

There are 0 answers