-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStatusCodePipe.php
65 lines (58 loc) · 1.77 KB
/
StatusCodePipe.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
declare(strict_types=1);
/**
* Copyright (c) 2024-2025 guanguans<ityaozm@gmail.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* @see https://github.com/guanguans/laravel-api-response
*/
namespace Guanguans\LaravelApiResponse\Pipes;
use Guanguans\LaravelApiResponse\Support\Traits\WithPipeArgs;
use Guanguans\LaravelApiResponse\Support\Utils;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
class StatusCodePipe
{
use WithPipeArgs;
/**
* @noinspection RedundantDocCommentTagInspection
*
* @param \Closure(array): \Illuminate\Http\JsonResponse $next
* @param array{
* status: bool,
* code: int,
* message: string,
* data: mixed,
* error: ?array,
* } $structure
*/
public function handle(
array $structure,
\Closure $next,
int $fallbackErrorStatusCode = Response::HTTP_INTERNAL_SERVER_ERROR,
int $fallbackSuccessStatusCode = Response::HTTP_OK
): JsonResponse {
return $next($structure)->setStatusCode($this->statusCodeFor(
$structure,
$fallbackErrorStatusCode,
$fallbackSuccessStatusCode
));
}
/**
* @param array{
* status: bool,
* code: int,
* message: string,
* data: mixed,
* error: ?array,
* } $structure
*/
private function statusCodeFor(array $structure, int $fallbackErrorStatusCode, int $fallbackSuccessStatusCode): int
{
return Utils::isValidStatusCode($statusCode = Utils::statusCodeFor($structure['code']))
? $statusCode
: ($structure['status'] ? $fallbackSuccessStatusCode : $fallbackErrorStatusCode);
}
}