Last active
June 11, 2020 11:46
-
-
Save edionmelarosa/46a0799e3f3618beeae1bda389f85ee5 to your computer and use it in GitHub Desktop.
Useful function for PHP/Laravel project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!function_exists('json_response')) { | |
function json_response($data, $status=200) | |
{ | |
return response() | |
->json($data, $status); | |
} | |
} | |
if (!function_exists('lazy_csv_file')) { | |
/** | |
* Reads entire csv file into a generator | |
* | |
* @param mixed $path | |
* @param bool $skipFirstRow | |
* @return Generator<int, (array|null|false)> | |
* @throws Exception | |
*/ | |
function lazy_csv_file($path, $skipFirstRow=false) | |
{ | |
try { | |
if ($handle = fopen($path, 'r')) { | |
// skip first row | |
if ($skipFirstRow) { | |
fgetcsv($handle); | |
} | |
while (($line = fgetcsv($handle, 1000)) !== FALSE) { | |
yield $line; | |
} | |
fclose($handle); | |
} | |
} catch (\Throwable $th) { | |
throw new Exception($th); | |
} | |
} | |
} | |
if (!function_exists('process_base_64_file')) { | |
function process_base_64_file($base64File) | |
{ | |
try { | |
// .jpg .png .pdf | |
$extension = explode('/', explode(':', substr($base64File, 0, strpos($base64File, ';')))[1])[1]; | |
$replace = substr($base64File, 0, strpos($base64File, ',') + 1); | |
$file = str_replace($replace, '', $base64File); | |
$file = str_replace(' ', '+', $file); | |
$fileName = uniqid() . '.' . $extension; | |
return [ | |
'file' => $file, | |
'fileName' => $fileName, | |
'extension' => $extension | |
]; | |
} catch (\Throwable $th) { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment