1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace AbterPhp\Admin\Http\Controllers; |
6
|
|
|
|
7
|
|
|
use Opulence\Http\Responses\Response; |
8
|
|
|
use Opulence\Http\Responses\ResponseHeaders; |
9
|
|
|
|
10
|
|
|
trait ApiIssueTrait |
11
|
|
|
{ |
12
|
|
|
/** @var string */ |
13
|
|
|
protected $problemBaseUrl; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @param string $msg |
17
|
|
|
* @param array $errors |
18
|
|
|
* |
19
|
|
|
* @return Response |
20
|
|
|
*/ |
21
|
|
|
protected function handleErrors(string $msg, array $errors): Response |
22
|
|
|
{ |
23
|
|
|
$this->logger->debug($msg); |
24
|
|
|
|
25
|
|
|
$detail = []; |
26
|
|
|
foreach ($errors as $key => $keyErrors) { |
27
|
|
|
foreach ($keyErrors as $keyError) { |
28
|
|
|
$detail[] = sprintf('%s: %s', $key, $keyError); |
29
|
|
|
} |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$status = ResponseHeaders::HTTP_BAD_REQUEST; |
33
|
|
|
$content = [ |
34
|
|
|
'type' => sprintf('%sbad-request', $this->problemBaseUrl), |
35
|
|
|
'title' => 'Bad Request', |
36
|
|
|
'status' => $status, |
37
|
|
|
'detail' => implode("\n", $detail), |
38
|
|
|
]; |
39
|
|
|
|
40
|
|
|
$response = new Response(); |
41
|
|
|
$response->setStatusCode($status); |
42
|
|
|
$response->setContent(json_encode($content)); |
43
|
|
|
|
44
|
|
|
return $response; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param string $msg |
49
|
|
|
* @param \Exception $exception |
50
|
|
|
* |
51
|
|
|
* @return Response |
52
|
|
|
*/ |
53
|
|
|
protected function handleException(string $msg, \Exception $exception): Response |
54
|
|
|
{ |
55
|
|
|
$this->logger->error($msg, $this->getExceptionContext($exception)); |
56
|
|
|
|
57
|
|
|
$status = ResponseHeaders::HTTP_INTERNAL_SERVER_ERROR; |
58
|
|
|
$content = [ |
59
|
|
|
'type' => sprintf('%sinternal-server-error', $this->problemBaseUrl), |
60
|
|
|
'title' => 'Internal Server Error', |
61
|
|
|
'status' => $status, |
62
|
|
|
'detail' => $exception->getMessage(), |
63
|
|
|
]; |
64
|
|
|
|
65
|
|
|
$response = new Response(); |
66
|
|
|
$response->setStatusCode($status); |
67
|
|
|
$response->setContent(json_encode($content)); |
68
|
|
|
|
69
|
|
|
return $response; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param \Exception $exception |
74
|
|
|
* |
75
|
|
|
* @return array |
76
|
|
|
*/ |
77
|
|
|
protected function getExceptionContext(\Exception $exception): array |
78
|
|
|
{ |
79
|
|
|
$result = [static::LOG_CONTEXT_EXCEPTION => $exception->getMessage()]; |
|
|
|
|
80
|
|
|
|
81
|
|
|
$i = 1; |
82
|
|
|
while ($exception = $exception->getPrevious()) { |
83
|
|
|
$result[sprintf(static::LOG_PREVIOUS_EXCEPTION, $i++)] = $exception->getMessage(); |
|
|
|
|
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
return $result; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|