aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/api/exceptions/ApiException.php
diff options
context:
space:
mode:
authorArthurHoaro <arthur@hoa.ro>2016-12-15 10:13:00 +0100
committerArthurHoaro <arthur@hoa.ro>2016-12-15 10:36:00 +0100
commit18e6796726d73d7dc90ecdd16c181493941f5487 (patch)
tree17159284be5072b505eead31efdc064b6d5a35d0 /application/api/exceptions/ApiException.php
parent423ab02846286f94276d21e38ca1e296646618bf (diff)
downloadShaarli-18e6796726d73d7dc90ecdd16c181493941f5487.tar.gz
Shaarli-18e6796726d73d7dc90ecdd16c181493941f5487.tar.zst
Shaarli-18e6796726d73d7dc90ecdd16c181493941f5487.zip
REST API structure using Slim framework
* REST API routes are handle by Slim. * Every API controller go through ApiMiddleware which handles security. * First service implemented `/info`, for tests purpose.
Diffstat (limited to 'application/api/exceptions/ApiException.php')
-rw-r--r--application/api/exceptions/ApiException.php77
1 files changed, 77 insertions, 0 deletions
diff --git a/application/api/exceptions/ApiException.php b/application/api/exceptions/ApiException.php
new file mode 100644
index 00000000..c8490e0c
--- /dev/null
+++ b/application/api/exceptions/ApiException.php
@@ -0,0 +1,77 @@
1<?php
2
3namespace Shaarli\Api\Exceptions;
4
5use 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 */
13abstract class ApiException extends \Exception {
14
15 /**
16 * @var Response instance from Slim.
17 */
18 protected $response;
19
20 /**
21 * @var bool Debug mode enabled/disabled.
22 */
23 protected $debug;
24
25 /**
26 * Build the final response.
27 *
28 * @return Response Final response to give.
29 */
30 public abstract function getApiResponse();
31
32 /**
33 * Creates ApiResponse body.
34 * In production mode, it will only return the exception message,
35 * but in dev mode, it includes additional information in an array.
36 *
37 * @return array|string response body
38 */
39 protected function getApiResponseBody() {
40 if ($this->debug !== true) {
41 return $this->getMessage();
42 }
43 return [
44 'message' => $this->getMessage(),
45 'stacktrace' => get_class($this) .': '. $this->getTraceAsString()
46 ];
47 }
48
49 /**
50 * Build the Response object to return.
51 *
52 * @param int $code HTTP status.
53 *
54 * @return Response with status + body.
55 */
56 protected function buildApiResponse($code)
57 {
58 $style = $this->debug ? JSON_PRETTY_PRINT : null;
59 return $this->response->withJson($this->getApiResponseBody(), $code, $style);
60 }
61
62 /**
63 * @param Response $response
64 */
65 public function setResponse($response)
66 {
67 $this->response = $response;
68 }
69
70 /**
71 * @param bool $debug
72 */
73 public function setDebug($debug)
74 {
75 $this->debug = $debug;
76 }
77}