DumpDataCollector.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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\HttpKernel\DataCollector;
  11. use Symfony\Component\ErrorHandler\ErrorRenderer\FileLinkFormatter;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Stopwatch\Stopwatch;
  16. use Symfony\Component\VarDumper\Cloner\Data;
  17. use Symfony\Component\VarDumper\Cloner\VarCloner;
  18. use Symfony\Component\VarDumper\Dumper\CliDumper;
  19. use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider;
  20. use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
  21. use Symfony\Component\VarDumper\Dumper\HtmlDumper;
  22. use Symfony\Component\VarDumper\Server\Connection;
  23. /**
  24. * @author Nicolas Grekas <p@tchwork.com>
  25. *
  26. * @final
  27. */
  28. class DumpDataCollector extends DataCollector implements DataDumperInterface
  29. {
  30. private string|FileLinkFormatter|false $fileLinkFormat;
  31. private int $dataCount = 0;
  32. private bool $isCollected = true;
  33. private int $clonesCount = 0;
  34. private int $clonesIndex = 0;
  35. private array $rootRefs;
  36. private string $charset;
  37. private mixed $sourceContextProvider;
  38. private bool $webMode;
  39. public function __construct(
  40. private ?Stopwatch $stopwatch = null,
  41. string|FileLinkFormatter|null $fileLinkFormat = null,
  42. ?string $charset = null,
  43. private ?RequestStack $requestStack = null,
  44. private DataDumperInterface|Connection|null $dumper = null,
  45. ?bool $webMode = null,
  46. ) {
  47. $fileLinkFormat = $fileLinkFormat ?: \ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
  48. $this->fileLinkFormat = $fileLinkFormat instanceof FileLinkFormatter && false === $fileLinkFormat->format('', 0) ? false : $fileLinkFormat;
  49. $this->charset = $charset ?: \ini_get('php.output_encoding') ?: \ini_get('default_charset') ?: 'UTF-8';
  50. $this->webMode = $webMode ?? !\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true);
  51. // All clones share these properties by reference:
  52. $this->rootRefs = [
  53. &$this->data,
  54. &$this->dataCount,
  55. &$this->isCollected,
  56. &$this->clonesCount,
  57. ];
  58. $this->sourceContextProvider = $dumper instanceof Connection && isset($dumper->getContextProviders()['source']) ? $dumper->getContextProviders()['source'] : new SourceContextProvider($this->charset);
  59. }
  60. public function __clone()
  61. {
  62. $this->clonesIndex = ++$this->clonesCount;
  63. }
  64. public function dump(Data $data): ?string
  65. {
  66. $this->stopwatch?->start('dump');
  67. ['name' => $name, 'file' => $file, 'line' => $line, 'file_excerpt' => $fileExcerpt] = $this->sourceContextProvider->getContext();
  68. if (!$this->dumper || $this->dumper instanceof Connection && !$this->dumper->write($data)) {
  69. $this->isCollected = false;
  70. }
  71. $context = $data->getContext();
  72. $label = $context['label'] ?? '';
  73. unset($context['label']);
  74. $data = $data->withContext($context);
  75. if ($this->dumper && !$this->dumper instanceof Connection) {
  76. $this->doDump($this->dumper, $data, $name, $file, $line, $label);
  77. }
  78. if (!$this->dataCount) {
  79. $this->data = [];
  80. }
  81. $this->data[] = compact('data', 'name', 'file', 'line', 'fileExcerpt', 'label');
  82. ++$this->dataCount;
  83. $this->stopwatch?->stop('dump');
  84. return null;
  85. }
  86. public function collect(Request $request, Response $response, ?\Throwable $exception = null): void
  87. {
  88. if (!$this->dataCount) {
  89. $this->data = [];
  90. }
  91. // Sub-requests and programmatic calls stay in the collected profile.
  92. if ($this->dumper || ($this->requestStack && $this->requestStack->getMainRequest() !== $request) || $request->isXmlHttpRequest() || $request->headers->has('Origin')) {
  93. return;
  94. }
  95. // In all other conditions that remove the web debug toolbar, dumps are written on the output.
  96. if (!$this->requestStack
  97. || !$response->headers->has('X-Debug-Token')
  98. || $response->isRedirection()
  99. || ($response->headers->has('Content-Type') && !str_contains($response->headers->get('Content-Type') ?? '', 'html'))
  100. || 'html' !== $request->getRequestFormat()
  101. || false === strripos($response->getContent(), '</body>')
  102. ) {
  103. if ($response->headers->has('Content-Type') && str_contains($response->headers->get('Content-Type') ?? '', 'html')) {
  104. $dumper = new HtmlDumper('php://output', $this->charset);
  105. } else {
  106. $dumper = new CliDumper('php://output', $this->charset);
  107. }
  108. $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
  109. foreach ($this->data as $dump) {
  110. $this->doDump($dumper, $dump['data'], $dump['name'], $dump['file'], $dump['line'], $dump['label'] ?? '');
  111. }
  112. }
  113. }
  114. public function reset(): void
  115. {
  116. $this->stopwatch?->reset();
  117. parent::reset();
  118. $this->dataCount = 0;
  119. $this->isCollected = true;
  120. $this->clonesCount = 0;
  121. $this->clonesIndex = 0;
  122. }
  123. /**
  124. * @internal
  125. */
  126. public function __sleep(): array
  127. {
  128. if (!$this->dataCount) {
  129. $this->data = [];
  130. }
  131. if ($this->clonesCount !== $this->clonesIndex) {
  132. return [];
  133. }
  134. $this->data[] = $this->fileLinkFormat;
  135. $this->data[] = $this->charset;
  136. $this->dataCount = 0;
  137. $this->isCollected = true;
  138. return parent::__sleep();
  139. }
  140. /**
  141. * @internal
  142. */
  143. public function __wakeup(): void
  144. {
  145. parent::__wakeup();
  146. $charset = array_pop($this->data);
  147. $fileLinkFormat = array_pop($this->data);
  148. $this->dataCount = \count($this->data);
  149. foreach ($this->data as $dump) {
  150. if (!\is_string($dump['name']) || !\is_string($dump['file']) || !\is_int($dump['line'])) {
  151. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  152. }
  153. }
  154. self::__construct($this->stopwatch ?? null, \is_string($fileLinkFormat) || $fileLinkFormat instanceof FileLinkFormatter ? $fileLinkFormat : null, \is_string($charset) ? $charset : null);
  155. }
  156. public function getDumpsCount(): int
  157. {
  158. return $this->dataCount;
  159. }
  160. public function getDumps(string $format, int $maxDepthLimit = -1, int $maxItemsPerDepth = -1): array
  161. {
  162. $data = fopen('php://memory', 'r+');
  163. if ('html' === $format) {
  164. $dumper = new HtmlDumper($data, $this->charset);
  165. $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
  166. } else {
  167. throw new \InvalidArgumentException(\sprintf('Invalid dump format: "%s".', $format));
  168. }
  169. $dumps = [];
  170. if (!$this->dataCount) {
  171. return $this->data = [];
  172. }
  173. foreach ($this->data as $dump) {
  174. $dumper->dump($dump['data']->withMaxDepth($maxDepthLimit)->withMaxItemsPerDepth($maxItemsPerDepth));
  175. $dump['data'] = stream_get_contents($data, -1, 0);
  176. ftruncate($data, 0);
  177. rewind($data);
  178. $dumps[] = $dump;
  179. }
  180. return $dumps;
  181. }
  182. public function getName(): string
  183. {
  184. return 'dump';
  185. }
  186. public function __destruct()
  187. {
  188. if (0 === $this->clonesCount-- && !$this->isCollected && $this->dataCount) {
  189. $this->clonesCount = 0;
  190. $this->isCollected = true;
  191. $h = headers_list();
  192. $i = \count($h);
  193. array_unshift($h, 'Content-Type: '.\ini_get('default_mimetype'));
  194. while (0 !== stripos($h[$i], 'Content-Type:')) {
  195. --$i;
  196. }
  197. if ($this->webMode) {
  198. $dumper = new HtmlDumper('php://output', $this->charset);
  199. } else {
  200. $dumper = new CliDumper('php://output', $this->charset);
  201. }
  202. $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
  203. foreach ($this->data as $i => $dump) {
  204. $this->data[$i] = null;
  205. $this->doDump($dumper, $dump['data'], $dump['name'], $dump['file'], $dump['line'], $dump['label'] ?? '');
  206. }
  207. $this->data = [];
  208. $this->dataCount = 0;
  209. }
  210. }
  211. private function doDump(DataDumperInterface $dumper, Data $data, string $name, string $file, int $line, string $label): void
  212. {
  213. if ($dumper instanceof CliDumper) {
  214. $contextDumper = function ($name, $file, $line, $fmt, $label) {
  215. $this->line = '' !== $label ? $this->style('meta', $label).' in ' : '';
  216. if ($this instanceof HtmlDumper) {
  217. if ($file) {
  218. $s = $this->style('meta', '%s');
  219. $f = strip_tags($this->style('', $file));
  220. $name = strip_tags($this->style('', $name));
  221. if ($fmt && $link = \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line)) {
  222. $name = \sprintf('<a href="%s" title="%s">'.$s.'</a>', strip_tags($this->style('', $link)), $f, $name);
  223. } else {
  224. $name = \sprintf('<abbr title="%s">'.$s.'</abbr>', $f, $name);
  225. }
  226. } else {
  227. $name = $this->style('meta', $name);
  228. }
  229. $this->line .= $name.' on line '.$this->style('meta', $line).':';
  230. } else {
  231. $this->line .= $this->style('meta', $name).' on line '.$this->style('meta', $line).':';
  232. }
  233. $this->dumpLine(0);
  234. };
  235. $contextDumper = $contextDumper->bindTo($dumper, $dumper);
  236. $contextDumper($name, $file, $line, $this->fileLinkFormat, $label);
  237. } else {
  238. $cloner = new VarCloner();
  239. $dumper->dump($cloner->cloneVar(('' !== $label ? $label.' in ' : '').$name.' on line '.$line.':'));
  240. }
  241. $dumper->dump($data);
  242. }
  243. }