platform/src/Core/Content/ImportExport/DataAbstractionLayer/Serializer/Entity/MediaSerializer.php line 136

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\ImportExport\DataAbstractionLayer\Serializer\Entity;
  3. use Shopware\Core\Content\ImportExport\Exception\InvalidMediaUrlException;
  4. use Shopware\Core\Content\ImportExport\Exception\MediaDownloadException;
  5. use Shopware\Core\Content\ImportExport\Struct\Config;
  6. use Shopware\Core\Content\Media\Aggregate\MediaFolder\MediaFolderEntity;
  7. use Shopware\Core\Content\Media\File\FileSaver;
  8. use Shopware\Core\Content\Media\File\MediaFile;
  9. use Shopware\Core\Content\Media\MediaService;
  10. use Shopware\Core\Framework\Context;
  11. use Shopware\Core\Framework\DataAbstractionLayer\EntityDefinition;
  12. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  15. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  16. use Shopware\Core\Framework\Struct\Struct;
  17. use Shopware\Core\Framework\Uuid\Uuid;
  18. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  19. use Symfony\Component\HttpFoundation\Request;
  20. class MediaSerializer extends EntitySerializer implements EventSubscriberInterface
  21. {
  22.     private FileSaver $fileSaver;
  23.     private MediaService $mediaService;
  24.     private EntityRepositoryInterface $mediaFolderRepository;
  25.     private EntityRepositoryInterface $mediaRepository;
  26.     /**
  27.      * @var array[]
  28.      */
  29.     private array $cacheMediaFiles = [];
  30.     public function __construct(
  31.         MediaService $mediaService,
  32.         FileSaver $fileSaver,
  33.         EntityRepositoryInterface $mediaFolderRepository,
  34.         EntityRepositoryInterface $mediaRepository
  35.     ) {
  36.         $this->mediaService $mediaService;
  37.         $this->fileSaver $fileSaver;
  38.         $this->mediaFolderRepository $mediaFolderRepository;
  39.         $this->mediaRepository $mediaRepository;
  40.     }
  41.     /**
  42.      * @param array|Struct|null $entity
  43.      *
  44.      * @return \Generator
  45.      */
  46.     public function serialize(Config $configEntityDefinition $definition$entity): iterable
  47.     {
  48.         yield from parent::serialize($config$definition$entity);
  49.     }
  50.     /**
  51.      * @param array|\Traversable $entity
  52.      *
  53.      * @return array|\Traversable
  54.      */
  55.     public function deserialize(Config $configEntityDefinition $definition$entity)
  56.     {
  57.         $entity \is_array($entity) ? $entity iterator_to_array($entity);
  58.         $deserialized parent::deserialize($config$definition$entity);
  59.         $deserialized \is_array($deserialized) ? $deserialized iterator_to_array($deserialized);
  60.         $url $entity['url'] ?? null;
  61.         if (empty($url)) {
  62.             return $deserialized;
  63.         }
  64.         if (!filter_var($url\FILTER_VALIDATE_URL)) {
  65.             $deserialized['_error'] = new InvalidMediaUrlException($url);
  66.             return $deserialized;
  67.         }
  68.         $media null;
  69.         if (isset($deserialized['id'])) {
  70.             $media $this->mediaRepository->search(new Criteria([$deserialized['id']]), Context::createDefaultContext())->first();
  71.         }
  72.         $isNew $media === null;
  73.         if ($isNew || $media->getUrl() !== $url) {
  74.             $entityName $config->get('sourceEntity') ?? $definition->getEntityName();
  75.             $deserialized['mediaFolderId'] = $deserialized['mediaFolderId']
  76.                 ?? $this->getMediaFolderId($deserialized['id'] ?? null$entityName);
  77.             $deserialized['id'] = $deserialized['id'] ?? Uuid::randomHex();
  78.             $parsed parse_url($url);
  79.             $pathInfo pathinfo($parsed['path']);
  80.             $media $this->fetchFileFromURL((string) $url$pathInfo['extension'] ?? '');
  81.             if ($media === null) {
  82.                 $deserialized['_error'] = new MediaDownloadException($url);
  83.                 return $deserialized;
  84.             }
  85.             if ($isNew && $media->getHash()) {
  86.                 $deserialized $this->fetchExistingMediaByHash($deserialized$media->getHash());
  87.             }
  88.             $this->cacheMediaFiles[$deserialized['id']] = [
  89.                 'media' => $media,
  90.                 'destination' => $pathInfo['filename'],
  91.             ];
  92.         }
  93.         return $deserialized;
  94.     }
  95.     public function supports(string $entity): bool
  96.     {
  97.         return $entity === 'media';
  98.     }
  99.     public static function getSubscribedEvents()
  100.     {
  101.         return [
  102.             'media.written' => 'persistMedia',
  103.         ];
  104.     }
  105.     /**
  106.      * @internal
  107.      */
  108.     public function persistMedia(EntityWrittenEvent $event): void
  109.     {
  110.         if (empty($this->cacheMediaFiles)) {
  111.             return;
  112.         }
  113.         $mediaFiles $this->cacheMediaFiles;
  114.         // prevent recursion
  115.         $this->cacheMediaFiles = [];
  116.         foreach ($event->getIds() as $id) {
  117.             if (!isset($mediaFiles[$id])) {
  118.                 continue;
  119.             }
  120.             $mediaFile $mediaFiles[$id];
  121.             $this->fileSaver->persistFileToMedia(
  122.                 $mediaFile['media'],
  123.                 $mediaFile['destination'],
  124.                 $id,
  125.                 $event->getContext()
  126.             );
  127.         }
  128.     }
  129.     private function getMediaFolderId(?string $id$entity): string
  130.     {
  131.         if ($id !== null) {
  132.             /** @var MediaFolderEntity|null $folder */
  133.             $folder $this->mediaFolderRepository->search(new Criteria([$id]), Context::createDefaultContext())->first();
  134.             if ($folder !== null) {
  135.                 return $folder->getId();
  136.             }
  137.         }
  138.         $criteria = new Criteria();
  139.         $criteria->addFilter(new EqualsFilter('media_folder.defaultFolder.entity'$entity));
  140.         $criteria->addAssociation('defaultFolder');
  141.         /** @var MediaFolderEntity|null $default */
  142.         $default $this->mediaFolderRepository->search($criteriaContext::createDefaultContext())->first();
  143.         if ($default !== null) {
  144.             return $default->getId();
  145.         }
  146.         $criteria = new Criteria();
  147.         $criteria->addFilter(new EqualsFilter('media_folder.defaultFolder.entity''import_export_profile'));
  148.         $criteria->addAssociation('defaultFolder');
  149.         /** @var MediaFolderEntity|null $fallback */
  150.         $fallback $this->mediaFolderRepository->search($criteriaContext::createDefaultContext())->first();
  151.         if ($fallback === null) {
  152.             throw new \RuntimeException('Failed to find default media folder for import_export_profile');
  153.         }
  154.         return $fallback->getId();
  155.     }
  156.     private function fetchFileFromURL(string $urlstring $extension): ?MediaFile
  157.     {
  158.         $request = new Request();
  159.         $request->query->set('url'$url);
  160.         $request->query->set('extension'$extension);
  161.         $request->request->set('url'$url);
  162.         $request->request->set('extension'$extension);
  163.         $request->headers->set('content-type''application/json');
  164.         try {
  165.             $file $this->mediaService->fetchFile($request);
  166.             if ($file !== null && $file->getFileSize() > 0) {
  167.                 return $file;
  168.             }
  169.         } catch (\Throwable $throwable) {
  170.         }
  171.         return null;
  172.     }
  173.     private function fetchExistingMediaByHash(array $deserializedstring $hash): array
  174.     {
  175.         $criteria = new Criteria();
  176.         $criteria->addFilter(new EqualsFilter('metaData.hash'$hash));
  177.         $media $this->mediaRepository->search($criteriaContext::createDefaultContext())->first();
  178.         if ($media) {
  179.             $deserialized['id'] = $media->getId();
  180.         }
  181.         return $deserialized;
  182.     }
  183. }