<?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\Attribute\Attachment;
use Serenity\MediaBundle\Entity\File;
use Symfony\Component\Validator\Constraints as Assert;

trait FileTrait
{
    #[Assert\Valid]
    #[ORM\OneToOne(targetEntity: File::class, cascade: ['all'])]
    #[ORM\JoinColumn(name: 'file_id', referencedColumnName: 'id', onDelete: 'SET NULL')]
    #[Attachment]
    private ?File $file = null;

    public function getFile(): ?File
    {
        return $this->file;
    }

    public function setFile(?File $file): void
    {
        if (null === $file) {
            return;
        }
        if (!$file->getUploadedFile() && !$file->getFile()->getName()) {
            $this->file = null;

            return;
        }
        $this->file = $file;
    }
}
