|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Visiosoft\ConnectModule\Traits; |
| 4 | + |
| 5 | +use Illuminate\Http\JsonResponse; |
| 6 | + |
| 7 | +trait ReturnResponseTrait |
| 8 | +{ |
| 9 | + protected array $output = [ |
| 10 | + 'success' => true, |
| 11 | + 'data' => [], |
| 12 | + 'message' => '', |
| 13 | + ]; |
| 14 | + |
| 15 | + /** |
| 16 | + * @param $data |
| 17 | + * @param bool $success |
| 18 | + * @param string $message |
| 19 | + * @param int $statusCode |
| 20 | + * @return JsonResponse |
| 21 | + */ |
| 22 | + public function sendResponse($data = [], string $message = '', bool $success = true, int $statusCode = 200): JsonResponse |
| 23 | + { |
| 24 | + if (request()->method() == 'POST') { |
| 25 | + $statusCode = 201; |
| 26 | + } |
| 27 | + $this->output['success'] = $success; |
| 28 | + $this->output['data'] = $data; |
| 29 | + $this->output['message'] = $message; |
| 30 | + return $this->setResponse($this->output, $statusCode); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * @param array $errors |
| 35 | + * @param string $message |
| 36 | + * @param int $statusCode |
| 37 | + * @return JsonResponse |
| 38 | + */ |
| 39 | + public function sendError($errors = [], string $message = '', int $statusCode = 404): JsonResponse |
| 40 | + { |
| 41 | + $this->output['success'] = false; |
| 42 | + $this->output['errors'] = $errors; |
| 43 | + $this->output['message'] = $message; |
| 44 | + return $this->setResponse($this->output, $statusCode); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * @param $e |
| 49 | + * @param $statusCode |
| 50 | + * @return JsonResponse |
| 51 | + */ |
| 52 | + public function sendExceptionError($e, $statusCode = 500): JsonResponse |
| 53 | + { |
| 54 | + $message = 'internal error'; |
| 55 | + if (config('app.debug')) { |
| 56 | + $message = $e->getMessage() . ' LINE:' . $e->getLine(); |
| 57 | + } |
| 58 | + $this->output['success'] = false; |
| 59 | + $this->output['message'] = $message; |
| 60 | + return $this->setResponse($this->output, $statusCode); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * @param array $data |
| 65 | + * @param int $code |
| 66 | + * @return JsonResponse |
| 67 | + */ |
| 68 | + private function setResponse(array $data = [], int $code = 200): JsonResponse |
| 69 | + { |
| 70 | + return response()->json($data, $code); |
| 71 | + } |
| 72 | +} |
0 commit comments