blob: baa7a180b0597284d24d58ee0bdc2b488d378213 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\VarDumper\Caster;
13
14use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext;
15use Symfony\Component\VarDumper\Cloner\Stub;
16use Symfony\Component\VarDumper\Exception\ThrowingCasterException;
17
18/**
19 * Casts common Exception classes to array representation.
20 *
21 * @author Nicolas Grekas <p@tchwork.com>
22 *
23 * @final
24 */
25class ExceptionCaster
26{
27 public static $srcContext = 1;
28 public static $traceArgs = true;
29 public static $errorTypes = [
30 \E_DEPRECATED => 'E_DEPRECATED',
31 \E_USER_DEPRECATED => 'E_USER_DEPRECATED',
32 \E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR',
33 \E_ERROR => 'E_ERROR',
34 \E_WARNING => 'E_WARNING',
35 \E_PARSE => 'E_PARSE',
36 \E_NOTICE => 'E_NOTICE',
37 \E_CORE_ERROR => 'E_CORE_ERROR',
38 \E_CORE_WARNING => 'E_CORE_WARNING',
39 \E_COMPILE_ERROR => 'E_COMPILE_ERROR',
40 \E_COMPILE_WARNING => 'E_COMPILE_WARNING',
41 \E_USER_ERROR => 'E_USER_ERROR',
42 \E_USER_WARNING => 'E_USER_WARNING',
43 \E_USER_NOTICE => 'E_USER_NOTICE',
44 \E_STRICT => 'E_STRICT',
45 ];
46
47 private static $framesCache = [];
48
49 public static function castError(\Error $e, array $a, Stub $stub, bool $isNested, int $filter = 0)
50 {
51 return self::filterExceptionArray($stub->class, $a, "\0Error\0", $filter);
52 }
53
54 public static function castException(\Exception $e, array $a, Stub $stub, bool $isNested, int $filter = 0)
55 {
56 return self::filterExceptionArray($stub->class, $a, "\0Exception\0", $filter);
57 }
58
59 public static function castErrorException(\ErrorException $e, array $a, Stub $stub, bool $isNested)
60 {
61 if (isset($a[$s = Caster::PREFIX_PROTECTED.'severity'], self::$errorTypes[$a[$s]])) {
62 $a[$s] = new ConstStub(self::$errorTypes[$a[$s]], $a[$s]);
63 }
64
65 return $a;
66 }
67
68 public static function castThrowingCasterException(ThrowingCasterException $e, array $a, Stub $stub, bool $isNested)
69 {
70 $trace = Caster::PREFIX_VIRTUAL.'trace';
71 $prefix = Caster::PREFIX_PROTECTED;
72 $xPrefix = "\0Exception\0";
73
74 if (isset($a[$xPrefix.'previous'], $a[$trace]) && $a[$xPrefix.'previous'] instanceof \Exception) {
75 $b = (array) $a[$xPrefix.'previous'];
76 $class = get_debug_type($a[$xPrefix.'previous']);
77 self::traceUnshift($b[$xPrefix.'trace'], $class, $b[$prefix.'file'], $b[$prefix.'line']);
78 $a[$trace] = new TraceStub($b[$xPrefix.'trace'], false, 0, -\count($a[$trace]->value));
79 }
80
81 unset($a[$xPrefix.'previous'], $a[$prefix.'code'], $a[$prefix.'file'], $a[$prefix.'line']);
82
83 return $a;
84 }
85
86 public static function castSilencedErrorContext(SilencedErrorContext $e, array $a, Stub $stub, bool $isNested)
87 {
88 $sPrefix = "\0".SilencedErrorContext::class."\0";
89
90 if (!isset($a[$s = $sPrefix.'severity'])) {
91 return $a;
92 }
93
94 if (isset(self::$errorTypes[$a[$s]])) {
95 $a[$s] = new ConstStub(self::$errorTypes[$a[$s]], $a[$s]);
96 }
97
98 $trace = [[
99 'file' => $a[$sPrefix.'file'],
100 'line' => $a[$sPrefix.'line'],
101 ]];
102
103 if (isset($a[$sPrefix.'trace'])) {
104 $trace = array_merge($trace, $a[$sPrefix.'trace']);
105 }
106
107 unset($a[$sPrefix.'file'], $a[$sPrefix.'line'], $a[$sPrefix.'trace']);
108 $a[Caster::PREFIX_VIRTUAL.'trace'] = new TraceStub($trace, self::$traceArgs);
109
110 return $a;
111 }
112
113 public static function castTraceStub(TraceStub $trace, array $a, Stub $stub, bool $isNested)
114 {
115 if (!$isNested) {
116 return $a;
117 }
118 $stub->class = '';
119 $stub->handle = 0;
120 $frames = $trace->value;
121 $prefix = Caster::PREFIX_VIRTUAL;
122
123 $a = [];
124 $j = \count($frames);
125 if (0 > $i = $trace->sliceOffset) {
126 $i = max(0, $j + $i);
127 }
128 if (!isset($trace->value[$i])) {
129 return [];
130 }
131 $lastCall = isset($frames[$i]['function']) ? (isset($frames[$i]['class']) ? $frames[0]['class'].$frames[$i]['type'] : '').$frames[$i]['function'].'()' : '';
132 $frames[] = ['function' => ''];
133 $collapse = false;
134
135 for ($j += $trace->numberingOffset - $i++; isset($frames[$i]); ++$i, --$j) {
136 $f = $frames[$i];
137 $call = isset($f['function']) ? (isset($f['class']) ? $f['class'].$f['type'] : '').$f['function'] : '???';
138
139 $frame = new FrameStub(
140 [
141 'object' => $f['object'] ?? null,
142 'class' => $f['class'] ?? null,
143 'type' => $f['type'] ?? null,
144 'function' => $f['function'] ?? null,
145 ] + $frames[$i - 1],
146 false,
147 true
148 );
149 $f = self::castFrameStub($frame, [], $frame, true);
150 if (isset($f[$prefix.'src'])) {
151 foreach ($f[$prefix.'src']->value as $label => $frame) {
152 if (str_starts_with($label, "\0~collapse=0")) {
153 if ($collapse) {
154 $label = substr_replace($label, '1', 11, 1);
155 } else {
156 $collapse = true;
157 }
158 }
159 $label = substr_replace($label, "title=Stack level $j.&", 2, 0);
160 }
161 $f = $frames[$i - 1];
162 if ($trace->keepArgs && !empty($f['args']) && $frame instanceof EnumStub) {
163 $frame->value['arguments'] = new ArgsStub($f['args'], $f['function'] ?? null, $f['class'] ?? null);
164 }
165 } elseif ('???' !== $lastCall) {
166 $label = new ClassStub($lastCall);
167 if (isset($label->attr['ellipsis'])) {
168 $label->attr['ellipsis'] += 2;
169 $label = substr_replace($prefix, "ellipsis-type=class&ellipsis={$label->attr['ellipsis']}&ellipsis-tail=1&title=Stack level $j.", 2, 0).$label->value.'()';
170 } else {
171 $label = substr_replace($prefix, "title=Stack level $j.", 2, 0).$label->value.'()';
172 }
173 } else {
174 $label = substr_replace($prefix, "title=Stack level $j.", 2, 0).$lastCall;
175 }
176 $a[substr_replace($label, sprintf('separator=%s&', $frame instanceof EnumStub ? ' ' : ':'), 2, 0)] = $frame;
177
178 $lastCall = $call;
179 }
180 if (null !== $trace->sliceLength) {
181 $a = \array_slice($a, 0, $trace->sliceLength, true);
182 }
183
184 return $a;
185 }
186
187 public static function castFrameStub(FrameStub $frame, array $a, Stub $stub, bool $isNested)
188 {
189 if (!$isNested) {
190 return $a;
191 }
192 $f = $frame->value;
193 $prefix = Caster::PREFIX_VIRTUAL;
194
195 if (isset($f['file'], $f['line'])) {
196 $cacheKey = $f;
197 unset($cacheKey['object'], $cacheKey['args']);
198 $cacheKey[] = self::$srcContext;
199 $cacheKey = implode('-', $cacheKey);
200
201 if (isset(self::$framesCache[$cacheKey])) {
202 $a[$prefix.'src'] = self::$framesCache[$cacheKey];
203 } else {
204 if (preg_match('/\((\d+)\)(?:\([\da-f]{32}\))? : (?:eval\(\)\'d code|runtime-created function)$/', $f['file'], $match)) {
205 $f['file'] = substr($f['file'], 0, -\strlen($match[0]));
206 $f['line'] = (int) $match[1];
207 }
208 $src = $f['line'];
209 $srcKey = $f['file'];
210 $ellipsis = new LinkStub($srcKey, 0);
211 $srcAttr = 'collapse='.(int) $ellipsis->inVendor;
212 $ellipsisTail = $ellipsis->attr['ellipsis-tail'] ?? 0;
213 $ellipsis = $ellipsis->attr['ellipsis'] ?? 0;
214
215 if (is_file($f['file']) && 0 <= self::$srcContext) {
216 if (!empty($f['class']) && (is_subclass_of($f['class'], 'Twig\Template') || is_subclass_of($f['class'], 'Twig_Template')) && method_exists($f['class'], 'getDebugInfo')) {
217 $template = $f['object'] ?? unserialize(sprintf('O:%d:"%s":0:{}', \strlen($f['class']), $f['class']));
218
219 $ellipsis = 0;
220 $templateSrc = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : '');
221 $templateInfo = $template->getDebugInfo();
222 if (isset($templateInfo[$f['line']])) {
223 if (!method_exists($template, 'getSourceContext') || !is_file($templatePath = $template->getSourceContext()->getPath())) {
224 $templatePath = null;
225 }
226 if ($templateSrc) {
227 $src = self::extractSource($templateSrc, $templateInfo[$f['line']], self::$srcContext, 'twig', $templatePath, $f);
228 $srcKey = ($templatePath ?: $template->getTemplateName()).':'.$templateInfo[$f['line']];
229 }
230 }
231 }
232 if ($srcKey == $f['file']) {
233 $src = self::extractSource(file_get_contents($f['file']), $f['line'], self::$srcContext, 'php', $f['file'], $f);
234 $srcKey .= ':'.$f['line'];
235 if ($ellipsis) {
236 $ellipsis += 1 + \strlen($f['line']);
237 }
238 }
239 $srcAttr .= sprintf('&separator= &file=%s&line=%d', rawurlencode($f['file']), $f['line']);
240 } else {
241 $srcAttr .= '&separator=:';
242 }
243 $srcAttr .= $ellipsis ? '&ellipsis-type=path&ellipsis='.$ellipsis.'&ellipsis-tail='.$ellipsisTail : '';
244 self::$framesCache[$cacheKey] = $a[$prefix.'src'] = new EnumStub(["\0~$srcAttr\0$srcKey" => $src]);
245 }
246 }
247
248 unset($a[$prefix.'args'], $a[$prefix.'line'], $a[$prefix.'file']);
249 if ($frame->inTraceStub) {
250 unset($a[$prefix.'class'], $a[$prefix.'type'], $a[$prefix.'function']);
251 }
252 foreach ($a as $k => $v) {
253 if (!$v) {
254 unset($a[$k]);
255 }
256 }
257 if ($frame->keepArgs && !empty($f['args'])) {
258 $a[$prefix.'arguments'] = new ArgsStub($f['args'], $f['function'], $f['class']);
259 }
260
261 return $a;
262 }
263
264 private static function filterExceptionArray(string $xClass, array $a, string $xPrefix, int $filter): array
265 {
266 if (isset($a[$xPrefix.'trace'])) {
267 $trace = $a[$xPrefix.'trace'];
268 unset($a[$xPrefix.'trace']); // Ensures the trace is always last
269 } else {
270 $trace = [];
271 }
272
273 if (!($filter & Caster::EXCLUDE_VERBOSE) && $trace) {
274 if (isset($a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line'])) {
275 self::traceUnshift($trace, $xClass, $a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line']);
276 }
277 $a[Caster::PREFIX_VIRTUAL.'trace'] = new TraceStub($trace, self::$traceArgs);
278 }
279 if (empty($a[$xPrefix.'previous'])) {
280 unset($a[$xPrefix.'previous']);
281 }
282 unset($a[$xPrefix.'string'], $a[Caster::PREFIX_DYNAMIC.'xdebug_message'], $a[Caster::PREFIX_DYNAMIC.'__destructorException']);
283
284 if (isset($a[Caster::PREFIX_PROTECTED.'message']) && str_contains($a[Caster::PREFIX_PROTECTED.'message'], "@anonymous\0")) {
285 $a[Caster::PREFIX_PROTECTED.'message'] = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', function ($m) {
286 return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0];
287 }, $a[Caster::PREFIX_PROTECTED.'message']);
288 }
289
290 if (isset($a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line'])) {
291 $a[Caster::PREFIX_PROTECTED.'file'] = new LinkStub($a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line']);
292 }
293
294 return $a;
295 }
296
297 private static function traceUnshift(array &$trace, ?string $class, string $file, int $line): void
298 {
299 if (isset($trace[0]['file'], $trace[0]['line']) && $trace[0]['file'] === $file && $trace[0]['line'] === $line) {
300 return;
301 }
302 array_unshift($trace, [
303 'function' => $class ? 'new '.$class : null,
304 'file' => $file,
305 'line' => $line,
306 ]);
307 }
308
309 private static function extractSource(string $srcLines, int $line, int $srcContext, string $lang, ?string $file, array $frame): EnumStub
310 {
311 $srcLines = explode("\n", $srcLines);
312 $src = [];
313
314 for ($i = $line - 1 - $srcContext; $i <= $line - 1 + $srcContext; ++$i) {
315 $src[] = ($srcLines[$i] ?? '')."\n";
316 }
317
318 if ($frame['function'] ?? false) {
319 $stub = new CutStub(new \stdClass());
320 $stub->class = (isset($frame['class']) ? $frame['class'].$frame['type'] : '').$frame['function'];
321 $stub->type = Stub::TYPE_OBJECT;
322 $stub->attr['cut_hash'] = true;
323 $stub->attr['file'] = $frame['file'];
324 $stub->attr['line'] = $frame['line'];
325
326 try {
327 $caller = isset($frame['class']) ? new \ReflectionMethod($frame['class'], $frame['function']) : new \ReflectionFunction($frame['function']);
328 $stub->class .= ReflectionCaster::getSignature(ReflectionCaster::castFunctionAbstract($caller, [], $stub, true, Caster::EXCLUDE_VERBOSE));
329
330 if ($f = $caller->getFileName()) {
331 $stub->attr['file'] = $f;
332 $stub->attr['line'] = $caller->getStartLine();
333 }
334 } catch (\ReflectionException $e) {
335 // ignore fake class/function
336 }
337
338 $srcLines = ["\0~separator=\0" => $stub];
339 } else {
340 $stub = null;
341 $srcLines = [];
342 }
343
344 $ltrim = 0;
345 do {
346 $pad = null;
347 for ($i = $srcContext << 1; $i >= 0; --$i) {
348 if (isset($src[$i][$ltrim]) && "\r" !== ($c = $src[$i][$ltrim]) && "\n" !== $c) {
349 if (null === $pad) {
350 $pad = $c;
351 }
352 if ((' ' !== $c && "\t" !== $c) || $pad !== $c) {
353 break;
354 }
355 }
356 }
357 ++$ltrim;
358 } while (0 > $i && null !== $pad);
359
360 --$ltrim;
361
362 foreach ($src as $i => $c) {
363 if ($ltrim) {
364 $c = isset($c[$ltrim]) && "\r" !== $c[$ltrim] ? substr($c, $ltrim) : ltrim($c, " \t");
365 }
366 $c = substr($c, 0, -1);
367 if ($i !== $srcContext) {
368 $c = new ConstStub('default', $c);
369 } else {
370 $c = new ConstStub($c, $stub ? 'in '.$stub->class : '');
371 if (null !== $file) {
372 $c->attr['file'] = $file;
373 $c->attr['line'] = $line;
374 }
375 }
376 $c->attr['lang'] = $lang;
377 $srcLines[sprintf("\0~separator=› &%d\0", $i + $line - $srcContext)] = $c;
378 }
379
380 return new EnumStub($srcLines);
381 }
382}