From 1378e642287a10aa857dc90069d9a16f854cbeba Mon Sep 17 00:00:00 2001 From: Najm Njeim Date: Sun, 19 Sep 2021 12:25:18 +0300 Subject: [PATCH] addition of new methods and config file --- CHANGELOG.md | 3 + README.md | 46 +++++++++--- config/respond.php | 54 ++++++++++++++ resources/lang/ar/messages.php | 6 ++ resources/lang/en/messages.php | 6 ++ resources/lang/fr/messages.php | 6 ++ src/RespondBuilder.php | 60 ++++++++++++++- src/RespondException.php | 17 +++++ src/RespondHelper.php | 131 --------------------------------- src/RespondServiceProvider.php | 9 +++ 10 files changed, 192 insertions(+), 146 deletions(-) create mode 100644 config/respond.php create mode 100644 src/RespondException.php diff --git a/CHANGELOG.md b/CHANGELOG.md index a4863af..39d3633 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,8 @@ All notable changes will be documented in this file ## 1.0.2 - 2021-09-19 - general refactoring +## 1.1.0 - 2021-09-19 +- Addition of the helpers method withAccepted and withCreated. + diff --git a/README.md b/README.md index 5b93bc8..26fd409 100755 --- a/README.md +++ b/README.md @@ -12,6 +12,10 @@ You can install the package via composer: composer require nnjeim/respond ``` +## Configuration +``` +php artisan vendor:publish --provider="Nnjeim\Respond\RespondServiceProvider" + ## Usage ##### Respond Facade @@ -25,7 +29,8 @@ use Nnjeim\Respond\Respond; return Respond::toJson() ->setMessage('countries') - ->withSuccess($response->data); + ->setData($response->data) + ->withSuccess(); } abort(400); @@ -48,12 +53,13 @@ public function __construct(RespondHelper $respond) . $respond = $this ->respond + ->toJson() ->setMessage('countries') - ->toJson(); + ->setData($data); if ($this->success) { - return $respond->withSuccess($data) + return $respond->withSuccess() } return $respond->withErrors(); @@ -98,7 +104,9 @@ Sets the response errors. ##### respond in Json format ``` -returns an instance of Illuminate\Http\JsonResponse +returns an instance of Illuminate\Http\JsonResponse + +this method overwrites the config `toJson` set value. @return $this toJson() ``` @@ -107,55 +115,69 @@ returns an instance of Illuminate\Http\JsonResponse ``` On success response. The default response status code is 200. -@return $this withSuccess(?array $data = null) +@return array|JsonResponse withSuccess() +``` + +##### Respond with created +``` +On created response. The default response status code is 201. + +@return array|JsonResponse withCreated() +``` + +##### Respond with accepted +``` +On accepted response. The default response status code is 202. + +@return array|JsonResponse withAccepted() ``` ##### Respond with no content ``` On success response with no results found. The default status code is 204 -@return $this withNoContent() +@return array|JsonResponse withNoContent() ``` ##### Respond with errors ``` On error response. The default response status code is 422. -@return $this withErrors(?array $errors = null) +@return array|JsonResponse withErrors(?array $errors = null) ``` ##### Respond with server error ``` On server error response. The default response status code is 500. -@return $this withServerError() +@return array|JsonResponse withServerError() ``` ##### Respond with not found ``` Record not found error. The default response status code is 404. -@return array withNotFound(?string $attribute = null, bool $plural = true) +@return array|JsonResponse withNotFound() ``` ##### Respond with not authenticated ``` Not authenticated reponse. The default response status code is 401. -@return array withNotAuthenticated($message = null) +@return array|JsonResponse withNotAuthenticated() ``` ##### Respond with not authorized ``` Not authorized reponse. The default response status code is 403. -@return array withNotAuthorized($message = null) +@return array|JsonResponse withNotAuthorized() ``` ## Respond ``` -@return array +@return array|JsonResponse [ 'response' => [ diff --git a/config/respond.php b/config/respond.php new file mode 100644 index 0000000..645b8b6 --- /dev/null +++ b/config/respond.php @@ -0,0 +1,54 @@ + true, + 'responses' => [ + 'success' => [ + 'success' => true, + 'message' => 'messages.success.ok', + 'status' => Response::HTTP_OK, + ], + 'created' => [ + 'success' => true, + 'message' => 'messages.success.created', + 'status' => Response::HTTP_CREATED, + ], + 'accepted' => [ + 'success' => true, + 'message' => 'messages.success.accepted', + 'status' => Response::HTTP_ACCEPTED, + ], + 'errors' => [ + 'success' => false, + 'message' => 'messages.exceptions.unprocessable_entity', + 'status' => Response::HTTP_UNPROCESSABLE_ENTITY, + ], + 'nocontent' => [ + 'success' => true, + 'message' => 'messages.exceptions.no_content', + 'status' => Response::HTTP_NO_CONTENT, + ], + 'servererror' => [ + 'success' => false, + 'message' => 'messages.exceptions.server_error', + 'status' => Response::HTTP_INTERNAL_SERVER_ERROR, + ], + 'notfound' => [ + 'success' => false, + 'message' => 'messages.exceptions.not_found', + 'status' => Response::HTTP_NOT_FOUND, + ], + 'notauthenticated' => [ + 'success' => false, + 'message' => 'messages.exceptions.not_authenticated', + 'status' => Response::HTTP_UNAUTHORIZED, + ], + 'notauthorized' => [ + 'success' => false, + 'message' => 'messages.exceptions.not_authorized', + 'status' => Response::HTTP_FORBIDDEN, + ], + ], +]; diff --git a/resources/lang/ar/messages.php b/resources/lang/ar/messages.php index 24c7f5f..dcc97bd 100644 --- a/resources/lang/ar/messages.php +++ b/resources/lang/ar/messages.php @@ -5,6 +5,11 @@ 'singular' => 'سجل', 'plural' => 'سجلات', ], + 'success' => [ + 'ok' => 'تمت المعاملة بنجاح.', + 'created' => 'تم إنشاء السجل بنجاح.', + 'accepted' => 'تم قبول المعاملة.', + ], 'exceptions' => [ 'not_authenticated' => 'البيانات لا تتطابق مع سجلاتنا', 'not_authorized' => 'الاتصال ممنوع !', @@ -12,5 +17,6 @@ 'unprocessable_entity' => 'لا يمكن معالجة هذا الإجراء!', 'server_error' => 'خطأ في الخادم', 'no_content' => 'لا بيانات', + 'method_not_found' => 'لم يتم تعريف الوظيفة :method!', ], ]; diff --git a/resources/lang/en/messages.php b/resources/lang/en/messages.php index efba62b..1d3752d 100644 --- a/resources/lang/en/messages.php +++ b/resources/lang/en/messages.php @@ -5,6 +5,11 @@ 'singular' => 'record', 'plural' => 'records', ], + 'success' => [ + 'ok' => 'The transaction was completed successfully.', + 'created' => 'The record was created successfully.', + 'accepted' => 'The transaction was accepted.', + ], 'exceptions' => [ 'not_authenticated' => 'These credentials do not match our records.', 'not_authorized' => 'Access forbidden!', @@ -12,5 +17,6 @@ 'unprocessable_entity' => 'This action cannot be processed!', 'server_error' => 'Internal Server Error', 'no_content' => 'No content', + 'method_not_found' => 'Method :method is not defined!', ], ]; diff --git a/resources/lang/fr/messages.php b/resources/lang/fr/messages.php index 6922676..88d2f6a 100644 --- a/resources/lang/fr/messages.php +++ b/resources/lang/fr/messages.php @@ -5,6 +5,11 @@ 'singular' => 'enregistrement', 'plural' => 'enregistrements', ], + 'success' => [ + 'ok' => 'La transaction a été effectuée avec succès.', + 'created' => 'L\'enregistrement a été créé avec succès.', + 'accepted' => 'La transaction a été acceptée.', + ], 'exceptions' => [ 'not_authenticated' => 'Ces informations d\'identification ne correspondent pas à nos enregistrements.', 'not_authorized' => 'Accès interdit!', @@ -12,5 +17,6 @@ 'unprocessable_entity' => 'Cette action ne peut pas être traitée!', 'server_error' => 'Erreur Interne du Serveur', 'no_content' => 'Pas de contenu', + 'method_not_found' => 'La méthode :method n\'est pas definie!', ], ]; diff --git a/src/RespondBuilder.php b/src/RespondBuilder.php index f9d5134..49b7ae3 100644 --- a/src/RespondBuilder.php +++ b/src/RespondBuilder.php @@ -2,7 +2,11 @@ namespace Nnjeim\Respond; +use Nnjeim\Respond\RespondException; + use Illuminate\Http\JsonResponse; +use Illuminate\Support\Str; +use Exception; abstract class RespondBuilder { @@ -26,19 +30,69 @@ public function __set($key, $value) $this->attributes[$key] = $value; } + /** + * @param $method + * @param null $args + * @return array|JsonResponse + * @throws Exception + */ + public function __call($method, $args = null) + { + if (Str::contains($method, 'with')) { + + return $this->withResponder($method, ...$args); + } + + throw RespondException::methodNotFoundException($method); + } + + /** + * @param string $method + * @param null $args + * @return array|JsonResponse + * @throws Exception + */ + public function withResponder(string $method, $args = null) { + + $key = strtolower(Str::after($method, 'with')); + + $responses = config('respond.responses'); + + if (! array_key_exists($key, $responses)) { + throw RespondException::methodNotFoundException($method); + } + + ['success' => $success, 'message' => $message, 'status' => $status] + = $responses[$key] + + ['message' => null]; + + /*-- set success --*/ + $this->success = $success; + /*-- set message --*/ + if (isset($message)) { + $this->message ??= trans("respond::$message"); + } + /*-- set status --*/ + $this->status ??= $status; + + return $this->respond(); + } + /** * @return array|JsonResponse */ public function respond() { - $this->formatResponse(); + $this->formResponse(); ['response' => $response, 'status' => $status] = $this->attributes; - return ($this->json === null) ? compact('response', 'status') : response()->json($response, $status); + return ($this->json === null && !config('respond.toJson')) + ? compact('response', 'status') + : response()->json($response, $status); } - private function formatResponse(): void + private function formResponse(): void { $response = [ 'success' => false, diff --git a/src/RespondException.php b/src/RespondException.php new file mode 100644 index 0000000..2f1dd8b --- /dev/null +++ b/src/RespondException.php @@ -0,0 +1,17 @@ +success = true; - - $this->status ??= self::HTTP_OK; - - if ($data !== null) { - - $this->setData($data); - } - - return $this->respond(); - } - - /** - * @param array|null $errors - * @return array|JsonResponse - */ - public function withErrors(?array $errors = null) - { - $this->success = false; - - $this->status ??= self::HTTP_UNPROCESSABLE_ENTITY; - - $this->message ??= trans('respond::messages.exceptions.unprocessable_entity'); - - if ($errors !== null) { - - $this->errors = $errors; - } - - return $this->respond(); - } - - /** - * @return array|JsonResponse - */ - public function withNoContent() - { - $this->success = true; - - $this->status ??= self::HTTP_NO_CONTENT; - - $this->message ??= trans('respond::messages.exceptions.no_content'); - - $this->errors ??= [[$this->message]]; - - return $this->respond(); - } - - /** - * @return array|JsonResponse - */ - public function withServerError() - { - $this->success = false; - - $this->status ??= self::HTTP_INTERNAL_SERVER_ERROR; - - $this->message ??= trans('respond::messages.exceptions.server_error'); - - $this->errors ??= [[$this->message]]; - - return $this->respond(); - } - - /** - * @param string|null $attribute - * @param bool $plural - * @return array|JsonResponse - */ - public function withNotFound(?string $attribute = null, bool $plural = true) - { - $this->success = false; - - $this->status ??= self::HTTP_NOT_FOUND; - - $defaultAttribute = trans('respond::messages.record.singular'); - - $error = trans('respond::messages.exceptions.not_found', [ - 'attribute' => $attribute ?? $defaultAttribute - ]); - - $this->errors = [[$error]]; - - return $this->respond(); - } - - /** - * @return array|JsonResponse - */ - public function withNotAuthenticated() - { - $this->success = false; - - $this->status ??= self::HTTP_UNAUTHORIZED; - - $this->errors ??= [[trans('respond::messages.exceptions.not_authenticated')]]; - - return $this->respond(); - } - - /** - * @return array|JsonResponse - */ - public function withNotAuthorized() - { - $this->success = false; - - $this->status ??= self::HTTP_FORBIDDEN; - - $this->errors ??= [[trans('respond::messages.exceptions.not_authorized')]]; - - return $this->respond(); - } } diff --git a/src/RespondServiceProvider.php b/src/RespondServiceProvider.php index 7b0eb7f..fe024a9 100644 --- a/src/RespondServiceProvider.php +++ b/src/RespondServiceProvider.php @@ -17,6 +17,15 @@ public function boot() { // Load translations $this->loadTranslationsFrom(__DIR__ . '/../resources/lang', 'respond'); + + // Load the configurations + $this->mergeConfigFrom(__DIR__ . '/../config/respond.php', 'respond'); + + if ($this->app->runningInConsole()) { + $this->publishes([ + __DIR__ . '/../config/respond.php' => config_path('respond.php'), + ]); + } } /**