]> BookStack Code Mirror - bookstack/blob - app/Exceptions/NotifyException.php
Refactor notify exception to clean up api exception handling
[bookstack] / app / Exceptions / NotifyException.php
1 <?php
2
3 namespace BookStack\Exceptions;
4
5 use Exception;
6 use Illuminate\Contracts\Support\Responsable;
7 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
8
9 class NotifyException extends Exception implements Responsable, HttpExceptionInterface
10 {
11     public $message;
12     public $redirectLocation;
13     protected $status;
14
15     /**
16      * @var array<mixed>
17      */
18     protected array $headers = [];
19
20     public function __construct(string $message, string $redirectLocation = '/', int $status = 500)
21     {
22         $this->message = $message;
23         $this->redirectLocation = $redirectLocation;
24         $this->status = $status;
25
26         if ($status >= 300 && $status < 400) {
27             // add redirect header only when a matching HTTP status is given
28             $this->headers = ['location' => $redirectLocation];
29         }
30
31         parent::__construct();
32     }
33
34     /**
35      * Get the desired HTTP status code for this exception.
36      *
37      * {@inheritdoc}
38      */
39     public function getStatusCode(): int
40     {
41         return $this->status;
42     }
43
44     /**
45      * Get the desired HTTP headers for this exception.
46      *
47      * {@inheritdoc}
48      */
49     public function getHeaders(): array
50     {
51         return $this->headers;
52     }
53
54     /**
55      * @param array<mixed> $headers
56      */
57     public function setHeaders(array $headers): void
58     {
59         $this->headers = $headers;
60     }
61
62     /**
63      * Send the response for this type of exception.
64      *
65      * {@inheritdoc}
66      */
67     public function toResponse($request)
68     {
69         $message = $this->getMessage();
70
71         // Front-end JSON handling. API-side handling managed via handler.
72         if ($request->wantsJson()) {
73             return response()->json(['error' => $message], $this->getStatusCode());
74         }
75
76         if (!empty($message)) {
77             session()->flash('error', $message);
78         }
79
80         return redirect($this->redirectLocation);
81     }
82 }