<?php

/*
 * 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 CpCreation\VitiCore\Behavior\Impl;

use CpCreation\VitiCore\Media\Model\File as ModelFile;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

trait FileMandatory
{
    #[ORM\OneToOne(
        targetEntity: ModelFile::class,
        cascade: ['persist', 'remove']
    )]
    #[Assert\Valid]
    private ?ModelFile $file = null;

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

    public function setFile(?ModelFile $file): void
    {
        if (null !== $file && ($file->getPath() || $file->getFile())) {
            $this->file = $file;
        } else {
            $this->file = null;
        }
    }

    #[Assert\Callback]
    public function validate(ExecutionContextInterface $context): void
    {
        if (null !== $this->file) {
            if (!$this->file->getFile() && !$this->file->getPath()) {
                $context->buildViolation('This value should not be blank.')
                    ->atPath('file.file')
                    ->addViolation();
            }
        }
    }
}
