*/ class PostEventSubscriber extends EntityManagerEventSubscriber { protected Filesystem $filesystem; protected PostRepositoryQuery $query; public function __construct(Filesystem $filesystem, PostRepositoryQuery $query) { $this->filesystem = $filesystem; $this->query = $query; } public function support(EntityInterface $entity) { return $entity instanceof Post; } public function onUpdate(EntityManagerEvent $event) { if (!$this->support($event->getEntity())) { return; } $this->removeOrphanUploads(); } public function onDelete(EntityManagerEvent $event) { if (!$this->support($event->getEntity())) { return; } $this->removeOrphanUploads(); } protected function removeOrphanUploads() { $finder = new Finder(); $finder->files()->in('uploads/post'); foreach ($finder as $file) { $image = str_replace('uploads/', '', $file->getPathname()); $post = $this->query->create() ->where('.image = :image') ->setParameter(':image', $image) ->findOne() ; if (null === $post) { $this->filesystem->remove($file->getRealPath()); } } } }