]>
Commit | Line | Data |
---|---|---|
18e67967 A |
1 | <?php |
2 | ||
3 | namespace Shaarli\Api\Exceptions; | |
4 | ||
5 | use Slim\Http\Response; | |
6 | ||
7 | /** | |
8 | * Abstract class ApiException | |
9 | * | |
10 | * Parent Exception related to the API, able to generate a valid Response (ResponseInterface). | |
11 | * Also can include various information in debug mode. | |
12 | */ | |
f211e417 V |
13 | abstract class ApiException extends \Exception |
14 | { | |
18e67967 A |
15 | |
16 | /** | |
17 | * @var Response instance from Slim. | |
18 | */ | |
19 | protected $response; | |
20 | ||
21 | /** | |
22 | * @var bool Debug mode enabled/disabled. | |
23 | */ | |
24 | protected $debug; | |
25 | ||
26 | /** | |
27 | * Build the final response. | |
28 | * | |
29 | * @return Response Final response to give. | |
30 | */ | |
f211e417 | 31 | abstract public function getApiResponse(); |
18e67967 A |
32 | |
33 | /** | |
34 | * Creates ApiResponse body. | |
35 | * In production mode, it will only return the exception message, | |
36 | * but in dev mode, it includes additional information in an array. | |
37 | * | |
38 | * @return array|string response body | |
39 | */ | |
f211e417 V |
40 | protected function getApiResponseBody() |
41 | { | |
18e67967 A |
42 | if ($this->debug !== true) { |
43 | return $this->getMessage(); | |
44 | } | |
45 | return [ | |
46 | 'message' => $this->getMessage(), | |
53054b2b | 47 | 'stacktrace' => get_class($this) . ': ' . $this->getTraceAsString() |
18e67967 A |
48 | ]; |
49 | } | |
50 | ||
51 | /** | |
52 | * Build the Response object to return. | |
53 | * | |
54 | * @param int $code HTTP status. | |
55 | * | |
56 | * @return Response with status + body. | |
57 | */ | |
58 | protected function buildApiResponse($code) | |
59 | { | |
60 | $style = $this->debug ? JSON_PRETTY_PRINT : null; | |
61 | return $this->response->withJson($this->getApiResponseBody(), $code, $style); | |
62 | } | |
63 | ||
64 | /** | |
65 | * @param Response $response | |
66 | */ | |
67 | public function setResponse($response) | |
68 | { | |
69 | $this->response = $response; | |
70 | } | |
71 | ||
72 | /** | |
73 | * @param bool $debug | |
74 | */ | |
75 | public function setDebug($debug) | |
76 | { | |
77 | $this->debug = $debug; | |
78 | } | |
79 | } |