ApiException.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. /**
  13. * @var Response instance from Slim.
  14. */
  15. protected $response;
  16. /**
  17. * @var bool Debug mode enabled/disabled.
  18. */
  19. protected $debug;
  20. /**
  21. * Build the final response.
  22. *
  23. * @return Response Final response to give.
  24. */
  25. abstract public function getApiResponse();
  26. /**
  27. * Creates ApiResponse body.
  28. * In production mode, it will only return the exception message,
  29. * but in dev mode, it includes additional information in an array.
  30. *
  31. * @return array|string response body
  32. */
  33. protected function getApiResponseBody()
  34. {
  35. if ($this->debug !== true) {
  36. return $this->getMessage();
  37. }
  38. return [
  39. 'message' => $this->getMessage(),
  40. 'stacktrace' => get_class($this) .': '. $this->getTraceAsString()
  41. ];
  42. }
  43. /**
  44. * Build the Response object to return.
  45. *
  46. * @param int $code HTTP status.
  47. *
  48. * @return Response with status + body.
  49. */
  50. protected function buildApiResponse($code)
  51. {
  52. $style = $this->debug ? JSON_PRETTY_PRINT : null;
  53. return $this->response->withJson($this->getApiResponseBody(), $code, $style);
  54. }
  55. /**
  56. * @param Response $response
  57. */
  58. public function setResponse($response)
  59. {
  60. $this->response = $response;
  61. }
  62. /**
  63. * @param bool $debug
  64. */
  65. public function setDebug($debug)
  66. {
  67. $this->debug = $debug;
  68. }
  69. }