]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/api/exceptions/ApiException.php
lint: apply phpcbf to application/
[github/shaarli/Shaarli.git] / application / api / exceptions / ApiException.php
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 */
13 abstract class ApiException extends \Exception
14 {
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 */
31 abstract public function getApiResponse();
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 */
40 protected function getApiResponseBody()
41 {
42 if ($this->debug !== true) {
43 return $this->getMessage();
44 }
45 return [
46 'message' => $this->getMessage(),
47 'stacktrace' => get_class($this) .': '. $this->getTraceAsString()
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 }