Skip to content

Commit

Permalink
addition of new methods and config file
Browse files Browse the repository at this point in the history
  • Loading branch information
nnjeim committed Sep 19, 2021
1 parent ec491ec commit 1378e64
Show file tree
Hide file tree
Showing 10 changed files with 192 additions and 146 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.



46 changes: 34 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -25,7 +29,8 @@ use Nnjeim\Respond\Respond;

return Respond::toJson()
->setMessage('countries')
->withSuccess($response->data);
->setData($response->data)
->withSuccess();
}

abort(400);
Expand All @@ -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();
Expand Down Expand Up @@ -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()
```
Expand All @@ -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' => [
Expand Down
54 changes: 54 additions & 0 deletions config/respond.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

use Symfony\Component\HttpFoundation\Response;

return [
'toJson' => 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,
],
],
];
6 changes: 6 additions & 0 deletions resources/lang/ar/messages.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,18 @@
'singular' => 'سجل',
'plural' => 'سجلات',
],
'success' => [
'ok' => 'تمت المعاملة بنجاح.',
'created' => 'تم إنشاء السجل بنجاح.',
'accepted' => 'تم قبول المعاملة.',
],
'exceptions' => [
'not_authenticated' => 'البيانات لا تتطابق مع سجلاتنا',
'not_authorized' => 'الاتصال ممنوع !',
'not_found' => '! :attribute لم يتم العثور على',
'unprocessable_entity' => 'لا يمكن معالجة هذا الإجراء!',
'server_error' => 'خطأ في الخادم',
'no_content' => 'لا بيانات',
'method_not_found' => 'لم يتم تعريف الوظيفة :method!',
],
];
6 changes: 6 additions & 0 deletions resources/lang/en/messages.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,18 @@
'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!',
'not_found' => 'No :attribute was found!',
'unprocessable_entity' => 'This action cannot be processed!',
'server_error' => 'Internal Server Error',
'no_content' => 'No content',
'method_not_found' => 'Method :method is not defined!',
],
];
6 changes: 6 additions & 0 deletions resources/lang/fr/messages.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,18 @@
'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!',
'not_found' => 'Aucun :attribute a été trouvé!',
'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!',
],
];
60 changes: 57 additions & 3 deletions src/RespondBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

namespace Nnjeim\Respond;

use Nnjeim\Respond\RespondException;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;
use Exception;

abstract class RespondBuilder
{
Expand All @@ -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,
Expand Down
17 changes: 17 additions & 0 deletions src/RespondException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Nnjeim\Respond;

use Exception;

class RespondException extends Exception
{
/**
* @param string $method
* @return static
*/
public static function methodNotFoundException(string $method) {

return new static(trans('respond::messages.exceptions.method_not_found', compact('method')));
}
}
Loading

0 comments on commit 1378e64

Please sign in to comment.