ApiException.php 1.7 KB

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