Skip to content

Instantly share code, notes, and snippets.

@hubgit
Last active January 11, 2018 00:00
Show Gist options
  • Save hubgit/0cdf96c296f20017fe91 to your computer and use it in GitHub Desktop.
Save hubgit/0cdf96c296f20017fe91 to your computer and use it in GitHub Desktop.
Symfony service to subscribe to VichUploaderBundle's POST_UPLOAD event. Saves file details as new entity fields. Note: untested since pasting and editing, may not work as-is.
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* @ORM\Table()
* @ORM\Entity()
* @Vich\Uploadable()
* @ORM\HasLifecycleCallbacks()
*/
class Attachment
{
/**
* @var File
*
* @Assert\File(
* maxSize="100Mi",
* disallowEmptyMessage=true
* )
*
* @Vich\UploadableField(
* mapping="attachment_file",
* fileNameProperty="fileName"
* )
*/
private $file;
/**
* @var string
*
* @ORM\Column(type="string", length=255)
*/
private $fileName;
/**
* @var int
*
* @ORM\Column(type="integer")
*/
private $fileSize;
/**
* @var string
*
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $mimeType;
/**
* @return FileEntity
*/
public function getFile()
{
return $this->file;
}
/**
* @param File|UploadedFile|null $file
*/
public function setFile(File $file = null)
{
$this->file = $file;
if ($file instanceof UploadedFile) {
$this->updated = new \DateTime();
}
}
/**
* @return string
*/
public function getFileName()
{
return $this->fileName;
}
/**
* @param string $fileName
*/
public function setFileName($fileName)
{
$this->fileName = $fileName;
}
/**
* @return int
*/
public function getFileSize()
{
return $this->fileSize;
}
/**
* @param int $fileSize
*/
public function setFileSize($fileSize)
{
$this->fileSize = $fileSize;
}
/**
* @return string
*/
public function getMimeType()
{
return $this->mimeType;
}
/**
* @param string $mimeType
*/
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
}
}
<?php
namespace AppBundle\Service;
use AppBundle\Entity\Attachment;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Vich\UploaderBundle\Event as VichEvent;
class FileSubscriber implements EventSubscriberInterface
{
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
VichEvent\Events::POST_UPLOAD => 'postUpload'
];
}
/**
* @param VichEvent\Event $event
*/
public function postUpload(VichEvent\Event $event)
{
/** @var Attachment $object */
$object = $event->getObject();
$file = $object->getFile();
$object->setFileSize($file->getSize());
$object->setMimeType($file->getMimeType());
}
}
services:
app.file_subscriber:
class: AppBundle\Service\FileSubscriber
tags:
- { name: kernel.event_subscriber }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment