Skip to content

Commit df53386

Browse files
committed
Fix message translation
1 parent de249cd commit df53386

File tree

7 files changed

+68
-6
lines changed

7 files changed

+68
-6
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -424,8 +424,8 @@ return ApiResponse::create(400, 'error_code.error_code_name:status=FAILED');
424424

425425
{
426426
"success": false,
427-
"message": "Just a failed error message",
428-
"error_code_name": "Example error message with status FAILED"
427+
"message": "Example error message with status FAILED",
428+
"error_code": "error_code_name"
429429
}
430430

431431
```

resources/lang/en/errors.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
|--------------------------------------------------------------------------
1717
*/
1818

19-
'example_code' => 'An example success message',
19+
'example_code' => 'An example error message',
2020
'validation_failed' => 'Validation Failed.',
2121

2222
/*

src/ApiResponse.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
use Illuminate\Http\Request;
1111
use Illuminate\Http\Resources\Json\JsonResource;
1212
use Illuminate\Support\Arr;
13-
use Illuminate\Support\Facades\Lang;
1413
use Illuminate\Support\Str;
1514
use Illuminate\Support\Traits\Conditionable;
1615
use InvalidArgumentException;
@@ -142,7 +141,7 @@ protected function getTranslatedMessageMeta(string $message, array &$data, bool
142141
return [];
143142
}
144143

145-
$translationPrefix = Lang::has($message) ? null : 'api-response::'.config("api-response.translation.{$fileKey}");
144+
$translationPrefix = $this->isTranslationKey($message) ? null : 'api-response::'.config("api-response.translation.{$fileKey}");
146145

147146
$translated = $this->extractTranslationDataFromResponsePayload($data, $message, $translationPrefix);
148147

src/Concerns/ConvertsExceptionToApiResponse.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Illuminate\Http\JsonResponse;
99
use Illuminate\Http\Request;
1010
use Illuminate\Http\Response;
11+
use Illuminate\Support\Arr;
1112
use Illuminate\Support\Str;
1213
use Illuminate\Validation\UnauthorizedException;
1314
use Illuminate\Validation\ValidationException;
@@ -83,6 +84,18 @@ protected function convertHttpExceptionToJsonResponse(HttpExceptionInterface $ex
8384
return ApiResponse::create($statusCode, $message, $data, $headers);
8485
}
8586

87+
protected function convertExceptionToArray(Throwable $e)
88+
{
89+
return config('app.debug') ? [
90+
'message' => $e->getMessage(),
91+
'code' => $e->getCode(),
92+
'exception' => get_class($e),
93+
'file' => $e->getFile(),
94+
'line' => $e->getLine(),
95+
'trace' => collect($e->getTrace())->map(fn ($trace) => Arr::except($trace, ['args']))->all(),
96+
] : [];
97+
}
98+
8699
protected function shouldRenderHtmlOnException(): bool
87100
{
88101
return (bool) config('api-response.render_html_on_exception');

src/Concerns/Translatable.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace KennedyOsaze\LaravelApiResponse\Concerns;
44

55
use Illuminate\Support\Arr;
6+
use Illuminate\Support\Facades\Lang;
67
use Illuminate\Support\Str;
78

89
trait Translatable
@@ -89,4 +90,24 @@ public function getTranslatedStringArray(string $message, array $attributes = []
8990

9091
return ['key' => $key, 'message' => $message];
9192
}
93+
94+
/**
95+
* Determine if a translation exists.
96+
*
97+
* @param string $key
98+
*
99+
* @return bool
100+
*/
101+
public function isTranslationKey(string $key): bool
102+
{
103+
if (Lang::has($key)) {
104+
return true;
105+
}
106+
107+
if (count($parts = explode('::', $key)) === 1) {
108+
return Lang::has($parts[0]);
109+
}
110+
111+
return Lang::has($parts[0].'::'.Str::before($parts[1], ':'));
112+
}
92113
}

tests/ExceptionsHandlerTest.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ public function testUnpreparedExceptionReturnsMinimalResponseWhenDebugModeIsDisa
105105
$response = $this->handler->renderApiResponse($exception, $this->app->request);
106106

107107
$this->assertSame(500, $response->status());
108-
collect(['message', 'exception', 'file', 'line', 'trace'])->each(fn ($key) =>
108+
collect(['message', 'code', 'exception', 'file', 'line', 'trace'])->each(fn ($key) =>
109109
$this->assertArrayHasKey($key, $response->getData(true)['error'])
110110
);
111111
}
@@ -121,6 +121,15 @@ public function testExceptionReturnsViewWhenReturnHtmlIsEnabledOnException()
121121
$this->assertStringContainsString('<!DOCTYPE html>', $response->getContent());
122122
}
123123

124+
public function testHttpExceptionWithTranslationMessageReturnsCorrectResponseData()
125+
{
126+
$exception = new HttpException(400, 'api-response::errors.example_code');
127+
$response = $this->handler->renderApiResponse($exception, $this->app->request);
128+
129+
$this->assertSame(400, $response->status());
130+
$this->assertSame(__('api-response::errors.example_code'), $response->getData(true)['message']);
131+
}
132+
124133
/**
125134
* @dataProvider getHttpResponseExceptionProvider
126135
*/

tests/TranslatableTraitTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,24 @@ public function getTranslationProvider()
8282
['example_code', ['status' => 'dummy'], 'success', ['key' => 'example_code', 'message' => 'Example success message, dummy']],
8383
];
8484
}
85+
86+
/**
87+
* @dataProvider getIsTranslationKeyProvider
88+
*/
89+
public function testIsTranslationKeyReturnsOutputCorrectly($input, $output)
90+
{
91+
$result = $this->class->isTranslationKey($input);
92+
93+
$this->assertSame($output, $result);
94+
}
95+
96+
public function getIsTranslationKeyProvider()
97+
{
98+
return [
99+
['', false],
100+
['dummy message', false],
101+
['api-response::errors.example_code', true],
102+
['api-response::errors.error_code.error_code_name', true],
103+
];
104+
}
85105
}

0 commit comments

Comments
 (0)