Skip to content

Instantly share code, notes, and snippets.

@torabian
Last active May 5, 2020 13:52
Show Gist options
  • Save torabian/6468ed30f91e598015115abec21addf5 to your computer and use it in GitHub Desktop.
Save torabian/6468ed30f91e598015115abec21addf5 to your computer and use it in GitHub Desktop.
<?php
// Whenever you have a successful operation, either having a response object, or just empty response
// Call this function, and pass your collection array, or single object into this function.
function success($entity)
{
if (is_array($entity)) {
$content = [
'data' => [
'items' => $entity
]
];
}
if (is_object($entity)) {
$data = $entity;
$data->fields = join(array_keys(get_object_vars($data)), ',');
$content = [
'data' => $data
];
}
return json_encode($content, JSON_PRETTY_PRINT);
}
// Failure result, including business errors, server errors should be called by this function
// with a different status code (if it's internal error aka.)
function failure($code, $errors = [], $httpStatus = 200)
{
$errors = array_map(function ($item) {
// Do translations here, for each message field if you want, or send for front-end
if (isset($item['message']) && $item['message']) {
return $item;
}
}, $errors);
$content = [
'error' => [
'code' => $code,
'message' => $code, // Do some translations function if you have, to convert code to message
'errors' => $errors
]
];
return json_encode($content, JSON_PRETTY_PRINT);
}
$user = (object) ['first_name' => 'Ali', 'last_name' => 'Torabi'];
echo "\r\nSample success for list of items \r\n";
echo success([['name' => 'ali']]);
echo "\r\nSample success only a single item \r\n";
echo success($user);
echo "\r\nFailure with error code \r\n";
echo failure('ERROR_FIELD', [['location'=> 'email', 'message' => 'EMAIL_IS_NOT_CORRECT']]);
--- results:
Sample success for list of items
{
"data": {
"items": [
{
"name": "ali"
}
]
}
}
Sample success only a single item
{
"data": {
"first_name": "Ali",
"last_name": "Torabi",
"fields": "first_name,last_name"
}
}
Failure with error code
{
"error": {
"code": "ERROR_FIELD",
"message": "ERROR_FIELD",
"errors": [
{
"location": "email",
"message": "EMAIL_IS_NOT_CORRECT"
}
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment