An error occurred while loading the file. Please try again.
-
Guillaume Perréal authored5d46e728
<?php
/*
* Copyright (C) 2015 IRSTEA
* All rights reserved.
*/
namespace Irstea\FileUploadBundle\Form\DataTranformer;
use Irstea\FileUploadBundle\Entity\UploadedFile;
use Irstea\FileUploadBundle\Service\FileManagerInterface;
use Rhumsaa\Uuid\Uuid;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
/**
* Description of UploadedFileTransformer
*/
class UploadedFileTransformer implements DataTransformerInterface
{
/**
*
* @var boolean
*/
private $multiple;
/**
*
* @var FileManagerInterface
*/
private $fileManager;
public function __construct(FileManagerInterface $fileManager, $multiple = false)
{
$this->fileManager = $fileManager;
$this->multiple = $multiple;
}
/**
* {@inheritdoc}
*/
public function reverseTransform($value)
{
if(!$this->multiple) {
return $this->reverseTransformFile($value);
}
if(null === $value || '' === $value) {
return [];
}
if(!is_array($value) && !$value instanceof \Traversable) {
throw new TransformationFailedException('Expected an array or a \Traversable.');
}
$result = [];
foreach($value as $index => $identifier) {
if(null !== $file = $this->reverseTransformFile($identifier)) {
$result[$index] = $file;
}
}
return $result;
}
/**
* {@inheritdoc}
*/
public function transform($value)
{
if(!$this->multiple) {
7172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
return $this->transformFile($value);
}
if(empty($value)) {
return [];
}
if(!is_array($value) && !$value instanceof \Traversable) {
throw new TransformationFailedException('Expected an array or a \Traversable.');
}
$result = [];
foreach($value as $index => $file) {
if(null !== $item = $this->transformFile($file)) {
$result[$index] = $item;
}
}
return $result;
}
/**
*
* @param mixed $value
* @return mixed
*/
protected function transformFile($value)
{
if(null === $value) {
return null;
}
if(!$value instanceof UploadedFile) {
throw new TransformationFailedException('Expected an UploadedFile.');
}
return $value;
}
/**
*
* @param mixed $value
* @return UploadedFile
*/
protected function reverseTransformFile($value)
{
if(is_string($value) && Uuid::isValid($value)) {
$value = $this->fileManager->get($value);
}
if(null === $value || '' === $value) {
return null;
}
if($value instanceof UploadedFile) {
if($value->isOrphelin()) {
$value->setEtat(UploadedFile::ETAT_NORMAL);
}
return $value;
}
throw new TransformationFailedException('Expected an UploadedFile or a valid file UUID.');
}
}