Last active
June 29, 2022 10:30
-
-
Save Kyoss79/22bac8b3acf4c8cc9556b37634a2c30f to your computer and use it in GitHub Desktop.
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 | |
// lets assume we have an error object | |
// from a laravel API like the following: | |
$errorResponse = [ | |
'errors' => [ | |
'bike.name' => ['required']. | |
'locks.0.rrp' => ['min:49'], | |
'cancel_url' => ['required] | |
] | |
]; | |
// defined your custom error codes | |
$MY_CUSTOM_ERROR_CODES = ['min' => 555, 'max' => 556, 'required' => 557]; | |
$parsedErrors = []; | |
foreach ($errorResponse['errors'] as $errorKey => $errors) | |
{ | |
$isArray = false; | |
$isObject = false; | |
$errorElement = $errorKey; | |
$arrayItem = 0; | |
// keys with a dot are either arrays or objects | |
if (strpos($errorKey, '.') !== -1) { | |
$isObject = true; | |
$keyElements = explode('.', $errorKey); | |
if (length($keyElements) === 3) { | |
$isArray = true; | |
$arrayName = $keyElements[0]; | |
$arrayItem = (int) $keyElements[1]; | |
$errorElement = $keyElements[2]; | |
} else if (length($keyElements) === 2) { | |
$objectName = $keyElements[0]; | |
$errorElement = $keyElements[1]; | |
} | |
} | |
// parse the error | |
if (is_array($errors) && length($errors)) // is always an array, but let's check anyway | |
{ | |
// let's parse only one error per element | |
($errorType, $errorParams) = explode(':', $errors[0]; | |
// now create the parsed error; | |
$parsedError = [ | |
'field' => $errorElement, | |
'error_code' => $MY_CUSTOM_ERROR_CODES[$errorType], | |
'message' => $errors[0] | |
]; | |
if ($isArray) { | |
$parsedError['type'] = $arrayName; | |
$parsedError['product_number'] = $arrayItem; | |
} | |
if ($isObject) { | |
$parsedError['type'] = $objectName; | |
} | |
$parsedErrors[] = $parsedError; | |
} | |
} | |
// the generated errors would be | |
/* | |
[ | |
[ | |
'type' => 'bike', | |
'field' => 'name', | |
'error_code' => 557, | |
'message' => 'required' | |
], | |
[ | |
'type' => 'locks', | |
'product_number' => 0, | |
'field' => 'rrp', | |
'error_code' => 556, | |
'message' => 'min:49' | |
], | |
[ | |
'field' => 'cancel_url', | |
'error_code' => 557, | |
'message' => 'required' | |
], | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment