-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMessagePipe.php
More file actions
89 lines (77 loc) · 2.39 KB
/
MessagePipe.php
File metadata and controls
89 lines (77 loc) · 2.39 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
declare(strict_types=1);
/**
* Copyright (c) 2024-2026 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 Illuminate\Support\Facades\Lang;
use Symfony\Component\HttpFoundation\Response;
class MessagePipe
{
use WithPipeArgs;
/**
* @api
*
* @param array{
* status: bool|int|string,
* code: int,
* message: string,
* data: mixed,
* error: null|array<string, mixed>,
* } $structure
* @param \Closure(array<string, mixed>): \Illuminate\Http\JsonResponse $next
* @param string $fallbackErrorMessage // ['Whoops, looks like something went wrong.', 'Server Error', 'Internal Server Error', 'Unknown Status'];
*
* @noinspection RedundantDocCommentTagInspection
*/
public function handle(
array $structure,
\Closure $next,
string $mainTransKey = 'http-statuses',
string $fallbackErrorMessage = 'Internal Server Error',
string $fallbackSuccessMessage = 'OK'
): JsonResponse {
$structure['message'] = __($structure['message'] ?: $this->transKeyFor(
$structure,
$mainTransKey,
$fallbackErrorMessage,
$fallbackSuccessMessage
));
return $next($structure);
}
/**
* @param array{
* status: bool|int|string,
* code: int,
* message: string,
* data: mixed,
* error: null|array<string, mixed>,
* } $structure
*/
private function transKeyFor(
array $structure,
string $mainTransKey,
string $fallbackErrorMessage,
string $fallbackSuccessMessage
): string {
$code = $structure['code'];
if (Lang::has($key = "$mainTransKey.$code")) {
return $key;
}
$statusCode = Utils::statusCodeFor($code);
if (Lang::has($key = "$mainTransKey.$statusCode")) {
return $key;
}
return Response::$statusTexts[$statusCode] ?? (
$structure['status'] ? $fallbackSuccessMessage : $fallbackErrorMessage
);
}
}