Skip to content

Instantly share code, notes, and snippets.

@afiqiqmal
Last active January 26, 2021 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afiqiqmal/e608bd06455839bc8c32c33e3cc116bb to your computer and use it in GitHub Desktop.
Save afiqiqmal/e608bd06455839bc8c32c33e3cc116bb to your computer and use it in GitHub Desktop.
Additional response as macro
<?php
namespace App\Macros\Response;
use App\Http\Factory\JsonResponse;
use App\Macros\MacroContract;
use Illuminate\Http\Client\Response as ClientResponse;
use Illuminate\Support\Facades\Response as HttpResponse;
use Illuminate\Support\MessageBag;
class ResponseMacro implements MacroContract
{
public static function registerMacros()
{
(new self)->createMacros();
}
public function createMacros()
{
HttpResponse::macro('success', function ($msg = null, $obj = null, $code = 200, array $headers = []) {
if (! is_string($msg)) {
$obj = $msg;
$msg = __('api.request_success');
}
return $this->customJson(
[
'error' => false,
'message' => $msg,
'data' => $obj,
],
$code
);
});
HttpResponse::macro('customJson', function ($data = [], $status = 200, array $headers = [], $options = 0) {
return new JsonResponse($data, $status, $headers, $options);
});
HttpResponse::macro('error', function ($msg = 'Something went wrong', $reference = null, $code = 400, array $headers = [], $exception = null) {
if (!$exception) {
if ($reference instanceof \Exception) {
$exception = $reference;
$reference = null;
}
}
try {
$type = (new \ReflectionClass($exception))->getShortName();
$debugMessage = $exception->getMessage();
} catch (\Exception $e) {
}
$headers = array_merge([
'Access-Control-Allow-Origin' => '*',
], $headers);
if ($reference instanceof MessageBag) {
$flat = collect($reference->all())->flatten()->values()->all();
$refs = [];
foreach ($reference->getMessages() as $index => $item) {
$refs[] = [
'name' => $index,
'validation' => $item
];
}
}
return $this->customJson(
[
'error' => true,
'code' => $code,
'type' => $type ?? null,
'message' => $msg,
'detail' => is_string($reference) ? $reference : null,
'reference' => $refs ?? [],
'reference_flat' => $flat ?? [],
'debug_message' => config('app.debug') ? $debugMessage ?? null : null,
'under_maintenance' => app()->isApplicationDownForMaintenance(),
],
$code,
$headers
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment