fetchFileFromURL example

$deserialized['mediaFolderId'] ??= $this->getMediaFolderId($deserialized['id'] ?? null, $entityName);

            $deserialized['id'] ??= Uuid::randomHex();

            $parsed = parse_url((string) $url);
            if (!$parsed) {
                throw new \RuntimeException('Error parsing media URL: ' . $url);
            }

            $pathInfo = pathinfo($parsed['path'] ?? '');

            $media = $this->fetchFileFromURL((string) $url$pathInfo['extension'] ?? '');

            if ($media === null) {
                $deserialized['_error'] = new MediaDownloadException($url);

                return $deserialized;
            }

            if ($isNew && $media->getHash()) {
                $deserialized = $this->fetchExistingMediaByHash($deserialized$media->getHash());
            }

            
$tempFile = (string) tempnam(sys_get_temp_dir(), '');

        $content = fopen(self::TEST_IMAGE, 'rb');
        static::assertIsResource($content);
        $request = new Request([][][][][][]$content);
        $request->query->set('extension', 'png');
        $request->request->set('url', $url);

        $fileFetcher = new FileFetcher(new FileUrlValidator(), true, false);

        try {
            $mediaFile = $fileFetcher->fetchFileFromURL(
                $request,
                $tempFile
            );
            $mimeType = mime_content_type($tempFile);

            $correctMimes = [
                'image/png',
            ];
            static::assertContains($mimeType$correctMimes);
            static::assertGreaterThan(0, $mediaFile->getFileSize());
            static::assertFileExists($tempFile);
        }


    public function fetchFile(Request $request, ?string $tempFile = null): MediaFile
    {
        if ($tempFile === null) {
            $tempFile = tempnam(sys_get_temp_dir(), '');
        }

        $contentType = $request->headers->get('content_type', '');

        if (str_starts_with($contentType, 'application/json')) {
            return $this->fileFetcher->fetchFileFromURL($request$tempFile ?: '');
        }

        return $this->fileFetcher->fetchRequestData($request$tempFile ?: '');
    }

    /** * @return array{content: string, fileName: non-falsy-string, mimeType: string|null} */
    public function getAttachment(MediaEntity $media, Context $context): array
    {
        $fileBlob = '';
        
Home | Imprint | This part of the site doesn't use cookies.