MediaCollection example

$entities = array_map(static function Dstring $id): MediaEntity {
            $media = new MediaEntity();
            $media->setId($id);

            return $media;
        }$extension->getMediaIds());

        $this->mediaRepository
            ->expects(static::once())
            ->method('search')
            ->with($criteria$context)
            ->willReturn(new EntitySearchResult('media', 2, new MediaCollection($entities), null, $criteria$context));

        $this->mediaService
            ->expects(static::exactly(2))
            ->method('getAttachment')
            ->willReturnOnConsecutiveCalls(
                [
                    'content' => '',
                    'fileName' => '',
                    'mimeType' => 'application/pdf',
                    'id' => $idE,
                ],
                [
/** * @internal */
class TestCollectionWithToOneRelationship extends SerializationFixture
{
    /** * @return MediaCollection|MediaEntity */
    public function getInput(): EntityCollection|Entity
    {
        $mediaCollection = new MediaCollection();
        $userId = '6f51622eb3814c75ae0263cece27ce72';

        $user = new UserEntity();
        $user->setId($userId);
        $user->setFirstName('Manufacturer');
        $user->setLastName('');
        $user->setPassword('password');
        $user->setUsername('user1');
        $user->setActive(true);
        $user->setAdmin(true);
        $user->setEmail('user1@shop.de');
        

        return $this->fmap(fn (ProductMediaEntity $productMedia) => $productMedia->getMediaId());
    }

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

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

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

    protected function getExpectedClass(): string
    {
        

        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
    {
        
'title' => 'Logo',
                'alt' => 'Logo description',
            ],
        ];

        $mediaService->expects(static::never())
            ->method('fetchFile');

        $fileSaver->expects(static::never())
            ->method('persistFileToMedia');

        $searchResult = new EntitySearchResult('media', 1, new MediaCollection([$mediaEntity]), null, new Criteria()$context);
        $mediaRepository->method('search')->willReturn($searchResult);

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

        static::assertArrayNotHasKey('url', $result);

        $expected = $record;
        unset($expected['url']);

        // other properties are written
public function getFunctions(): array
    {
        return [
            new TwigFunction('searchMedia', $this->searchMedia(...)),
        ];
    }

    public function searchMedia(array $ids, Context $context): MediaCollection
    {
        if (empty($ids)) {
            return new MediaCollection();
        }

        $criteria = new Criteria($ids);

        /** @var MediaCollection $media */
        $media = $this->mediaRepository
            ->search($criteria$context)
            ->getEntities();

        return $media;
    }
}
if (!\array_key_exists('fields', $config)) {
            return [];
        }

        foreach ($config['fields'] as $key => $data) {
            if ($data['type'] === 'media' && $data['value'] && Uuid::isValid($data['value'])) {
                $mediaItems[$data['value']][] = $key;
            }
            $resolvedConfig[$key] = $data['value'];
        }

        $result = new MediaCollection();

        /** @var array<string> $mediaIds */
        $mediaIds = array_keys($mediaItems);
        if (!empty($mediaIds)) {
            $criteria = new Criteria($mediaIds);
            $criteria->setTitle('theme-service::resolve-media');
            $result = $this->repository->search($criteria$context->getContext());
        }

        foreach ($result as $media) {
            if (!\array_key_exists($media->getId()$mediaItems)) {
                
$media = $this->mediaRepository->search($criteria$this->context)->get($media->getId());
        static::assertInstanceOf(MediaEntity::class$media);

        $resource = fopen(__DIR__ . '/../fixtures/shopware-logo.png', 'rb');
        \assert($resource !== false);

        $this->getPublicFilesystem()->writeStream(
            $this->urlGenerator->getRelativeMediaUrl($media),
            $resource
        );

        $this->thumbnailService->generate(new MediaCollection([$media])$this->context);

        $criteria = new Criteria([$media->getId()]);
        $criteria->addAssociation('thumbnails');

        $media = $this->mediaRepository
            ->search($criteria$this->context)
            ->get($media->getId());

        static::assertInstanceOf(MediaEntity::class$media);

        $thumbnails = $media->getThumbnails();

        
$media = new MediaEntity();
        $media->setId('548faa1f7846436c85944f4aea792d96');
        $media->setUserId($userId);
        $media->setMimeType('image/jpg');
        $media->setFileExtension('jpg');
        $media->setFileSize(93889);
        $media->setTitle('2');
        $media->setCreatedAt(new \DateTime('2012-08-31T00:00:00.000+00:00'));
        $media->setUpdatedAt(new \DateTime('2017-11-21T11:25:34.000+00:00'));
        $media->setUser(clone $user);
        $media->internalSetEntityData('media', new FieldVisibility([]));
        $mediaCollection = new MediaCollection([$media]);
        $user->setMedia($mediaCollection);

        return $user;
    }

    /** * @return array<string, mixed> */
    protected function getJsonApiFixtures(string $baseUrl): array
    {
        return [
            
public function testEnrichWithMediaOnly(): void
    {
        $resolverContext = new ResolverContext($this->createMock(SalesChannelContext::class)new Request());

        $media = new MediaEntity();
        $media->setUniqueIdentifier('media123');

        $mediaSearchResult = new EntitySearchResult(
            'media',
            1,
            new MediaCollection([$media]),
            null,
            new Criteria(),
            Context::createDefaultContext()
        );

        $result = new ElementDataCollection();
        $result->add('media_id', $mediaSearchResult);

        $fieldConfig = new FieldConfigCollection();
        $fieldConfig->add(new FieldConfig('media', FieldConfig::SOURCE_STATIC, 'media123'));

        

                function DCriteria $criteria, Context $context) use ($id1$id2) {
                    $filters = $criteria->getFilters();

                    self::assertCount(0, $filters);

                    return [$id1$id2];
                },
                function DCriteria $criteria, Context $context) use ($id1$id2$media1$media2) {
                    static::assertSame([$id1$id2]$criteria->getIds());

                    return new MediaCollection([$media1$media2]);
                },
                function D) {
                    return [];
                },
            ],
            $mediaDefinition
        );

        $purger = new UnusedMediaPurger($reponew EventDispatcher());
        $media = array_merge([], ...iterator_to_array($purger->getNotUsedMedia()));

        
use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;
use Shopware\Core\Framework\DataAbstractionLayer\FieldVisibility;
use Shopware\Core\System\User\UserEntity;

/** * @internal */
class TestMainResourceShouldNotBeInIncluded extends SerializationFixture
{
    public function getInput(): EntityCollection|Entity
    {
        $mediaCollection = new MediaCollection();
        $userId = 'f343a3c119cf42a7841aa0ac5094908c';

        $user = new UserEntity();
        $user->setId($userId);
        $user->setFirstName('Manufacturer');
        $user->setLastName('');
        $user->setPassword('password');
        $user->setUsername('user1');
        $user->setActive(true);
        $user->setAdmin(true);
        $user->setEmail('user1@shop.de');
        
public function testEnrichWithStaticConfig(): void
    {
        $media = new MediaEntity();
        $media->setId('media123');

        $resolverContext = new ResolverContext($this->createMock(SalesChannelContext::class)new Request());
        $result = new ElementDataCollection();
        $result->add('media_id', new EntitySearchResult(
            'media',
            1,
            new MediaCollection([$media]),
            null,
            new Criteria(),
            $resolverContext->getSalesChannelContext()->getContext()
        ));

        $medias = [
            ['mediaId' => 'media123'],
        ];

        $fieldConfig = new FieldConfigCollection();
        $fieldConfig->add(new FieldConfig('sliderItems', FieldConfig::SOURCE_STATIC, $medias));

        
public function testRenameMediaMakesRollbackOnFailure(): void
    {
        $png = $this->getPng();

        $this->expectException(MediaException::class);
        $this->expectExceptionMessage(MediaException::couldNotRenameFile($png->getId()(string) $png->getFileName())->getMessage());

        $context = Context::createDefaultContext();
        $this->setFixtureContext($context);

        $collection = new MediaCollection([$png]);
        $searchResult = new EntitySearchResult('temp', 1, $collection, null, new Criteria()$context);

        $repositoryMock = $this->createMock(EntityRepository::class);
        $repositoryMock->expects(static::exactly(2))
            ->method('search')
            ->willReturn($searchResult);

        $repositoryMock->expects(static::once())
            ->method('update')
            ->willThrowException(new \Exception());

        
$mediaA->setId(Uuid::randomHex());
        $mediaA->setMimeType('image/png');
        $mediaA->setFileName('foo');
        $mediaA->setFileExtension('png');
        $mediaA->setPrivate(true);

        $mediaB = clone $mediaA;
        $mediaB->setId(Uuid::randomHex());
        $mediaB->setPrivate(false);

        if ($isPrivate) {
            $mediaWithRelatedFileName = new MediaCollection([$mediaA]);
        } else {
            $mediaWithRelatedFileName = new MediaCollection([$mediaB]);
        }

        $currentMedia = new MediaEntity();
        $currentMedia->setId(Uuid::randomHex());
        $currentMedia->setPrivate($isPrivate);

        $mediaSearchResult = $this->createMock(EntitySearchResult::class);
        $mediaSearchResult->method('get')->willReturn($currentMedia);
        $mediaSearchResult->method('getEntities')->willReturn($mediaWithRelatedFileName);
        
Home | Imprint | This part of the site doesn't use cookies.