|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the BEAR.Sunday package |
|
4
|
|
|
* |
|
5
|
|
|
* @license http://opensource.org/licenses/MIT MIT |
|
6
|
|
|
*/ |
|
7
|
|
|
namespace BEAR\Sunday\Provide\Error; |
|
8
|
|
|
|
|
9
|
|
|
use BEAR\Resource\Code; |
|
10
|
|
|
use BEAR\Resource\Exception\BadRequestException as BadRequest; |
|
11
|
|
|
use BEAR\Resource\Exception\ResourceNotFoundException as NotFound; |
|
12
|
|
|
use BEAR\Resource\Exception\ServerErrorException as ServerError; |
|
13
|
|
|
use BEAR\Sunday\Extension\Error\ErrorInterface; |
|
14
|
|
|
use BEAR\Sunday\Extension\Router\RouterMatch as Request; |
|
15
|
|
|
use BEAR\Sunday\Extension\Transfer\TransferInterface; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Vnd.Error media type error |
|
19
|
|
|
* |
|
20
|
|
|
* @see https://github.com/blongden/vnd.error |
|
21
|
|
|
*/ |
|
22
|
|
|
final class VndError implements ErrorInterface |
|
23
|
|
|
{ |
|
24
|
|
|
/** |
|
25
|
|
|
* @var string |
|
26
|
|
|
*/ |
|
27
|
|
|
const CONTENT_TYPE = 'application/vnd.error+json'; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @var TransferInterface |
|
31
|
|
|
*/ |
|
32
|
|
|
private $transfer; |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @var ErrorPage |
|
36
|
|
|
*/ |
|
37
|
|
|
private $errorPage; |
|
38
|
|
|
|
|
39
|
7 |
|
public function __construct(TransferInterface $transfer) |
|
40
|
|
|
{ |
|
41
|
7 |
|
$this->transfer = $transfer; |
|
42
|
|
|
$this->errorPage = new ErrorPage; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* {@inheritdoc} |
|
47
|
|
|
*/ |
|
48
|
5 |
|
public function handle(\Exception $e, Request $request) |
|
49
|
|
|
{ |
|
50
|
|
|
if ($this->isCodeExists($e)) { |
|
51
|
|
|
$this->errorPage->code = $e->getCode(); |
|
52
|
|
|
$this->errorPage->body = ['message' => (new Code)->statusText[$this->errorPage->code]]; |
|
53
|
|
|
|
|
54
|
3 |
|
return $this; |
|
55
|
|
|
} |
|
56
|
2 |
|
$this->errorPage->code = 500; |
|
57
|
2 |
|
$this->errorPage->body = ['message' => '500 Server Error']; |
|
58
|
|
|
error_log($request); |
|
59
|
|
|
error_log($e); |
|
60
|
|
|
|
|
61
|
2 |
|
return $this; |
|
62
|
5 |
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* {@inheritdoc} |
|
66
|
|
|
*/ |
|
67
|
5 |
|
public function transfer() |
|
68
|
|
|
{ |
|
69
|
5 |
|
$this->errorPage->headers['content-type'] = self::CONTENT_TYPE; |
|
70
|
|
|
$this->transfer->__invoke($this->errorPage, []); |
|
71
|
5 |
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* @param \Exception $e |
|
75
|
|
|
* |
|
76
|
|
|
* @return bool |
|
77
|
|
|
*/ |
|
78
|
5 |
|
private function isCodeExists(\Exception $e) |
|
79
|
|
|
{ |
|
80
|
5 |
|
if (! ($e instanceof NotFound || $e instanceof BadRequest || $e instanceof ServerError)) { |
|
81
|
1 |
|
return false; |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
return array_key_exists($e->getCode(), (new Code)->statusText); |
|
85
|
5 |
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|