vendor/store.shopware.com/swagmigrationassistant/Migration/Subscriber/MediaDeletedSubscriber.php line 43

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. /*
  3.  * (c) shopware AG <info@shopware.com>
  4.  * For the full copyright and license information, please view the LICENSE
  5.  * file that was distributed with this source code.
  6.  */
  7. namespace SwagMigrationAssistant\Migration\Subscriber;
  8. use Shopware\Core\Content\Media\MediaDefinition;
  9. use Shopware\Core\Content\Media\MediaEvents;
  10. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityDeletedEvent;
  12. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
  14. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  15. class MediaDeletedSubscriber implements EventSubscriberInterface
  16. {
  17.     /**
  18.      * @var EntityRepositoryInterface
  19.      */
  20.     private $mediaFileRepository;
  21.     public function __construct(EntityRepositoryInterface $mediaFileRepository)
  22.     {
  23.         $this->mediaFileRepository $mediaFileRepository;
  24.     }
  25.     /**
  26.      * Due to the order in which media file entries get written, which
  27.      * is before the related media is written, we cannot use a foreign
  28.      * key constraint for deletion and need to delete the media file entries
  29.      * manually.
  30.      */
  31.     public static function getSubscribedEvents(): array
  32.     {
  33.         return [
  34.             MediaEvents::MEDIA_DELETED_EVENT => 'onMediaDelete',
  35.         ];
  36.     }
  37.     public function onMediaDelete(EntityDeletedEvent $event): void
  38.     {
  39.         if ($event->getEntityName() !== MediaDefinition::ENTITY_NAME) {
  40.             return;
  41.         }
  42.         $context $event->getContext();
  43.         $deletedMediaIds $event->getIds();
  44.         $criteria = new Criteria();
  45.         $criteria->addFilter(new EqualsAnyFilter('mediaId'$deletedMediaIds));
  46.         $result $this->mediaFileRepository->searchIds($criteria$context);
  47.         $mediaFileIds $result->getIds();
  48.         if (empty($mediaFileIds)) {
  49.             return;
  50.         }
  51.         $mediaFileDeletions = [];
  52.         foreach ($mediaFileIds as $mediaFileId) {
  53.             $mediaFileDeletions[] = [
  54.                 'id' => $mediaFileId,
  55.             ];
  56.         }
  57.         $this->mediaFileRepository->delete($mediaFileDeletions$context);
  58.     }
  59. }