vendor/shopware/storefront/Theme/Subscriber/UnusedMediaSubscriber.php line 33

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Storefront\Theme\Subscriber;
  3. use Shopware\Core\Content\Media\Event\UnusedMediaSearchEvent;
  4. use Shopware\Core\Framework\Context;
  5. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  7. use Shopware\Core\Framework\Log\Package;
  8. use Shopware\Core\Framework\Uuid\Uuid;
  9. use Shopware\Storefront\Theme\ThemeService;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. /**
  12.  * @internal
  13.  */
  14. #[Package('storefront')]
  15. class UnusedMediaSubscriber implements EventSubscriberInterface
  16. {
  17.     public function __construct(
  18.         private readonly EntityRepository $themeRepository,
  19.         private readonly ThemeService $themeService
  20.     ) {
  21.     }
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         return [
  25.             UnusedMediaSearchEvent::class => 'removeUsedMedia',
  26.         ];
  27.     }
  28.     public function removeUsedMedia(UnusedMediaSearchEvent $event): void
  29.     {
  30.         $context Context::createDefaultContext();
  31.         /** @var array<string> $allThemeIds */
  32.         $allThemeIds $this->themeRepository->searchIds(new Criteria(), $context)->getIds();
  33.         $mediaIds = [];
  34.         foreach ($allThemeIds as $themeId) {
  35.             $config $this->themeService->getThemeConfiguration($themeIdfalse$context);
  36.             foreach ($config['fields'] ?? [] as $data) {
  37.                 if ($data['type'] === 'media' && $data['value'] && Uuid::isValid($data['value'])) {
  38.                     $mediaIds[] = $data['value'];
  39.                 }
  40.             }
  41.         }
  42.         $event->markAsUsed(array_unique($mediaIds));
  43.     }
  44. }