Skip to content

Instantly share code, notes, and snippets.

@ollo-ride-nico
Created January 26, 2018 16:56
Show Gist options
  • Save ollo-ride-nico/b52c2df8c64cd1a0ee547054ae4c8b81 to your computer and use it in GitHub Desktop.
Save ollo-ride-nico/b52c2df8c64cd1a0ee547054ae4c8b81 to your computer and use it in GitHub Desktop.
// Listener
class ImageUploadListener
{
private $uploader;
public function __construct(FileUploader $uploader)
{
$this->uploader = $uploader;
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
private function uploadFile($entity)
{
// upload only works for Image class inherited entities
if (!$entity instanceof Image) {
return;
}
;
$file = $entity->getUrl();
$nameAlt = $entity->getAlt();
// only upload new files
if ($file instanceof UploadedFile) {
$fileName = $this->uploader->upload($file);
$entity->setUrl($fileName);
$entity->setAlt($nameAlt);
}
}
}
// Uploader
class FileUploader
{
const ASSET_PATH = 'images/';
private $targetDir;
public function __construct($targetDir)
{
$this->targetDir = $targetDir . '/uploads/' . self::ASSET_PATH;
}
public function upload(UploadedFile $file)
{
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getTargetDir(), $fileName);
return $fileName;
}
public function getTargetDir()
{
return $this->targetDir;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment