Last active
April 14, 2021 07:17
-
-
Save stefankleff/a4e0a2f546f5526cec3678213b829d06 to your computer and use it in GitHub Desktop.
Usage of IDs in files and directories for VichUploader bundle
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
<?php | |
namespace App\EventListener; | |
use Doctrine\Common\EventArgs; | |
use Doctrine\ORM\Event\LifecycleEventArgs; | |
use Doctrine\ORM\Event\OnFlushEventArgs; | |
use Vich\UploaderBundle\EventListener\Doctrine\BaseListener; | |
class UploadListener extends BaseListener | |
{ | |
/** | |
* VichUploader is using prePersist and preUpdate events. | |
* These events are executed BEFORE the id of the entity is generated. | |
* Because we potentially want to use the id in the file or directory name, | |
* we can't use these events. | |
* The OnFlush event is thrown after the id generation in the Unit of Work. | |
* This allows usage of id generators (f.ex. Symfony UUID, PostgresSQL) with | |
* the exception of postInsertGenerators like MySQL autoincrement. | |
* The event is also not yet in the database transaction, therefore it's safe | |
* to execute a potential long running upload. | |
* | |
* @return array The array of events | |
*/ | |
public function getSubscribedEvents(): array | |
{ | |
return [ | |
'onFlush', | |
]; | |
} | |
public function onFlush(OnFlushEventArgs $eventArgs) | |
{ | |
$em = $eventArgs->getEntityManager(); | |
$uow = $em->getUnitOfWork(); | |
foreach ($uow->getScheduledEntityInsertions() as $entity) { | |
$event = new LifecycleEventArgs($entity, $em); | |
$this->upload($event); | |
} | |
foreach ($uow->getScheduledEntityUpdates() as $entity) { | |
$event = new LifecycleEventArgs($entity, $em); | |
$this->upload($event); | |
} | |
} | |
/** | |
* @param EventArgs $event The event | |
* | |
* @throws \Vich\UploaderBundle\Exception\MappingNotFoundException | |
*/ | |
public function upload(EventArgs $event): void | |
{ | |
$object = $this->adapter->getObjectFromArgs($event); | |
if (!$this->isUploadable($object)) { | |
return; | |
} | |
foreach ($this->getUploadableFields($object) as $field) { | |
$this->handler->upload($object, $field); | |
} | |
$this->adapter->recomputeChangeSet($event); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment