DumpDataCollector.php 11 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 ?Stopwatch $stopwatch = null;
  31. private string|FileLinkFormatter|false $fileLinkFormat;
  32. private int $dataCount = 0;
  33. private bool $isCollected = true;
  34. private int $clonesCount = 0;
  35. private int $clonesIndex = 0;
  36. private array $rootRefs;
  37. private string $charset;
  38. private ?RequestStack $requestStack;
  39. private DataDumperInterface|Connection|null $dumper;
  40. private mixed $sourceContextProvider;
  41. private bool $webMode;
  42. public function __construct(?Stopwatch $stopwatch = null, string|FileLinkFormatter|null $fileLinkFormat = null, ?string $charset = null, ?RequestStack $requestStack = null, DataDumperInterface|Connection|null $dumper = null, ?bool $webMode = null)
  43. {
  44. $fileLinkFormat = $fileLinkFormat ?: \ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
  45. $this->stopwatch = $stopwatch;
  46. $this->fileLinkFormat = $fileLinkFormat instanceof FileLinkFormatter && false === $fileLinkFormat->format('', 0) ? false : $fileLinkFormat;
  47. $this->charset = $charset ?: \ini_get('php.output_encoding') ?: \ini_get('default_charset') ?: 'UTF-8';
  48. $this->requestStack = $requestStack;
  49. $this->dumper = $dumper;
  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. $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
  106. } else {
  107. $dumper = new CliDumper('php://output', $this->charset);
  108. $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
  109. }
  110. foreach ($this->data as $dump) {
  111. $this->doDump($dumper, $dump['data'], $dump['name'], $dump['file'], $dump['line'], $dump['label'] ?? '');
  112. }
  113. }
  114. }
  115. public function reset(): void
  116. {
  117. $this->stopwatch?->reset();
  118. parent::reset();
  119. $this->dataCount = 0;
  120. $this->isCollected = true;
  121. $this->clonesCount = 0;
  122. $this->clonesIndex = 0;
  123. }
  124. /**
  125. * @internal
  126. */
  127. public function __sleep(): array
  128. {
  129. if (!$this->dataCount) {
  130. $this->data = [];
  131. }
  132. if ($this->clonesCount !== $this->clonesIndex) {
  133. return [];
  134. }
  135. $this->data[] = $this->fileLinkFormat;
  136. $this->data[] = $this->charset;
  137. $this->dataCount = 0;
  138. $this->isCollected = true;
  139. return parent::__sleep();
  140. }
  141. /**
  142. * @internal
  143. */
  144. public function __wakeup(): void
  145. {
  146. parent::__wakeup();
  147. $charset = array_pop($this->data);
  148. $fileLinkFormat = array_pop($this->data);
  149. $this->dataCount = \count($this->data);
  150. foreach ($this->data as $dump) {
  151. if (!\is_string($dump['name']) || !\is_string($dump['file']) || !\is_int($dump['line'])) {
  152. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  153. }
  154. }
  155. self::__construct($this->stopwatch, \is_string($fileLinkFormat) || $fileLinkFormat instanceof FileLinkFormatter ? $fileLinkFormat : null, \is_string($charset) ? $charset : null);
  156. }
  157. public function getDumpsCount(): int
  158. {
  159. return $this->dataCount;
  160. }
  161. public function getDumps(string $format, int $maxDepthLimit = -1, int $maxItemsPerDepth = -1): array
  162. {
  163. $data = fopen('php://memory', 'r+');
  164. if ('html' === $format) {
  165. $dumper = new HtmlDumper($data, $this->charset);
  166. $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
  167. } else {
  168. throw new \InvalidArgumentException(\sprintf('Invalid dump format: "%s".', $format));
  169. }
  170. $dumps = [];
  171. if (!$this->dataCount) {
  172. return $this->data = [];
  173. }
  174. foreach ($this->data as $dump) {
  175. $dumper->dump($dump['data']->withMaxDepth($maxDepthLimit)->withMaxItemsPerDepth($maxItemsPerDepth));
  176. $dump['data'] = stream_get_contents($data, -1, 0);
  177. ftruncate($data, 0);
  178. rewind($data);
  179. $dumps[] = $dump;
  180. }
  181. return $dumps;
  182. }
  183. public function getName(): string
  184. {
  185. return 'dump';
  186. }
  187. public function __destruct()
  188. {
  189. if (0 === $this->clonesCount-- && !$this->isCollected && $this->dataCount) {
  190. $this->clonesCount = 0;
  191. $this->isCollected = true;
  192. $h = headers_list();
  193. $i = \count($h);
  194. array_unshift($h, 'Content-Type: '.\ini_get('default_mimetype'));
  195. while (0 !== stripos($h[$i], 'Content-Type:')) {
  196. --$i;
  197. }
  198. if ($this->webMode) {
  199. $dumper = new HtmlDumper('php://output', $this->charset);
  200. $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
  201. } else {
  202. $dumper = new CliDumper('php://output', $this->charset);
  203. $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
  204. }
  205. foreach ($this->data as $i => $dump) {
  206. $this->data[$i] = null;
  207. $this->doDump($dumper, $dump['data'], $dump['name'], $dump['file'], $dump['line'], $dump['label'] ?? '');
  208. }
  209. $this->data = [];
  210. $this->dataCount = 0;
  211. }
  212. }
  213. private function doDump(DataDumperInterface $dumper, Data $data, string $name, string $file, int $line, string $label): void
  214. {
  215. if ($dumper instanceof CliDumper) {
  216. $contextDumper = function ($name, $file, $line, $fmt, $label) {
  217. $this->line = '' !== $label ? $this->style('meta', $label).' in ' : '';
  218. if ($this instanceof HtmlDumper) {
  219. if ($file) {
  220. $s = $this->style('meta', '%s');
  221. $f = strip_tags($this->style('', $file));
  222. $name = strip_tags($this->style('', $name));
  223. if ($fmt && $link = \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line)) {
  224. $name = \sprintf('<a href="%s" title="%s">'.$s.'</a>', strip_tags($this->style('', $link)), $f, $name);
  225. } else {
  226. $name = \sprintf('<abbr title="%s">'.$s.'</abbr>', $f, $name);
  227. }
  228. } else {
  229. $name = $this->style('meta', $name);
  230. }
  231. $this->line .= $name.' on line '.$this->style('meta', $line).':';
  232. } else {
  233. $this->line .= $this->style('meta', $name).' on line '.$this->style('meta', $line).':';
  234. }
  235. $this->dumpLine(0);
  236. };
  237. $contextDumper = $contextDumper->bindTo($dumper, $dumper);
  238. $contextDumper($name, $file, $line, $this->fileLinkFormat, $label);
  239. } else {
  240. $cloner = new VarCloner();
  241. $dumper->dump($cloner->cloneVar(('' !== $label ? $label.' in ' : '').$name.' on line '.$line.':'));
  242. }
  243. $dumper->dump($data);
  244. }
  245. }