MediaFile example

static::assertNull($result);
    }

    private function getMetadataLoader(): MetadataLoader
    {
        return $this->getContainer()
            ->get(MetadataLoader::class);
    }

    private function createMediaFile(string $filePath): MediaFile
    {
        return new MediaFile(
            $filePath,
            mime_content_type($filePath),
            pathinfo($filePath, \PATHINFO_EXTENSION),
            filesize($filePath)
        );
    }
}
/** * @throws FileTypeNotAllowedException * @throws MediaException */
    public function upload(UploadedFile $file, string $folder, string $type, Context $context, bool $isPrivate = false): string
    {
        $this->checkValidFile($file);

        $this->validator->validate($file$type);

        $mediaFile = new MediaFile(
            $file->getPathname(),
            $file->getMimeType() ?? '',
            $file->getClientOriginalExtension(),
            $file->getSize() ?: 0
        );

        $mediaId = $this->mediaService->createMediaInFolder($folder$context$isPrivate);

        $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($mediaFile$mediaId): void {
            $this->fileSaver->persistFileToMedia(
                $mediaFile,
                
$this->responseFactory = $this->createMock(ResponseFactoryInterface::class);
    }

    public function testRemoveNonPrintingCharactersInFileNameBeforeUpload(): void
    {
        $invalidFileName = 'fileĀ­name.png';
        $mediaId = Uuid::randomHex();
        $context = Context::createDefaultContext();

        $request = new Request(['fileName' => $invalidFileName]);

        $uploadFile = new MediaFile(
            '/tmp/foo/bar/baz',
            'image/png',
            'png',
            1000,
            Uuid::randomHex()
        );

        $this->mediaService->expects(static::once())
            ->method('fetchFile')
            ->willReturn($uploadFile);

        


        $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);
        $this->mediaRepository->method('search')->willReturn($mediaSearchResult);

        $mediaFile = new MediaFile('foo', 'image/png', 'png', 0);

        $context = Context::createDefaultContext(new AdminApiSource(Uuid::randomHex()));

        static::expectException(MediaException::class);
        static::expectExceptionMessage('A file with the name "foo.png" already exists.');

        $this->fileSaver->persistFileToMedia($mediaFile, 'foo', Uuid::randomHex()$context);
    }

    public static function duplicateFileNameProvider(): \Generator
    {
        
private function getAudioTypeDetector(): AudioTypeDetector
    {
        return $this->getContainer()->get(AudioTypeDetector::class);
    }

    private function createMediaFile(string $filePath): MediaFile
    {
        static::assertIsString($mimeContentType = mime_content_type($filePath));
        static::assertIsInt($filesize = filesize($filePath));

        return new MediaFile(
            $filePath,
            $mimeContentType,
            pathinfo($filePath, \PATHINFO_EXTENSION),
            $filesize
        );
    }
}
$path = $this->themeFileImporter->getRealPath($path);

        if (!$this->themeFileImporter->fileExists($path)) {
            return null;
        }

        $pathinfo = pathinfo($path);

        return [
            'basename' => $pathinfo['filename'],
            'media' => ['id' => $mediaId, 'mediaFolderId' => $themeFolderId],
            'mediaFile' => new MediaFile(
                $path,
                (string) MimeType::fromFilename($pathinfo['basename']),
                $pathinfo['extension'] ?? '',
                (int) filesize($path)
            ),
        ];
    }

    private function getMediaDefaultFolderId(Context $context): ?string
    {
        $criteria = new Criteria();
        
'id' => $mediaId,
                        'title' => "File #{$i}: {$file}",
                        'mediaFolderId' => $isDownloadFile ? $downloadFolderId : $mediaFolderId,
                        'private' => $isDownloadFile,
                        'tags' => $this->getTags($tags),
                    ],
                ],
                $writeContext
            );

            $this->mediaUpdater->persistFileToMedia(
                new MediaFile(
                    $file,
                    (string) mime_content_type($file),
                    pathinfo($file, \PATHINFO_EXTENSION),
                    (int) filesize($file)
                ),
                $this->fileNameProvider->provide(
                    pathinfo($file, \PATHINFO_FILENAME),
                    pathinfo($file, \PATHINFO_EXTENSION),
                    $mediaId,
                    $context->getContext()
                ),
                
\copy(
            __DIR__ . '/../fixtures/animated.gif',
            $publicPath
        );

        static::assertIsString(
            $appUrl = EnvironmentHelper::getVariable('APP_URL')
        );
        $webPath = rtrim($appUrl, '/') . '/animate.gif';

        $type = $this->getImageTypeDetector()->detect(
            new MediaFile(
                $webPath,
                'image/gif',
                'gif',
                1024
            ),
            null
        );

        static::assertInstanceOf(ImageType::class$type);
        static::assertCount(2, $type->getFlags());
        static::assertTrue($type->is(ImageType::TRANSPARENT));
        
$taxRepository = $this->getContainer()->get('tax.repository');
        $taxRepository->upsert([
            ['id' => $taxId, 'name' => 'test', 'taxRate' => 15],
        ], Context::createDefaultContext());

        $tempFile = tempnam(sys_get_temp_dir(), '');
        static::assertIsString($tempFile);
        copy(self::TEST_IMAGE, $tempFile);

        $fileSize = filesize($tempFile);
        static::assertIsInt($fileSize);
        $mediaFile = new MediaFile($tempFile, 'image/png', 'png', $fileSize);

        $mediaId = Uuid::randomHex();
        $context = Context::createDefaultContext();

        $mediaRepository = $this->getContainer()->get('media.repository');
        $mediaRepository->create(
            [
                [
                    'id' => $mediaId,
                ],
            ],
            
$this->fileSaver = $this->getContainer()->get(FileSaver::class);
    }

    public function testPersistFileToMediaHappyPathForInitialUpload(): void
    {
        $tempFile = tempnam(sys_get_temp_dir(), '');
        static::assertIsString($tempFile);
        copy(self::TEST_IMAGE, $tempFile);

        $fileSize = filesize($tempFile);
        static::assertIsInt($fileSize);
        $mediaFile = new MediaFile($tempFile, 'image/png', 'png', $fileSize);

        $mediaId = Uuid::randomHex();

        $context = Context::createDefaultContext();

        $this->mediaRepository->create(
            [
                [
                    'id' => $mediaId,
                ],
            ],
            
private function getTypeDetector(): TypeDetector
    {
        return $this->getContainer()->get(TypeDetector::class);
    }

    private function createMediaFile(string $filePath): MediaFile
    {
        static::assertIsString($mimeContentType = mime_content_type($filePath));
        static::assertIsInt($filesize = filesize($filePath));

        return new MediaFile(
            $filePath,
            $mimeContentType,
            pathinfo($filePath, \PATHINFO_EXTENSION),
            $filesize
        );
    }
}
ProductDefinition::class D ' should not support ' . $entity
                );
            }
        }
    }

    public function testDeserializeProductMedia(): void
    {
        $product = $this->getProduct();

        $mediaService = $this->createMock(MediaService::class);
        $expectedMediaFile = new MediaFile(
            '/tmp/foo/bar/shopware-logo.png',
            'image/png',
            'png',
            1000,
            'bc0d90db4dd806bd671ae9f7fabc5796'
        );
        $mediaService->expects(static::any())
            ->method('fetchFile')
            ->willReturnCallback(function DRequest $request) use ($expectedMediaFile): MediaFile {
                if ($request->get('url') === 'http://172.16.11.80/shopware-logo.png') {
                    return $expectedMediaFile;
                }
try {
            $bytesWritten = $this->copyStreams($inputStream$destStream, 0);
        } finally {
            fclose($inputStream);
            fclose($destStream);
        }

        if ($expectedLength !== $bytesWritten) {
            throw MediaException::invalidContentLength();
        }

        return new MediaFile(
            $fileName,
            (string) mime_content_type($fileName),
            $extension,
            $bytesWritten,
            hash_file('md5', $fileName) ?: null
        );
    }

    public function fetchFileFromURL(Request $request, string $fileName): MediaFile
    {
        if (!$this->enableUrlUploadFeature) {
            
$this->io->progressAdvance($result->count());
            $criteria->setOffset($criteria->getOffset() + $this->batchSize);
        } while ($result->getTotal() > $this->batchSize);
    }

    private function detectMediaType(Context $context, MediaEntity $media): void
    {
        if (!$media->hasFile()) {
            return;
        }

        $file = new MediaFile(
            $media->getUrl(),
            $media->getMimeType() ?? '',
            $media->getFileExtension() ?? '',
            $media->getFileSize() ?? 0
        );

        $type = $this->typeDetector->detect($file);
        $changeSet = ['id' => $media->getId(), 'mediaTypeRaw' => serialize($type)];

        $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($changeSet): void {
            $this->mediaRepository->upsert([$changeSet]$context);
        });
private function getDocumentTypeDetector(): DocumentTypeDetector
    {
        return $this->getContainer()->get(DocumentTypeDetector::class);
    }

    private function createMediaFile(string $filePath): MediaFile
    {
        static::assertIsString($mimeContentType = mime_content_type($filePath));
        static::assertIsInt($filesize = filesize($filePath));

        return new MediaFile(
            $filePath,
            $mimeContentType,
            pathinfo($filePath, \PATHINFO_EXTENSION),
            $filesize
        );
    }
}
Home | Imprint | This part of the site doesn't use cookies.