1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Whoops - php errors for cool kids |
4
|
|
|
* @author Filipe Dobreira <http://github.com/filp> |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
namespace Whoops\Handler; |
8
|
|
|
|
9
|
|
|
use Whoops\Exception\Formatter; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Catches an exception and converts it to a JSON |
13
|
|
|
* response. Additionally can also return exception |
14
|
|
|
* frames for consumption by an API. |
15
|
|
|
*/ |
16
|
|
|
class JsonResponseHandler extends Handler |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var bool |
20
|
|
|
*/ |
21
|
|
|
private $returnFrames = false; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var bool |
25
|
|
|
*/ |
26
|
|
|
private $onlyForAjaxRequests = false; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param bool|null $returnFrames |
30
|
|
|
* @return bool|$this |
31
|
|
|
*/ |
32
|
2 |
View Code Duplication |
public function addTraceToOutput($returnFrames = null) |
|
|
|
|
33
|
1 |
|
{ |
34
|
2 |
|
if (func_num_args() == 0) { |
35
|
2 |
|
return $this->returnFrames; |
36
|
|
|
} |
37
|
|
|
|
38
|
2 |
|
$this->returnFrames = (bool) $returnFrames; |
39
|
2 |
|
return $this; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param bool|null $onlyForAjaxRequests |
44
|
|
|
* @return null|bool |
45
|
|
|
*/ |
46
|
|
|
public function onlyForAjaxRequests($onlyForAjaxRequests = null) |
47
|
|
|
{ |
48
|
|
|
if (func_num_args() == 0) { |
49
|
|
|
return $this->onlyForAjaxRequests; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$this->onlyForAjaxRequests = (bool) $onlyForAjaxRequests; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Check, if possible, that this execution was triggered by an AJAX request. |
57
|
|
|
* |
58
|
|
|
* @return bool |
59
|
|
|
*/ |
60
|
|
|
private function isAjaxRequest() |
61
|
|
|
{ |
62
|
|
|
return ( |
63
|
|
|
!empty($_SERVER['HTTP_X_REQUESTED_WITH']) |
64
|
|
|
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @return int |
69
|
|
|
*/ |
70
|
2 |
|
public function handle() |
71
|
|
|
{ |
72
|
2 |
|
if ($this->onlyForAjaxRequests() && !$this->isAjaxRequest()) { |
73
|
|
|
return Handler::DONE; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
$response = array( |
77
|
2 |
|
'error' => Formatter::formatExceptionAsDataArray( |
78
|
2 |
|
$this->getInspector(), |
79
|
2 |
|
$this->addTraceToOutput() |
|
|
|
|
80
|
2 |
|
), |
81
|
2 |
|
); |
82
|
|
|
|
83
|
2 |
|
if (\Whoops\Util\Misc::canSendHeaders()) { |
84
|
|
|
header('Content-Type: application/json'); |
85
|
|
|
} |
86
|
|
|
|
87
|
2 |
|
echo json_encode($response); |
88
|
2 |
|
return Handler::QUIT; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.