<?php
/**
 * @author Colinet Julien
 */
namespace CpCreation\VitiCore\Behavior\Impl;

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

trait FileMandatory
{
    /**
     * @ORM\OneToOne(targetEntity="CpCreation\VitiCore\Media\Model\Fil", cascade={"persist", "remove"})
     * @Assert\Valid()
     *
     * @var ModelFile
     */
    private $file;

    /**
     * @return ModelFile|null
     */
    public function getFile(): ?ModelFile
    {
        return $this->file;
    }

    /**
     * @param ModelFile $file
     */
    public function setFile(ModelFile $file = null)
    {
        if ($file->getPath() || $file->getFile())
        {
            $this->file = $file;
        }else{
            $this->file = null;
        }
    }

    /**
     * @param \Symfony\Component\Validator\Context\ExecutionContextInterface $context
     * @Assert\Callback()
     */
    public function validate(ExecutionContextInterface $context)
    {
        if ($this->file) {
            if (!$this->file->getFile() && !$this->file->getPath()){
                $message = 'This value should not be blank.';
                $context->buildViolation($message)
                        ->atPath("file.file")
                        ->addViolation();
            }
        }
    }
}
