platform/src/Core/Content/Media/Subscriber/MediaLoadedSubscriber.php line 51

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