-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathExceptionHandler.php
More file actions
226 lines (188 loc) · 6.78 KB
/
ExceptionHandler.php
File metadata and controls
226 lines (188 loc) · 6.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Debug;
use Closure;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Paths;
use Throwable;
/**
* @see \CodeIgniter\Debug\ExceptionHandlerTest
*/
final class ExceptionHandler extends BaseExceptionHandler implements ExceptionHandlerInterface
{
use ResponseTrait;
/**
* ResponseTrait needs this.
*/
private ?RequestInterface $request = null;
/**
* ResponseTrait needs this.
*/
private ?ResponseInterface $response = null;
/**
* Determines the correct way to display the error.
*
* @param CLIRequest|IncomingRequest $request
*/
public function handle(
Throwable $exception,
RequestInterface $request,
ResponseInterface $response,
int $statusCode,
int $exitCode,
): void {
// ResponseTrait needs these properties.
$this->request = $request;
$this->response = $response;
if ($request instanceof IncomingRequest) {
try {
$response->setStatusCode($statusCode);
} catch (HTTPException) {
// Workaround for invalid HTTP status code.
$statusCode = 500;
$response->setStatusCode($statusCode);
}
if (! headers_sent()) {
header(
sprintf(
'HTTP/%s %s %s',
$request->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase(),
),
true,
$statusCode,
);
}
// Handles non-HTML requests.
if (! str_contains($request->getHeaderLine('accept'), 'text/html')) {
// If display_errors is enabled, shows the error details.
$data = $this->isDisplayErrorsEnabled()
? $this->collectVars($exception, $statusCode)
: '';
// Sanitize data to remove non-JSON-serializable values (resources, closures)
// before formatting for API responses (JSON, XML, etc.)
if ($data !== '') {
$data = $this->sanitizeData($data);
}
$this->respond($data, $statusCode)->send();
if (ENVIRONMENT !== 'testing') {
// @codeCoverageIgnoreStart
exit($exitCode);
// @codeCoverageIgnoreEnd
}
return;
}
}
// Determine possible directories of error views
$addPath = ($request instanceof IncomingRequest ? 'html' : 'cli') . DIRECTORY_SEPARATOR;
$path = $this->viewPath . $addPath;
$altPath = rtrim((new Paths())->viewDirectory, '\\/ ')
. DIRECTORY_SEPARATOR . 'errors' . DIRECTORY_SEPARATOR . $addPath;
// Determine the views
$view = $this->determineView($exception, $path, $statusCode);
$altView = $this->determineView($exception, $altPath, $statusCode);
// Check if the view exists
$viewFile = null;
if (is_file($path . $view)) {
$viewFile = $path . $view;
} elseif (is_file($altPath . $altView)) {
$viewFile = $altPath . $altView;
}
// Displays the HTML or CLI error code.
$this->render($exception, $statusCode, $viewFile);
if (ENVIRONMENT !== 'testing') {
// @codeCoverageIgnoreStart
exit($exitCode);
// @codeCoverageIgnoreEnd
}
}
/**
* Determines the view to display based on the exception thrown, HTTP status
* code, whether an HTTP or CLI request, etc.
*
* @return string The filename of the view file to use
*/
protected function determineView(
Throwable $exception,
string $templatePath,
int $statusCode = 500,
): string {
// Production environments should have a custom exception file.
$view = 'production.php';
if ($this->isDisplayErrorsEnabled()) {
// If display_errors is enabled, shows the error details.
$view = 'error_exception.php';
}
// 404 Errors
if ($exception instanceof PageNotFoundException) {
return 'error_404.php';
}
$templatePath = rtrim($templatePath, '\\/ ') . DIRECTORY_SEPARATOR;
// Allow for custom views based upon the status code
if (is_file($templatePath . 'error_' . $statusCode . '.php')) {
return 'error_' . $statusCode . '.php';
}
return $view;
}
private function isDisplayErrorsEnabled(): bool
{
return in_array(
strtolower(ini_get('display_errors')),
['1', 'true', 'on', 'yes'],
true,
);
}
/**
* Sanitizes data to remove non-JSON-serializable values like resources and closures.
* This is necessary for API responses that need to be JSON/XML encoded.
*
* @param array<int, bool> $seen Used internally to prevent infinite recursion
*/
private function sanitizeData(mixed $data, array &$seen = []): mixed
{
$type = gettype($data);
switch ($type) {
case 'resource':
case 'resource (closed)':
return '[Resource #' . (int) $data . ']';
case 'array':
$result = [];
foreach ($data as $key => $value) {
$result[$key] = $this->sanitizeData($value, $seen);
}
return $result;
case 'object':
$oid = spl_object_id($data);
if (isset($seen[$oid])) {
return '[' . $data::class . ' Object *RECURSION*]';
}
$seen[$oid] = true;
if ($data instanceof Closure) {
return '[Closure]';
}
$result = [];
foreach ((array) $data as $key => $value) {
$cleanKey = preg_replace('/^\x00.*\x00/', '', (string) $key);
$result[$cleanKey] = $this->sanitizeData($value, $seen);
}
return $result;
default:
return $data;
}
}
}