Last active
January 26, 2021 06:17
-
-
Save afiqiqmal/e608bd06455839bc8c32c33e3cc116bb to your computer and use it in GitHub Desktop.
Additional response as macro
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 | |
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