8000 [Feature] Allow error response using string error key · josh-taylor/laravel-json-api@87742f4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 87742f4

Browse files
committed
[Feature] Allow error response using string error key
The response factory now allows for a string key to be passed through for an error. In such cases, the error will be pulled from the error repository.
1 parent 92a4306 commit 87742f4

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

src/Http/Responses/ResponseFactory.php

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,12 @@
1818

1919
namespace CloudCreativity\LaravelJsonApi\Http\Responses;
2020

21+
use CloudCreativity\JsonApi\Contracts\Repositories\ErrorRepositoryInterface;
2122
use CloudCreativity\JsonApi\Exceptions\MutableErrorCollection as Errors;
2223
use CloudCreativity\LaravelJsonApi\Contracts\Pagination\PaginatorInterface;
2324
use Illuminate\Contracts\Pagination\Paginator;
2425
use Illuminate\Http\Response;
26+
use InvalidArgumentException;
2527
use Neomerx\JsonApi\Contracts\Document\ErrorInterface;
2628
use Neomerx\JsonApi\Contracts\Http\ResponsesInterface;
2729
use Neomerx\JsonApi\Exceptions\ErrorCollection;
@@ -43,15 +45,25 @@ class ResponseFactory
4345
*/
4446
private $paginator;
4547

48+
/**
49+
* @var ErrorRepositoryInterface
50+
*/
51+
private $errors;
52+
4653
/**
4754
* ResponseFactory constructor.
4855
* @param ResponsesInterface $responses
4956
* @param PaginatorInterface $paginator
57+
* @param ErrorRepositoryInterface $errors
5058
*/
51-
public function __construct(ResponsesInterface $responses, PaginatorInterface $paginator)
52-
{
59+
public function __construct(
60+
ResponsesInterface $responses,
61+
PaginatorInterface $paginator,
62+
ErrorRepositoryInterface $errors
63+
) {
5364
$this->responses = $responses;
5465
$this->paginator = $paginator;
66+
$this->errors = $errors;
5567
}
5668

5769
/**
@@ -144,13 +156,22 @@ public function relationship(
144156
}
145157

146158
/**
147-
* @param ErrorInterface $error
159+
* @param ErrorInterface|string $error
160+
* the error object or a string error key to get the error from the repository.
148161
* @param int|string|null $statusCode
149162
* @param array $headers
150163
* @return Response
151164
*/
152-
public function error(ErrorInterface $error, $statusCode = null, array $headers = [])
165+
public function error($error, $statusCode = null, array $headers = [])
153166
{
167+
if (is_string($error) && !empty($error)) {
168+
$error = $this->errors->error($error);
169+
}
170+
171+
if (!$error instanceof ErrorInterface) {
172+
throw new InvalidArgumentException('Expecting an error object or a string error key.');
173+
}
174+
154175
return $this->errors($error, $statusCode, $headers);
155176
}
156177

0 commit comments

Comments
 (0)
0