aboutsummaryrefslogblamecommitdiffhomepage
path: root/application/api/exceptions/ApiException.php
blob: d6b66323279f86e4dd886c0477f9c41e4f67a9bb (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12











                                                                                              

                                              















                                               
                                              







                                                                       

                                           





































                                                                                     
<?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;
    }
}