Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
App\Model\File:
type: entity
table: files
entityListeners:
App\Doctrine\EventListener\FileUploadListener:
prePersist: [upload]
preUpdate: [upload]
preRemove: [remove]
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
path:
type: string
<?php
namespace App\Model;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class File
{
/**
* @var int
*/
protected $id;
/**
* @var UploadedFile|null
*/
protected $file;
/**
* @var string
*/
protected $path;
/**
* @return int
*/
public function getId()
{
return $this->id;
}
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
return $this;
}
/**
* @return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* @param mixed $path
*
* @return $this
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
}
<?php
namespace App\Doctrine\EventListener;
use App\Model\Image;
class FileUploadListener
{
public function __construct($uploadDir)
{
$this->uploadDir = $uploadDir;
}
public function upload(Image $image)
{
if (null === $image->getFile()) {
return;
}
$targetDir = $this->getTargetDir($image->getFile());
$image->getFile()->move(
sprintf('%s/%s', rtrim($this->uploadDir, '/'), $targetDir),
$image->getFile()->getClientOriginalName()
);
$image->setPath(sprintf('%s/%s', $targetDir, $image->getFile()->getClientOriginalName()));
$image->setFile(null);
}
public function remove(Image $image)
{
if (file_exists($image->getPath())) {
unlink($image->getPath());
}
}
private function getTargetDir(\SplFileInfo $file)
{
$checksum = hash('sha1', file_get_contents($file->getRealPath()));
return sprintf('%s/%s/%s/%s/%s', substr($checksum, 0, 2), substr($checksum, 2, 2), substr($checksum, 4, 4), substr($checksum, 8, 4), $checksum);
}
}
services:
doctrine.listener.file_upload:
class: App\Doctrine\EventListener\FileUploadListener
arguments: [%images_upload_dir%]
tags:
- { name: doctrine.orm.entity_listener }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment