1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace MarcinOrlowski\ResponseBuilder\ExceptionHandlers; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Laravel API Response Builder |
8
|
|
|
* |
9
|
|
|
* @package MarcinOrlowski\ResponseBuilder |
10
|
|
|
* |
11
|
|
|
* @author Marcin Orlowski <mail (#) marcinOrlowski (.) com> |
12
|
|
|
* @copyright 2016-2020 Marcin Orlowski |
13
|
|
|
* @license http://www.opensource.org/licenses/mit-license.php MIT |
14
|
|
|
* @link https://github.com/MarcinOrlowski/laravel-api-response-builder |
15
|
|
|
*/ |
16
|
|
|
|
17
|
|
|
use MarcinOrlowski\ResponseBuilder\BaseApiCodes; |
18
|
|
|
use MarcinOrlowski\ResponseBuilder\Contracts\ExceptionHandlerContract; |
19
|
|
|
use MarcinOrlowski\ResponseBuilder\ResponseBuilder as RB; |
20
|
|
|
use Symfony\Component\HttpFoundation\Response as HttpResponse; |
21
|
|
|
|
22
|
|
|
final class HttpExceptionHandler implements ExceptionHandlerContract |
23
|
|
|
{ |
24
|
1 |
|
public function handle(array $user_config, \Exception $ex): ?array |
25
|
|
|
{ |
26
|
|
|
$default_config = [ |
27
|
|
|
// used by unauthenticated() to obtain api and http code for the exception |
28
|
1 |
|
HttpResponse::HTTP_UNAUTHORIZED => [ |
29
|
1 |
|
'api_code' => BaseApiCodes::EX_AUTHENTICATION_EXCEPTION(), |
30
|
|
|
], |
31
|
|
|
// Required by ValidationException handler |
32
|
1 |
|
HttpResponse::HTTP_UNPROCESSABLE_ENTITY => [ |
33
|
1 |
|
'api_code' => BaseApiCodes::EX_VALIDATION_EXCEPTION(), |
34
|
|
|
], |
35
|
|
|
|
36
|
|
|
// Default entry MUST exists. Enforced by unit tests. |
37
|
|
|
RB::KEY_DEFAULT => [ |
38
|
1 |
|
'api_code' => BaseApiCodes::EX_HTTP_EXCEPTION(), |
39
|
|
|
], |
40
|
|
|
]; |
41
|
|
|
|
42
|
1 |
|
$config = \array_replace($default_config, $user_config); |
43
|
|
|
|
44
|
1 |
|
$http_code = $ex->getStatusCode(); |
|
|
|
|
45
|
1 |
|
$result = $config[ $http_code ] ?? null; |
46
|
|
|
|
47
|
|
|
// If we do not have dedicated entry fort this particular http_code, |
48
|
|
|
// fall back to default value. |
49
|
1 |
|
if ($result === null) { |
50
|
|
|
$result = $config[ RB::KEY_DEFAULT ]; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
// Some defaults to fall back to if not set in user config. |
54
|
|
|
$fallback = [ |
55
|
1 |
|
RB::KEY_HTTP_CODE => $http_code, |
56
|
1 |
|
RB::KEY_MSG_KEY => \sprintf('response-builder::builder.http_%d', $http_code), |
57
|
|
|
]; |
58
|
1 |
|
return \array_replace($fallback, $result); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|