getFilename(); $mimeType = $tempFileObject->getMimeType() ?? $mimeType; $extension = collect((new MimeTypes())->getExtensions($mimeType))->first(); if (!FacadesFile::put(\storage_path("tmp/$filePath.$extension"), $blob)) { new \ErrorException('Could not write on temp file'); } // Close this file after response is sent. // Closing the file will cause to remove it from temp director! app()->terminating(function () use ($tempFile) { fclose($tempFile); }); return new SplFileInfo(\storage_path("tmp/$filePath.$extension")); } /** * Generate from blob * * @param string $fileName * @param string $extension * @param string $base64String * @return SplFileInfo * @throws \ErrorException If writing to temp file failed. * @throws \App\Exceptions\CafelApiImageFetchException If invalid image was given or ext could not be confirmed. */ public static function fromBase64(string $fileName, string $extension, string $base64String): SplFileInfo { // * Create temp file and get its absolute path if (!($tempFile = tmpfile())) { new \ErrorException('Could not create temp file'); } $tempFilePath = stream_get_meta_data($tempFile)['uri']; if (!($blob = \base64_decode($base64String, true))) { throw new CafelApiImageFetchException("Invalid base64 string given for image '$fileName'"); } // * Save file data in file if (!(file_put_contents($tempFilePath, $blob))) { throw new \ErrorException('Could not write on temp file'); } $tempFileObject = new File($tempFilePath); $filePath = $fileName ?? $tempFileObject->getFilename(); $mimeType = $tempFileObject->getMimeType(); $guessedExt = $mimeType ? collect((new MimeTypes())->getExtensions($mimeType))->first() : $extension; // * Ignore jpeg that is guessed as jpg if ($guessedExt !== $extension and !($extension === 'jpeg' && $guessedExt === 'jpg')) { throw new CafelApiImageFetchException( "Given extension '$extension' could not be confirmed, found '$guessedExt' for image '$fileName'" ); } if (!FacadesFile::put(\storage_path("tmp/$filePath.$extension"), $blob)) { throw new \ErrorException('Could not write on temp file'); } // Close this file after response is sent. // Closing the file will cause to remove it from temp director! app()->terminating(function () use ($tempFile) { fclose($tempFile); }); return new SplFileInfo(\storage_path("tmp/$filePath.$extension")); } }