add FileAttribute to handle file in attributes

This commit is contained in:
Simon Vieille 2021-06-21 15:48:06 +02:00
parent 069f93c1c6
commit 41190f43b2
3 changed files with 34 additions and 20 deletions

View file

@ -2,6 +2,7 @@
namespace App\Core\Entity\Site\Page; namespace App\Core\Entity\Site\Page;
use App\Core\File\FileAttribute;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\File;
@ -12,17 +13,7 @@ class FileBlock extends Block
{ {
public function getValue() public function getValue()
{ {
$value = parent::getValue(); return FileAttribute::handleFile(parent::getValue());
if (is_string($value)) {
if (file_exists($value)) {
return new File($value);
}
return null;
}
return $value;
} }
public function setValue($value): self public function setValue($value): self

View file

@ -11,6 +11,7 @@ use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\File;
use App\Core\File\FileAttribute;
/** /**
* @ORM\Entity(repositoryClass=PageRepository::class) * @ORM\Entity(repositoryClass=PageRepository::class)
@ -229,15 +230,7 @@ class Page implements EntityInterface
public function getOgImage() public function getOgImage()
{ {
if (is_string($this->ogImage)) { return FileAttribute::handleFile($this->ogImage);
if (file_exists($this->ogImage)) {
return new File($this->ogImage);
}
return null;
}
return $this->ogImage;
} }
public function setOgImage($ogImage): self public function setOgImage($ogImage): self

View file

@ -0,0 +1,30 @@
<?php
namespace App\Core\File;
use Symfony\Component\HttpFoundation\File\File;
/**
* class FileAttribute.
*
* @author Simon Vieille <simon@deblan.fr>
*/
class FileAttribute
{
public static function handleFile($attribute, string $class = null)
{
if (null === $class) {
$class = File::class;
}
if (is_string($attribute)) {
if (file_exists($attribute)) {
return new $class($attribute);
}
return null;
}
return $attribute;
}
}