DumpDataCollector.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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\Stopwatch\Stopwatch;
  15. use Symfony\Component\VarDumper\Cloner\Data;
  16. use Symfony\Component\VarDumper\Cloner\VarCloner;
  17. use Symfony\Component\VarDumper\Dumper\CliDumper;
  18. use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
  19. use Symfony\Component\VarDumper\Dumper\HtmlDumper;
  20. use Twig\Template;
  21. /**
  22. * @author Nicolas Grekas <p@tchwork.com>
  23. */
  24. class DumpDataCollector extends DataCollector implements DataDumperInterface
  25. {
  26. private $stopwatch;
  27. private $fileLinkFormat;
  28. private $dataCount = 0;
  29. private $isCollected = true;
  30. private $clonesCount = 0;
  31. private $clonesIndex = 0;
  32. private $rootRefs;
  33. private $charset;
  34. private $requestStack;
  35. private $dumper;
  36. private $dumperIsInjected;
  37. public function __construct(Stopwatch $stopwatch = null, $fileLinkFormat = null, $charset = null, RequestStack $requestStack = null, DataDumperInterface $dumper = null)
  38. {
  39. $this->stopwatch = $stopwatch;
  40. $this->fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
  41. $this->charset = $charset ?: ini_get('php.output_encoding') ?: ini_get('default_charset') ?: 'UTF-8';
  42. $this->requestStack = $requestStack;
  43. $this->dumper = $dumper;
  44. $this->dumperIsInjected = null !== $dumper;
  45. // All clones share these properties by reference:
  46. $this->rootRefs = [
  47. &$this->data,
  48. &$this->dataCount,
  49. &$this->isCollected,
  50. &$this->clonesCount,
  51. ];
  52. }
  53. public function __clone()
  54. {
  55. $this->clonesIndex = ++$this->clonesCount;
  56. }
  57. public function dump(Data $data)
  58. {
  59. if ($this->stopwatch) {
  60. $this->stopwatch->start('dump');
  61. }
  62. if ($this->isCollected && !$this->dumper) {
  63. $this->isCollected = false;
  64. }
  65. $trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 7);
  66. $file = $trace[0]['file'];
  67. $line = $trace[0]['line'];
  68. $name = false;
  69. $fileExcerpt = false;
  70. for ($i = 1; $i < 7; ++$i) {
  71. if (isset($trace[$i]['class'], $trace[$i]['function'])
  72. && 'dump' === $trace[$i]['function']
  73. && 'Symfony\Component\VarDumper\VarDumper' === $trace[$i]['class']
  74. ) {
  75. $file = $trace[$i]['file'];
  76. $line = $trace[$i]['line'];
  77. while (++$i < 7) {
  78. if (isset($trace[$i]['function'], $trace[$i]['file']) && empty($trace[$i]['class']) && 0 !== strpos($trace[$i]['function'], 'call_user_func')) {
  79. $file = $trace[$i]['file'];
  80. $line = $trace[$i]['line'];
  81. break;
  82. } elseif (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof Template) {
  83. $template = $trace[$i]['object'];
  84. $name = $template->getTemplateName();
  85. $src = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : false);
  86. $info = $template->getDebugInfo();
  87. if (isset($info[$trace[$i - 1]['line']])) {
  88. $line = $info[$trace[$i - 1]['line']];
  89. $file = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getPath() : null;
  90. if ($src) {
  91. $src = explode("\n", $src);
  92. $fileExcerpt = [];
  93. for ($i = max($line - 3, 1), $max = min($line + 3, \count($src)); $i <= $max; ++$i) {
  94. $fileExcerpt[] = '<li'.($i === $line ? ' class="selected"' : '').'><code>'.$this->htmlEncode($src[$i - 1]).'</code></li>';
  95. }
  96. $fileExcerpt = '<ol start="'.max($line - 3, 1).'">'.implode("\n", $fileExcerpt).'</ol>';
  97. }
  98. }
  99. break;
  100. }
  101. }
  102. break;
  103. }
  104. }
  105. if (false === $name) {
  106. $name = str_replace('\\', '/', $file);
  107. $name = substr($name, strrpos($name, '/') + 1);
  108. }
  109. if ($this->dumper) {
  110. $this->doDump($data, $name, $file, $line);
  111. }
  112. $this->data[] = compact('data', 'name', 'file', 'line', 'fileExcerpt');
  113. ++$this->dataCount;
  114. if ($this->stopwatch) {
  115. $this->stopwatch->stop('dump');
  116. }
  117. }
  118. public function collect(Request $request, Response $response, \Exception $exception = null)
  119. {
  120. // Sub-requests and programmatic calls stay in the collected profile.
  121. if ($this->dumper || ($this->requestStack && $this->requestStack->getMasterRequest() !== $request) || $request->isXmlHttpRequest() || $request->headers->has('Origin')) {
  122. return;
  123. }
  124. // In all other conditions that remove the web debug toolbar, dumps are written on the output.
  125. if (!$this->requestStack
  126. || !$response->headers->has('X-Debug-Token')
  127. || $response->isRedirection()
  128. || ($response->headers->has('Content-Type') && false === strpos($response->headers->get('Content-Type'), 'html'))
  129. || 'html' !== $request->getRequestFormat()
  130. || false === strripos($response->getContent(), '</body>')
  131. ) {
  132. if ($response->headers->has('Content-Type') && false !== strpos($response->headers->get('Content-Type'), 'html')) {
  133. $this->dumper = new HtmlDumper('php://output', $this->charset);
  134. $this->dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
  135. } else {
  136. $this->dumper = new CliDumper('php://output', $this->charset);
  137. }
  138. foreach ($this->data as $dump) {
  139. $this->doDump($dump['data'], $dump['name'], $dump['file'], $dump['line']);
  140. }
  141. }
  142. }
  143. public function reset()
  144. {
  145. if ($this->stopwatch) {
  146. $this->stopwatch->reset();
  147. }
  148. $this->data = [];
  149. $this->dataCount = 0;
  150. $this->isCollected = true;
  151. $this->clonesCount = 0;
  152. $this->clonesIndex = 0;
  153. }
  154. public function serialize()
  155. {
  156. if ($this->clonesCount !== $this->clonesIndex) {
  157. return 'a:0:{}';
  158. }
  159. $this->data[] = $this->fileLinkFormat;
  160. $this->data[] = $this->charset;
  161. $ser = serialize($this->data);
  162. $this->data = [];
  163. $this->dataCount = 0;
  164. $this->isCollected = true;
  165. if (!$this->dumperIsInjected) {
  166. $this->dumper = null;
  167. }
  168. return $ser;
  169. }
  170. public function unserialize($data)
  171. {
  172. $this->data = unserialize($data);
  173. $charset = array_pop($this->data);
  174. $fileLinkFormat = array_pop($this->data);
  175. $this->dataCount = \count($this->data);
  176. self::__construct($this->stopwatch, $fileLinkFormat, $charset);
  177. }
  178. public function getDumpsCount()
  179. {
  180. return $this->dataCount;
  181. }
  182. public function getDumps($format, $maxDepthLimit = -1, $maxItemsPerDepth = -1)
  183. {
  184. $data = fopen('php://memory', 'r+b');
  185. if ('html' === $format) {
  186. $dumper = new HtmlDumper($data, $this->charset);
  187. $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
  188. } else {
  189. throw new \InvalidArgumentException(sprintf('Invalid dump format: %s', $format));
  190. }
  191. $dumps = [];
  192. foreach ($this->data as $dump) {
  193. $dumper->dump($dump['data']->withMaxDepth($maxDepthLimit)->withMaxItemsPerDepth($maxItemsPerDepth));
  194. $dump['data'] = stream_get_contents($data, -1, 0);
  195. ftruncate($data, 0);
  196. rewind($data);
  197. $dumps[] = $dump;
  198. }
  199. return $dumps;
  200. }
  201. public function getName()
  202. {
  203. return 'dump';
  204. }
  205. public function __destruct()
  206. {
  207. if (0 === $this->clonesCount-- && !$this->isCollected && $this->data) {
  208. $this->clonesCount = 0;
  209. $this->isCollected = true;
  210. $h = headers_list();
  211. $i = \count($h);
  212. array_unshift($h, 'Content-Type: '.ini_get('default_mimetype'));
  213. while (0 !== stripos($h[$i], 'Content-Type:')) {
  214. --$i;
  215. }
  216. if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && stripos($h[$i], 'html')) {
  217. $this->dumper = new HtmlDumper('php://output', $this->charset);
  218. $this->dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]);
  219. } else {
  220. $this->dumper = new CliDumper('php://output', $this->charset);
  221. }
  222. foreach ($this->data as $i => $dump) {
  223. $this->data[$i] = null;
  224. $this->doDump($dump['data'], $dump['name'], $dump['file'], $dump['line']);
  225. }
  226. $this->data = [];
  227. $this->dataCount = 0;
  228. }
  229. }
  230. private function doDump($data, $name, $file, $line)
  231. {
  232. if ($this->dumper instanceof CliDumper) {
  233. $contextDumper = function ($name, $file, $line, $fmt) {
  234. if ($this instanceof HtmlDumper) {
  235. if ($file) {
  236. $s = $this->style('meta', '%s');
  237. $f = strip_tags($this->style('', $file));
  238. $name = strip_tags($this->style('', $name));
  239. if ($fmt && $link = \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line)) {
  240. $name = sprintf('<a href="%s" title="%s">'.$s.'</a>', strip_tags($this->style('', $link)), $f, $name);
  241. } else {
  242. $name = sprintf('<abbr title="%s">'.$s.'</abbr>', $f, $name);
  243. }
  244. } else {
  245. $name = $this->style('meta', $name);
  246. }
  247. $this->line = $name.' on line '.$this->style('meta', $line).':';
  248. } else {
  249. $this->line = $this->style('meta', $name).' on line '.$this->style('meta', $line).':';
  250. }
  251. $this->dumpLine(0);
  252. };
  253. $contextDumper = $contextDumper->bindTo($this->dumper, $this->dumper);
  254. $contextDumper($name, $file, $line, $this->fileLinkFormat);
  255. } else {
  256. $cloner = new VarCloner();
  257. $this->dumper->dump($cloner->cloneVar($name.' on line '.$line.':'));
  258. }
  259. $this->dumper->dump($data);
  260. }
  261. private function htmlEncode($s)
  262. {
  263. $html = '';
  264. $dumper = new HtmlDumper(function ($line) use (&$html) { $html .= $line; }, $this->charset);
  265. $dumper->setDumpHeader('');
  266. $dumper->setDumpBoundaries('', '');
  267. $cloner = new VarCloner();
  268. $dumper->dump($cloner->cloneVar($s));
  269. return substr(strip_tags($html), 1, -1);
  270. }
  271. }