getMedia example


    public function buildAttachments(
        Context $context,
        MailTemplateEntity $mailTemplate,
        MailSendSubscriberConfig $extensions,
        array $eventConfig,
        ?string $orderId
    ): array {
        $attachments = [];

        foreach ($mailTemplate->getMedia() ?? [] as $mailTemplateMedia) {
            if ($mailTemplateMedia->getMedia() === null || $mailTemplateMedia->getLanguageId() !== $context->getLanguageId()) {
                continue;
            }

            $attachments[] = $this->mediaService->getAttachment(
                $mailTemplateMedia->getMedia(),
                $context
            );
        }

        $documentIds = $extensions->getDocumentIds();

        
$payload['appPaymentMethod']['appId'] = $appId;
            $payload['appPaymentMethod']['appName'] = $manifest->getMetadata()->getName();
            $payload['appPaymentMethod']['originalMediaId'] = $this->getMediaId($manifest$paymentMethod$context$existingAppPaymentMethod);

            if ($existing && $existingAppPaymentMethod) {
                $existingPaymentMethods->remove($existing->getId());

                $payload['id'] = $existing->getId();
                $payload['appPaymentMethod']['id'] = $existingAppPaymentMethod->getId();

                $media = $existing->getMedia();
                $originalMedia = $existingAppPaymentMethod->getOriginalMedia();
                if (($media === null && $originalMedia === null)
                    || ($media !== null && $originalMedia !== null && $originalMedia->getId() === $media->getId())
                ) {
                    // user has not overwritten media, set new                     $payload['mediaId'] = $payload['appPaymentMethod']['originalMediaId'];
                }
            } else {
                $payload['afterOrderEnabled'] = true;
                $payload['mediaId'] = $payload['appPaymentMethod']['originalMediaId'];
            }

            
            if (!empty($selection)) {
                $this->additionalTextService->buildAdditionalText($product$this->contextService->getShopContext());
                $data['additionaltext'] = $product->getAdditional();
            }

            if ($this->config->get('forceArticleMainImageInListing')
                && $configurator->getType() !== ConfiguratorService::CONFIGURATOR_TYPE_STANDARD
                && empty($selection)
            ) {
                $data['image'] = $this->legacyStructConverter->convertMediaStruct($product->getCover());
                $data['images'] = [];
                foreach ($product->getMedia() as $image) {
                    if ($image->getId() !== $product->getCover()->getId()) {
                        $data['images'][] = $this->legacyStructConverter->convertMediaStruct($image);
                    }
                }
            }
        }

        $data = array_merge($data$this->getLinksOfProduct($product$categoryId, !empty($selection)));

        $data['articleName'] = $this->sOptimizeText($data['articleName']);
        $data['description_long'] = htmlspecialchars_decode($data['description_long']);

        
$serializer = new ProductSerializer(
            $this->visibilityRepository,
            $this->salesChannelRepository,
            $this->productMediaRepository,
            $this->productConfiguratorSettingRepository
        );
        $serializer->setRegistry($serializerRegistry);

        $result = $serializer->deserialize(new Config([][][])$productDefinition$record);
        $result = \is_array($result) ? $result : iterator_to_array($result);

        static::assertEquals($product->getMedia()->first()->getId()$result['media'][0]['id']);
        static::assertEquals($product->getMedia()->first()->getMedia()->getId()$result['media'][0]['media']['id']);
        static::assertArrayNotHasKey('url', $result['media'][0]['media']);

        static::assertArrayNotHasKey('id', $result['media'][1]);
    }

    public function testDeserializeProductMediaWithInvalidUrl(): void
    {
        $record = [
            'media' => 'foo',
        ];

        
$slot->setUniqueIdentifier('id');
        $slot->setType('image');
        $slot->setConfig([]);
        $slot->setFieldConfig(new FieldConfigCollection());

        $this->imageResolver->enrich($slot$resolverContext$result);

        /** @var ImageStruct|null $imageStruct */
        $imageStruct = $slot->getData();
        static::assertInstanceOf(ImageStruct::class$imageStruct);
        static::assertEmpty($imageStruct->getUrl());
        static::assertEmpty($imageStruct->getMedia());
        static::assertEmpty($imageStruct->getMediaId());
    }

    public function testEnrichWithUrlOnly(): void
    {
        $resolverContext = new ResolverContext($this->createMock(SalesChannelContext::class)new Request());
        $result = new ElementDataCollection();

        $fieldConfig = new FieldConfigCollection();
        $fieldConfig->add(new FieldConfig('url', FieldConfig::SOURCE_STATIC, 'http://shopware.com/image.jpg'));

        

    public function downloadAction()
    {
        Shopware()->Front()->Plugins()->ViewRenderer()->setNoRender();
        $this->Front()->Plugins()->Json()->setRenderer(false);

        $mediaId = $this->Request()->getParam('mediaId');
        $media = $this->getMedia($mediaId)->getQuery()->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY);

        if (!$media) {
            echo self::FILE_NOT_FOUND_MESSAGE;

            return;
        }

        $file = $media['path'];
        $tmpFileName = sprintf('%s.%s', $media['name']$media['extension']);
        $mediaService = $this->get(MediaServiceInterface::class);

        @
$childrenCount = $childrenCounts[$category->getId()];
        }

        $url = $category->isBlog() ? $this->blogBaseUrl : $this->baseUrl;

        $attribute = [];
        foreach ($category->getAttributes() as $struct) {
            $attribute = array_merge($attribute$struct->toArray());
        }

        $media = [];
        if ($category->getMedia()) {
            $media = [
                'id' => $category->getMedia()->getId(),
                'name' => $category->getMedia()->getName(),
                'description' => $category->getMedia()->getDescription(),
                'path' => $category->getMedia()->getFile(),
                'type' => $category->getMedia()->getType(),
                'extension' => $category->getMedia()->getExtension(),
            ];
        }

        $path = $category->getPath() ? '|' . implode('|', $category->getPath()) . '|' : '';

        
