These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more
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 $jsonApi = false; |
||
27 | |||
28 | /** |
||
29 | * Returns errors[[]] instead of error[] to be in compliance with the json:api spec |
||
30 | * @param bool $jsonApi Default is false |
||
31 | * @return $this |
||
32 | */ |
||
33 | public function setJsonApi($jsonApi = false) |
||
34 | { |
||
35 | $this->jsonApi = (bool) $jsonApi; |
||
36 | return $this; |
||
37 | } |
||
38 | |||
39 | /** |
||
40 | * @param bool|null $returnFrames |
||
41 | * @return bool|$this |
||
42 | */ |
||
43 | 3 | View Code Duplication | public function addTraceToOutput($returnFrames = null) |
0 ignored issues
–
show
|
|||
44 | { |
||
45 | 3 | if (func_num_args() == 0) { |
|
46 | 3 | return $this->returnFrames; |
|
47 | } |
||
48 | |||
49 | 3 | $this->returnFrames = (bool) $returnFrames; |
|
50 | 3 | return $this; |
|
51 | } |
||
52 | |||
53 | /** |
||
54 | * @return int |
||
55 | */ |
||
56 | 3 | public function handle() |
|
57 | { |
||
58 | 3 | if ($this->jsonApi === true) { |
|
59 | $response = [ |
||
60 | 'errors' => [ |
||
61 | 1 | Formatter::formatExceptionAsDataArray( |
|
62 | 1 | $this->getInspector(), |
|
63 | 1 | $this->addTraceToOutput() |
|
64 | 1 | ), |
|
65 | ] |
||
66 | 1 | ]; |
|
67 | 1 | } else { |
|
68 | $response = [ |
||
69 | 2 | 'error' => Formatter::formatExceptionAsDataArray( |
|
70 | 2 | $this->getInspector(), |
|
71 | 2 | $this->addTraceToOutput() |
|
72 | 2 | ), |
|
73 | 2 | ]; |
|
74 | } |
||
75 | |||
76 | 3 | echo json_encode($response, defined('JSON_PARTIAL_OUTPUT_ON_ERROR') ? JSON_PARTIAL_OUTPUT_ON_ERROR : 0); |
|
77 | |||
78 | 3 | return Handler::QUIT; |
|
79 | } |
||
80 | |||
81 | /** |
||
82 | * @return string |
||
83 | */ |
||
84 | public function contentType() |
||
85 | { |
||
86 | return 'application/json'; |
||
87 | } |
||
88 | } |
||
89 |
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.