Created
January 26, 2018 16:56
-
-
Save ollo-ride-nico/b52c2df8c64cd1a0ee547054ae4c8b81 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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