2021-03-17 15:57:07 +01:00
|
|
|
<?php
|
|
|
|
|
2021-03-18 17:08:41 +01:00
|
|
|
namespace App\EventSuscriber\Blog;
|
2021-03-17 15:57:07 +01:00
|
|
|
|
2021-03-17 15:57:20 +01:00
|
|
|
use App\Entity\Blog\Post;
|
2021-03-20 13:41:15 +01:00
|
|
|
use App\Core\Entity\EntityInterface;
|
|
|
|
use App\Core\Event\EntityManager\EntityManagerEvent;
|
|
|
|
use App\Core\EventSuscriber\EntityManagerEventSubscriber;
|
2021-03-17 15:57:20 +01:00
|
|
|
use App\Repository\Blog\PostRepositoryQuery;
|
2021-03-17 15:57:07 +01:00
|
|
|
use Symfony\Component\Filesystem\Filesystem;
|
|
|
|
use Symfony\Component\Finder\Finder;
|
|
|
|
|
|
|
|
/**
|
2021-03-18 17:08:41 +01:00
|
|
|
* class PostEventSubscriber.
|
2021-03-17 15:57:07 +01:00
|
|
|
*
|
|
|
|
* @author Simon Vieille <simon@deblan.fr>
|
|
|
|
*/
|
2021-03-18 17:08:41 +01:00
|
|
|
class PostEventSubscriber extends EntityManagerEventSubscriber
|
2021-03-17 15:57:07 +01:00
|
|
|
{
|
|
|
|
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)
|
2021-03-17 15:57:20 +01:00
|
|
|
->findOne()
|
|
|
|
;
|
2021-03-17 15:57:07 +01:00
|
|
|
|
|
|
|
if (null === $post) {
|
|
|
|
$this->filesystem->remove($file->getRealPath());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|