BookStack/app/Exceptions/NotifyException.php

83 lines
1.9 KiB
PHP
Raw Normal View History

2021-06-26 11:23:15 -04:00
<?php
namespace BookStack\Exceptions;
2015-09-04 12:16:58 -04:00
use Exception;
use Illuminate\Contracts\Support\Responsable;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
2015-09-04 12:16:58 -04:00
class NotifyException extends Exception implements Responsable, HttpExceptionInterface
{
2015-09-04 12:16:58 -04:00
public $message;
public $redirectLocation;
protected $status;
2015-09-04 12:16:58 -04:00
/**
* @var array<mixed>
*/
protected array $headers = [];
public function __construct(string $message, string $redirectLocation = '/', int $status = 500)
2015-09-04 12:16:58 -04:00
{
$this->message = $message;
$this->redirectLocation = $redirectLocation;
$this->status = $status;
if ($status >= 300 && $status < 400) {
// add redirect header only when a matching HTTP status is given
$this->headers = ['location' => $redirectLocation];
}
2015-09-04 12:16:58 -04:00
parent::__construct();
}
/**
* Get the desired HTTP status code for this exception.
*
* {@inheritdoc}
*/
public function getStatusCode(): int
{
return $this->status;
}
/**
* Get the desired HTTP headers for this exception.
*
* {@inheritdoc}
*/
public function getHeaders(): array
{
return $this->headers;
}
/**
* @param array<mixed> $headers
*/
public function setHeaders(array $headers): void
{
$this->headers = $headers;
}
/**
* Send the response for this type of exception.
2021-06-26 11:23:15 -04:00
*
* {@inheritdoc}
*/
public function toResponse($request)
{
$message = $this->getMessage();
// Front-end JSON handling. API-side handling managed via handler.
if ($request->wantsJson()) {
return response()->json(['error' => $message], $this->getStatusCode());
}
if (!empty($message)) {
session()->flash('error', $message);
}
return redirect($this->redirectLocation);
}
}