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