From a67de99b49eceea7a3f29a88aa9c1f1ed6beda91 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 2 Jul 2024 18:35:10 +1000 Subject: [PATCH] Fixes for task assigned user --- app/Utils/TempFile.php | 59 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/app/Utils/TempFile.php b/app/Utils/TempFile.php index 5f8409555f66..16b1dc1a932a 100644 --- a/app/Utils/TempFile.php +++ b/app/Utils/TempFile.php @@ -11,6 +11,8 @@ namespace App\Utils; +use Illuminate\Http\File; +use Illuminate\Http\UploadedFile; class TempFile { public static function path($url): string @@ -34,4 +36,61 @@ class TempFile return $file_path; } + + public static function UploadedFileFromRaw(string $fileData, string|null $fileName = null, string|null $mimeType = null): UploadedFile + { + // Create temp file and get its absolute path + $tempFile = tmpfile(); + $tempFilePath = stream_get_meta_data($tempFile)['uri']; + + // Save file data in file + file_put_contents($tempFilePath, $fileData); + + $tempFileObject = new File($tempFilePath); + $file = new UploadedFile( + $tempFileObject->getPathname(), + $fileName ?: $tempFileObject->getFilename(), + $mimeType ?: $tempFileObject->getMimeType(), + 0, + true // Mark it as test, since the file isn't from real HTTP POST. + ); + + // 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 UploadedFile object + return $file; + } + + /* create a tmp file from a raw string: https://gist.github.com/waska14/8b3bcebfad1f86f7fcd3b82927576e38*/ + public static function UploadedFileFromUrl(string $url, string|null $fileName = null, string|null $mimeType = null): UploadedFile + { + // Create temp file and get its absolute path + $tempFile = tmpfile(); + $tempFilePath = stream_get_meta_data($tempFile)['uri']; + + // Save file data in file + file_put_contents($tempFilePath, file_get_contents($url)); + + $tempFileObject = new File($tempFilePath); + $file = new UploadedFile( + $tempFileObject->getPathname(), + $fileName ?: $tempFileObject->getFilename(), + $mimeType ?: $tempFileObject->getMimeType(), + 0, + true // Mark it as test, since the file isn't from real HTTP POST. + ); + + // 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 UploadedFile object + return $file; + } }