<?php
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
function success_api_processor($data, string $message = null, int $code = 200): JsonResponse
{
return response()->json([
'status' => true,
'message' => $message,
'data' => $data
], $code);
}
function error_api_processor(string $message = null, int $code = 200, $data = null): JsonResponse
{
return response()->json([
'status' => false,
'message' => $message,
'data' => $data
], $code);
}
function validation_error_processor($validator): array
{
$err_keeper = [];
foreach ($validator->errors()->getMessages() as $index => $error) {
$err_keeper[] = ['field' => $index, 'error' => $error[0]];
}
return $err_keeper;
}
function get_base64_file($base64_file): array
{
$extension = explode('/', explode(':', substr($base64_file, 0, strpos($base64_file, ';')))[1])[1]; // .jpg .png .pdf
//find substring from replace here eg: data:image/png;base64,
$replace = substr($base64_file, 0, strpos($base64_file, ',') + 1);
$file = str_replace($replace, '', $base64_file);
$file = str_replace(' ', '+', $file);
$fileName = md5(uniqid(rand(), true)) . '.' . $extension;
return ['file' => $file, 'fileName' => $fileName];
}
function store_base64_file($requestFile, $fileName, $folderName)
{
$file = get_base64_file($requestFile)['file'];
Storage::put('public/' . $folderName . '/' . $fileName, base64_decode($file));
return $fileName;
}
function delete_file($folderName, $fileName): JsonResponse
{
//find if file exists
$path = storage_path('app/public/' . $folderName . '/' . $fileName);
//if so, then unlink from storage
if (File::exists($path)) {
try {
unlink($path);
return success_api_processor([], 'Image deleted successfully.');
} catch (\Exception $e) {
return error_api_processor('Something went wrong! Please try again later.', 200, []);
}
}
return error_api_processor('Image not found!.', 200, []);
}