Skip to content

Commit 4024a0c

Browse files
committed
- Document new functionality to pass additional object types - Extract code to fetch message from an exception to method
1 parent 2278d39 commit 4024a0c

File tree

3 files changed

+40
-15
lines changed

3 files changed

+40
-15
lines changed

README.md

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ A simple package allowing for consistent API responses throughout your Laravel a
2121
`composer require f9webltd/laravel-api-response-helpers`
2222

2323

24-
Simply reference the required trait in your controller:
24+
Simply reference the required trait within your controller:
2525

2626
```php
2727
<?php
@@ -48,7 +48,7 @@ Optionally, the trait could be imported within a base controller.
4848

4949
#### `respondNotFound(string|Exception $message, ?string $key = 'error')`
5050

51-
Returns a `404` HTTP status code, an excpetion object can optionally be passed.
51+
Returns a `404` HTTP status code, an exception object can optionally be passed.
5252

5353
#### `respondWithSuccess(array|Arrayable|JsonSerializable|null $contents = [])`
5454

@@ -78,6 +78,22 @@ Returns a `201` HTTP status code, with response optional data
7878

7979
Returns a `204` HTTP status code, with optional response data. Strictly speaking, the response body should be empty. However, functionality to optionally return data was added to handle legacy projects. Within your own projects, you can simply call the method, omitting parameters, to generate a correct `204` response i.e. `return $this->respondNoContent()`
8080

81+
## Additional Data Types
82+
83+
In addition to a plain PHP `array`, the following data types can be passed to relevant methods:
84+
85+
- Objects implementing the Laravel `Illuminate\Contracts\Support\Arrayable` contract
86+
- Objects implementing the native PHP `JsonSerializable` contract
87+
88+
This allows a variety of object types to be passed and converted automatically.
89+
90+
Some example objects that can be passed (there are a lot more):
91+
92+
- `Illuminate\Support\Collection` (i.e. [Collections](https://laravel.com/docs/8.x/collections))
93+
- `Illuminate\Database\Eloquent` (i.e. [Eloquent collections](https://laravel.com/docs/8.x/eloquent-collections))
94+
- `Illuminate\Http\Resources\Json\JsonResource` (i.e. [Laravel API resources](https://laravel.com/docs/8.x/eloquent-resources))
95+
- `Illuminate\Foundation\Http\FormRequest`
96+
8197
## Motivation
8298

8399
Ensure consistent JSON API responses throughout an application. The motivation was primarily based on a very old inherited Laravel project. The project contained a plethora of methods/structures used to return an error:

src/ApiResponseHelpers.php

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,8 @@ public function respondNotFound(
2424
$message,
2525
?string $key = 'error'
2626
): JsonResponse {
27-
$message = $message instanceof Exception
28-
? $message->getMessage()
29-
: $message;
30-
3127
return $this->apiResponse(
32-
[$key => $message],
28+
[$key => $this->morphMessage($message)],
3329
Response::HTTP_NOT_FOUND
3430
);
3531
}
@@ -82,9 +78,10 @@ public function respondError(?string $message = null): JsonResponse
8278
*/
8379
public function respondCreated($data = []): JsonResponse
8480
{
85-
$data = $this->morphToArray($data);
86-
87-
return $this->apiResponse($data, Response::HTTP_CREATED);
81+
return $this->apiResponse(
82+
$this->morphToArray($data),
83+
Response::HTTP_CREATED
84+
);
8885
}
8986

9087
/**
@@ -97,12 +94,8 @@ public function respondFailedValidation(
9794
$message,
9895
?string $key = 'message'
9996
): JsonResponse {
100-
$message = $message instanceof Exception
101-
? $message->getMessage()
102-
: $message;
103-
10497
return $this->apiResponse(
105-
[$key => $message ?? 'Validation errors'],
98+
[$key => $this->morphMessage($message)],
10699
Response::HTTP_UNPROCESSABLE_ENTITY
107100
);
108101
}
@@ -146,4 +139,15 @@ private function morphToArray($data)
146139

147140
return $data;
148141
}
142+
143+
/**
144+
* @param string|\Exception $message
145+
* @return string
146+
*/
147+
private function morphMessage($message): string
148+
{
149+
return $message instanceof Exception
150+
? $message->getMessage()
151+
: $message;
152+
}
149153
}

tests/ResponseTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,11 @@ public function testRespondFailedValidation(): void
137137
self::assertJsonStringEqualsJsonString('{"message":"Password is required"}', $response->getContent());
138138
self::assertEquals(['message' => 'Password is required'], $response->getData(true));
139139

140+
/** @var \Illuminate\Http\JsonResponse $response */
141+
$response = $this->service->respondFailedValidation(new DomainException('Bad things happening ...'));
142+
self::assertJsonStringEqualsJsonString('{"message":"Bad things happening ..."}', $response->getContent());
143+
self::assertEquals(['message' => 'Bad things happening ...'], $response->getData(true));
144+
140145
/** @var \Illuminate\Http\JsonResponse $response */
141146
$response = $this->service->respondFailedValidation('Password is required', 'erm');
142147
self::assertJsonStringEqualsJsonString('{"erm":"Password is required"}', $response->getContent());

0 commit comments

Comments
 (0)