<?php

/**
 * @author Colinet Julien
 */
declare(strict_types=1);

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\MediaBundle\Trait;

use Doctrine\ORM\Mapping as ORM;
use Serenity\MediaBundle\Entity\Image;
use Symfony\Component\Validator\Constraints as Assert;

trait ImageTrait
{
    #[Assert\Valid]
    #[ORM\OneToOne(targetEntity: Image::class, cascade: ['all'], orphanRemoval: true)]
    #[ORM\JoinColumn(name: 'image_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
    private ?Image $image = null;

    public function getImage(): ?Image
    {
        return $this->image;
    }

    public function setImage(?Image $image): void
    {
        if (null === $image) {
            return;
        }
        if (!$image->getUploadedFile() && !$image->getFile()->getName()) {
            $this->image = null;

            return;
        }
        if (method_exists($this, 'getId') && $this->getId()) {
            $image->setParentId($this->getId());
        }
        $image->setParentClass(static::class);

        $this->image = $image;
    }
}
