Skip to content

Instantly share code, notes, and snippets.

@zuxbrt
Last active February 17, 2020 09:26
Show Gist options
  • Save zuxbrt/29bcfff29b9bae31dcd039f0b183a46e to your computer and use it in GitHub Desktop.
Save zuxbrt/29bcfff29b9bae31dcd039f0b183a46e to your computer and use it in GitHub Desktop.
<?php
/**
* @author zuxbrt
*/
namespace App\Handlers;
use Exception;
class CSVEncoder
{
/**
* Error codes given after csv encoding failure.
*/
protected $error_codes = [
0 => 'JSON_ERROR_NONE',
1 => 'JSON_ERROR_DEPTH',
2 => 'JSON_ERROR_STATE_MISMATCH',
3 => 'JSON_ERROR_CTRL_CHAR',
4 => 'JSON_ERROR_SYNTAX',
5 => 'JSON_ERROR_UTF8',
6 => 'JSON_ERROR_RECURSION',
7 => 'JSON_ERROR_INF_OR_NAN',
8 => 'JSON_ERROR_UNSUPPORTED_TYPE',
9 => 'JSON_ERROR_INVALID_PROPERTY_NAME',
10 => 'JSON_ERROR_UTF16',
];
/**
* Encode csv file for user import.
* @param $file
* @param $file_path
*/
public function encodeCsv($file, $file_path)
{
$encoded = json_encode($file);
if(!$encoded){
$status_code = json_last_error();
$errorMsg = json_last_error_msg();
$pass = $this->handleError($status_code, $file, $file_path);
if($pass){
return $pass;
} else {
// log TODO
return null;
}
} else {
return $encoded;
}
}
/**
* Handle encoding error.
* @param int $code
* @param $file
*/
public function handleError($code, $file, $file_path)
{
switch($code) {
// no error
case ($code === 0):
return $file;
// The maximum stack depth has been exceeded
case ($code === 1):
return null;
// Invalid or malformed JSON
case ($code === 2):
return null;
// Control character error, possibly incorrectly encoded
case ($code === 3):
return null;
// syntax error
case ($code === 4):
return null;
// Malformed UTF-8 characters, possibly incorrectly encoded
case ($code === 5):
return $this->utf_ize($file, 'UTF-8', $file_path);
// One or more recursive references in the value to be encoded
case ($code === 6):
return null;
// One or more NAN or INF values in the value to be encoded
case ($code === 7):
return null;
// A value of a type that cannot be encoded was given
case ($code === 8):
return null;
// A property name that cannot be encoded was given
case ($code === 9):
return null;
// Malformed UTF-16 characters, possibly incorrectly encoded
case ($code === 10):
return $this->utf_ize($file, 'UTF-16', $file_path);
}
}
/**
* Convert encoding according to utf.
*/
public function utf_ize($content, $utf, $file_path) {
// get string from csv
$string_to_encode = file_get_contents($file_path);
$encoded = '';
try {
$encoded = mb_convert_encoding($string_to_encode, $utf, "auto");
return $encoded;
} catch (Exception $e){
// if unable to detect character encoding
if($e->getCode() === 0){
// get rid of binary values
$encoded = utf8_encode($string_to_encode);
return $encoded;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment