vendor/shopware/platform/src/Core/Content/Media/Subscriber/MediaLoadedSubscriber.php line 32

Open in your IDE?
  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 Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. class MediaLoadedSubscriber implements EventSubscriberInterface
  11. {
  12.     private UrlGeneratorInterface $urlGenerator;
  13.     public function __construct(UrlGeneratorInterface $urlGenerator)
  14.     {
  15.         $this->urlGenerator $urlGenerator;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             MediaEvents::MEDIA_LOADED_EVENT => [
  21.                 ['unserialize'10],
  22.                 ['addUrls'],
  23.             ],
  24.         ];
  25.     }
  26.     public function addUrls(EntityLoadedEvent $event): void
  27.     {
  28.         /** @var MediaEntity $media */
  29.         foreach ($event->getEntities() as $media) {
  30.             if (!$media->hasFile() || $media->isPrivate()) {
  31.                 continue;
  32.             }
  33.             $media->setUrl($this->urlGenerator->getAbsoluteMediaUrl($media));
  34.             foreach ($media->getThumbnails() as $thumbnail) {
  35.                 $this->addThumbnailUrl($thumbnail$media);
  36.             }
  37.         }
  38.     }
  39.     public function unserialize(EntityLoadedEvent $event): void
  40.     {
  41.         /** @var MediaEntity $media */
  42.         foreach ($event->getEntities() as $media) {
  43.             if ($media->getMediaTypeRaw()) {
  44.                 $media->setMediaType(unserialize($media->getMediaTypeRaw()));
  45.             }
  46.             if ($media->getThumbnails() === null) {
  47.                 if ($media->getThumbnailsRo()) {
  48.                     $media->setThumbnails(unserialize($media->getThumbnailsRo()));
  49.                 } else {
  50.                     $media->setThumbnails(new MediaThumbnailCollection());
  51.                 }
  52.             }
  53.         }
  54.     }
  55.     private function addThumbnailUrl(MediaThumbnailEntity $thumbnailMediaEntity $media): void
  56.     {
  57.         $thumbnail->setUrl(
  58.             $this->urlGenerator->getAbsoluteThumbnailUrl(
  59.                 $media,
  60.                 $thumbnail
  61.             )
  62.         );
  63.     }
  64. }