12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace Shaarli\Api\Exceptions;
- use Slim\Http\Response;
- /**
- * Abstract class ApiException
- *
- * Parent Exception related to the API, able to generate a valid Response (ResponseInterface).
- * Also can include various information in debug mode.
- */
- abstract class ApiException extends \Exception
- {
- /**
- * @var Response instance from Slim.
- */
- protected $response;
- /**
- * @var bool Debug mode enabled/disabled.
- */
- protected $debug;
- /**
- * Build the final response.
- *
- * @return Response Final response to give.
- */
- abstract public function getApiResponse();
- /**
- * Creates ApiResponse body.
- * In production mode, it will only return the exception message,
- * but in dev mode, it includes additional information in an array.
- *
- * @return array|string response body
- */
- protected function getApiResponseBody()
- {
- if ($this->debug !== true) {
- return $this->getMessage();
- }
- return [
- 'message' => $this->getMessage(),
- 'stacktrace' => get_class($this) .': '. $this->getTraceAsString()
- ];
- }
- /**
- * Build the Response object to return.
- *
- * @param int $code HTTP status.
- *
- * @return Response with status + body.
- */
- protected function buildApiResponse($code)
- {
- $style = $this->debug ? JSON_PRETTY_PRINT : null;
- return $this->response->withJson($this->getApiResponseBody(), $code, $style);
- }
- /**
- * @param Response $response
- */
- public function setResponse($response)
- {
- $this->response = $response;
- }
- /**
- * @param bool $debug
- */
- public function setDebug($debug)
- {
- $this->debug = $debug;
- }
- }
|