$progress = $this->import($context, ProductDefinition::ENTITY_NAME, '/fixtures/products_with_updated_cover.csv', 'products.csv');

        static::assertSame(Progress::STATE_SUCCEEDED, $progress->getState());

        /** @var ProductEntity $product */
        $product = $this->productRepository->search(
            (new Criteria(['e5c8b8f701034e8dbea72ac0fc32521e']))->addAssociation('media'),
            Context::createDefaultContext()
        )->first();

        static::assertInstanceOf(ProductMediaCollection::class$product->getMedia());
        static::assertCount(1, $product->getMedia());
    }

    /** * @group slow */
    public function testProductsWithVariantsCsv(): void
    {
        $connection = $this->getContainer()->get(Connection::class);
        $connection->executeStatement('DELETE FROM `product`');

        
return $this->fmap(fn (MailTemplateMediaEntity $mailTemplateMedia) => $mailTemplateMedia->getMediaId());
    }

    public function filterByMediaId(string $id): self
    {
        return $this->filter(fn (MailTemplateMediaEntity $mailTemplateMedia) => $mailTemplateMedia->getMediaId() === $id);
    }

    public function getMedia(): MediaCollection
    {
        return new MediaCollection(
            $this->fmap(fn (MailTemplateMediaEntity $mailTemplateMedia) => $mailTemplateMedia->getMedia())
        );
    }

    public function getApiAlias(): string
    {
        return 'mail_template_media_collection';
    }

    protected function getExpectedClass(): string
    {
        return MailTemplateMediaEntity::class;
    }

        return $this->media;
    }

    /** * Returns the creation date of the media. * * @return DateTimeInterface|null */
    public function getCreated()
    {
        if (!$this->getMedia() instanceof \Shopware\Models\Media\Media) {
            return null;
        }

        return $this->getMedia()->getCreated();
    }

    /** * Returns the id of the user, who uploaded the file. * * @return int|null */
    
$slot->setFieldConfig($fieldConfig);

        $this->imageSliderResolver->enrich($slot$resolverContext$result);

        $imageSliderStruct = $slot->getData();
        static::assertInstanceOf(ImageSliderStruct::class$imageSliderStruct);

        $sliderItems = $imageSliderStruct->getSliderItems();
        static::assertIsArray($sliderItems);

        $expectedSliderIds = ['media0', 'media1', 'media2', 'media3', 'media4'];
        $imageSliderIds = array_map(fn ($value) => $value->getMedia()?->getId() ?? '', $sliderItems);

        static::assertEquals($expectedSliderIds$imageSliderIds);
    }

    public function testEnrichWithStaticConfig(): void
    {
        $media = new MediaEntity();
        $media->setId('media123');

        $resolverContext = new ResolverContext($this->createMock(SalesChannelContext::class)new Request());
        $result = new ElementDataCollection();
        
return $this->eventManager->filter('Legacy_Struct_Converter_Convert_Configurator_Group', $data[
            'configurator_group' => $group,
        ]);
    }

    /** * @return array */
    public function convertCategoryStruct(Category $category)
    {
        $media = null;
        if ($category->getMedia()) {
            $media = $this->convertMediaStruct($category->getMedia());
        }

        $attribute = [];
        if ($category->hasAttribute('core')) {
            $attribute = $category->getAttribute('core')->toArray();
        }

        $productStream = null;
        if ($category->getProductStream()) {
            $productStream = $this->convertRelatedProductStreamStruct($category->getProductStream());
        }
$productEntity = $resolverContext->getEntity();

                if ($productEntity->getCover()) {
                    /** @var ProductMediaCollection $sliderItems */
                    $sliderItems = new ProductMediaCollection(array_merge(
                        [$productEntity->getCoverId() => $productEntity->getCover()],
                        $sliderItems->getElements()
                    ));
                }
            }

            foreach ($sliderItems->getMedia() as $media) {
                $imageSliderItem = new ImageSliderItemStruct();
                $imageSliderItem->setMedia($media);
                $imageSlider->addSliderItem($imageSliderItem);
            }
        }
    }

    protected function sortItemsByPosition(ProductMediaCollection $sliderItems): void
    {
        if (!$sliderItems->first() || !$sliderItems->first()->has('position')) {
            return;
        }
foreach ($groups as $group) {
            $items = [];
            $useMedia = false;
            $isActive = false;

            foreach ($group->getOptions() as $option) {
                $listItem = new MediaListItem(
                    $option->getId(),
                    $option->getName(),
                    \in_array($option->getId()$actives, true),
                    $option->getMedia(),
                    $option->getAttributes()
                );

                $isActive = $isActive || $listItem->isActive();
                $useMedia = $useMedia || $listItem->getMedia() !== null;

                $items[] = $listItem;
            }

            if ($useMedia) {
                $results[] = new MediaListFacetResult(
                    
$useMedia = false;
                $isActive = false;

                foreach ($group->getOptions() as $option) {
                    $listItem = new MediaListItem(
                        $option->getId(),
                        $option->getName(),
                        \in_array(
                            $option->getId(),
                            $actives
                        ),
                        $option->getMedia(),
                        $option->getAttributes()
                    );

                    $isActive = $isActive || $listItem->isActive();
                    $useMedia = $useMedia || $listItem->getMedia() !== null;

                    $items[] = $listItem;
                }

                if ($useMedia) {
                    $results[] = new MediaListFacetResult(
                        
Home | Imprint | This part of the site doesn't use cookies.