*/ // phpcs:disable Generic.Files.LineLength.TooLong class Utils { /** * Store an image for a model * if a string is passed then the store action is ignored and the strieng is returned * * @param \Illuminate\Http\UploadedFile|\SplFileInfo|string $image * @param string $folderName * @return string The storage path * * @throws \ErrorException If file copy fails. * @throws Exception If didn't manage to return a file path. */ public static function storeImage($image, string $folderName): string { if (\is_object($image) and get_class($image) === UploadedFile::class) { /** @var UploadedFile */ $image = $image; $newPath = self::prepareMoveFile($image->getClientOriginalName(), $folderName); $newPath = str_replace(storage_path('app'), '', $newPath); $image->storePubliclyAs(pathinfo($newPath, \PATHINFO_DIRNAME), pathinfo($newPath, \PATHINFO_BASENAME)); return '/storage' . str_replace('/public', '', $newPath); } if (\is_object($image) and get_class($image) === SplFileInfo::class) { /** @var SplFileInfo */ $image = $image; $newPath = self::prepareMoveFile($image->getBaseName(), $folderName); if (!File::copy($image->getRealPath(), $newPath)) { throw new \ErrorException(sprintf( 'Failed to copy file %s to %s', $image->getRealPath(), $newPath )); } return str_replace(\storage_path('app/public'), '/storage', $newPath); } if (\is_string($image)) { return $image; } throw new Exception(sprintf('Cannot handle image %s', \gettype($image))); } /** * Prepare storage path and return * the image full path * * @param string $filename The basename for the file. * @param string $folderName Foldername for storage. * @return string */ private static function prepareMoveFile(string $filename, string $folderName): string { $pathFolder = \storage_path("app/public/images/$folderName"); if (!File::exists($pathFolder)) { File::makeDirectory($pathFolder, 0755, true); } $filename = sprintf('%s-%s', Str::uuid(), $filename); $fullPath = sprintf('%s/%s', $pathFolder, $filename); if (File::exists($fullPath)) { File::delete($fullPath); } return $fullPath; } }