ExceptionCaster.php 16 KB

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