src/Core/Content/Media/Subscriber/MediaLoadedSubscriber.php line 53

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\Media\Subscriber;
  3. use Shopware\Core\Content\Media\Aggregate\MediaThumbnail\MediaThumbnailCollection;
  4. use Shopware\Core\Content\Media\Aggregate\MediaThumbnail\MediaThumbnailEntity;
  5. use Shopware\Core\Content\Media\MediaEntity;
  6. use Shopware\Core\Content\Media\MediaEvents;
  7. use Shopware\Core\Content\Media\Pathname\UrlGeneratorInterface;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
  9. use Shopware\Core\Framework\Log\Package;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. /**
  12.  * @internal
  13.  */
  14. #[Package('content')]
  15. class MediaLoadedSubscriber implements EventSubscriberInterface
  16. {
  17.     /**
  18.      * @internal
  19.      */
  20.     public function __construct(private readonly UrlGeneratorInterface $urlGenerator)
  21.     {
  22.     }
  23.     public static function getSubscribedEvents(): array
  24.     {
  25.         return [
  26.             MediaEvents::MEDIA_LOADED_EVENT => [
  27.                 ['unserialize'10],
  28.                 ['addUrls'],
  29.             ],
  30.         ];
  31.     }
  32.     public function addUrls(EntityLoadedEvent $event): void
  33.     {
  34.         /** @var MediaEntity $media */
  35.         foreach ($event->getEntities() as $media) {
  36.             if (!$media->hasFile() || $media->isPrivate()) {
  37.                 continue;
  38.             }
  39.             $media->setUrl($this->urlGenerator->getAbsoluteMediaUrl($media));
  40.             foreach ($media->getThumbnails() ?? [] as $thumbnail) {
  41.                 $this->addThumbnailUrl($thumbnail$media);
  42.             }
  43.         }
  44.     }
  45.     public function unserialize(EntityLoadedEvent $event): void
  46.     {
  47.         /** @var MediaEntity $media */
  48.         foreach ($event->getEntities() as $media) {
  49.             if ($media->getMediaTypeRaw()) {
  50.                 $media->setMediaType(unserialize($media->getMediaTypeRaw()));
  51.             }
  52.             if ($media->getThumbnails() === null) {
  53.                 if ($media->getThumbnailsRo()) {
  54.                     $media->setThumbnails(unserialize($media->getThumbnailsRo()));
  55.                 } else {
  56.                     $media->setThumbnails(new MediaThumbnailCollection());
  57.                 }
  58.             }
  59.         }
  60.     }
  61.     private function addThumbnailUrl(MediaThumbnailEntity $thumbnailMediaEntity $media): void
  62.     {
  63.         $thumbnail->setUrl(
  64.             $this->urlGenerator->getAbsoluteThumbnailUrl(
  65.                 $media,
  66.                 $thumbnail
  67.             )
  68.         );
  69.     }
  70. }