DumpDataCollector.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 = array(
  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_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS;
  66. if (\PHP_VERSION_ID >= 50400) {
  67. $trace = debug_backtrace($trace, 7);
  68. } else {
  69. $trace = debug_backtrace($trace);
  70. }
  71. $file = $trace[0]['file'];
  72. $line = $trace[0]['line'];
  73. $name = false;
  74. $fileExcerpt = false;
  75. for ($i = 1; $i < 7; ++$i) {
  76. if (isset($trace[$i]['class'], $trace[$i]['function'])
  77. && 'dump' === $trace[$i]['function']
  78. && 'Symfony\Component\VarDumper\VarDumper' === $trace[$i]['class']
  79. ) {
  80. $file = $trace[$i]['file'];
  81. $line = $trace[$i]['line'];
  82. while (++$i < 7) {
  83. if (isset($trace[$i]['function'], $trace[$i]['file']) && empty($trace[$i]['class']) && 0 !== strpos($trace[$i]['function'], 'call_user_func')) {
  84. $file = $trace[$i]['file'];
  85. $line = $trace[$i]['line'];
  86. break;
  87. } elseif (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof Template) {
  88. $template = $trace[$i]['object'];
  89. $name = $template->getTemplateName();
  90. $src = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : false);
  91. $info = $template->getDebugInfo();
  92. if (isset($info[$trace[$i - 1]['line']])) {
  93. $line = $info[$trace[$i - 1]['line']];
  94. $file = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getPath() : null;
  95. if ($src) {
  96. $src = explode("\n", $src);
  97. $fileExcerpt = array();
  98. for ($i = max($line - 3, 1), $max = min($line + 3, \count($src)); $i <= $max; ++$i) {
  99. $fileExcerpt[] = '<li'.($i === $line ? ' class="selected"' : '').'><code>'.$this->htmlEncode($src[$i - 1]).'</code></li>';
  100. }
  101. $fileExcerpt = '<ol start="'.max($line - 3, 1).'">'.implode("\n", $fileExcerpt).'</ol>';
  102. }
  103. }
  104. break;
  105. }
  106. }
  107. break;
  108. }
  109. }
  110. if (false === $name) {
  111. $name = str_replace('\\', '/', $file);
  112. $name = substr($name, strrpos($name, '/') + 1);
  113. }
  114. if ($this->dumper) {
  115. $this->doDump($data, $name, $file, $line);
  116. }
  117. $this->data[] = compact('data', 'name', 'file', 'line', 'fileExcerpt');
  118. ++$this->dataCount;
  119. if ($this->stopwatch) {
  120. $this->stopwatch->stop('dump');
  121. }
  122. }
  123. public function collect(Request $request, Response $response, \Exception $exception = null)
  124. {
  125. // Sub-requests and programmatic calls stay in the collected profile.
  126. if ($this->dumper || ($this->requestStack && $this->requestStack->getMasterRequest() !== $request) || $request->isXmlHttpRequest() || $request->headers->has('Origin')) {
  127. return;
  128. }
  129. // In all other conditions that remove the web debug toolbar, dumps are written on the output.
  130. if (!$this->requestStack
  131. || !$response->headers->has('X-Debug-Token')
  132. || $response->isRedirection()
  133. || ($response->headers->has('Content-Type') && false === strpos($response->headers->get('Content-Type'), 'html'))
  134. || 'html' !== $request->getRequestFormat()
  135. || false === strripos($response->getContent(), '</body>')
  136. ) {
  137. if ($response->headers->has('Content-Type') && false !== strpos($response->headers->get('Content-Type'), 'html')) {
  138. $this->dumper = new HtmlDumper('php://output', $this->charset);
  139. } else {
  140. $this->dumper = new CliDumper('php://output', $this->charset);
  141. }
  142. foreach ($this->data as $dump) {
  143. $this->doDump($dump['data'], $dump['name'], $dump['file'], $dump['line']);
  144. }
  145. }
  146. }
  147. public function serialize()
  148. {
  149. if ($this->clonesCount !== $this->clonesIndex) {
  150. return 'a:0:{}';
  151. }
  152. $this->data[] = $this->fileLinkFormat;
  153. $this->data[] = $this->charset;
  154. $ser = serialize($this->data);
  155. $this->data = array();
  156. $this->dataCount = 0;
  157. $this->isCollected = true;
  158. if (!$this->dumperIsInjected) {
  159. $this->dumper = null;
  160. }
  161. return $ser;
  162. }
  163. public function unserialize($data)
  164. {
  165. parent::unserialize($data);
  166. $charset = array_pop($this->data);
  167. $fileLinkFormat = array_pop($this->data);
  168. $this->dataCount = \count($this->data);
  169. self::__construct($this->stopwatch, $fileLinkFormat, $charset);
  170. }
  171. public function getDumpsCount()
  172. {
  173. return $this->dataCount;
  174. }
  175. public function getDumps($format, $maxDepthLimit = -1, $maxItemsPerDepth = -1)
  176. {
  177. $data = fopen('php://memory', 'r+b');
  178. if ('html' === $format) {
  179. $dumper = new HtmlDumper($data, $this->charset);
  180. } else {
  181. throw new \InvalidArgumentException(sprintf('Invalid dump format: %s', $format));
  182. }
  183. $dumps = array();
  184. foreach ($this->data as $dump) {
  185. if (method_exists($dump['data'], 'withMaxDepth')) {
  186. $dumper->dump($dump['data']->withMaxDepth($maxDepthLimit)->withMaxItemsPerDepth($maxItemsPerDepth));
  187. } else {
  188. // getLimitedClone is @deprecated, to be removed in 3.0
  189. $dumper->dump($dump['data']->getLimitedClone($maxDepthLimit, $maxItemsPerDepth));
  190. }
  191. $dump['data'] = stream_get_contents($data, -1, 0);
  192. ftruncate($data, 0);
  193. rewind($data);
  194. $dumps[] = $dump;
  195. }
  196. return $dumps;
  197. }
  198. public function getName()
  199. {
  200. return 'dump';
  201. }
  202. public function __destruct()
  203. {
  204. if (0 === $this->clonesCount-- && !$this->isCollected && $this->data) {
  205. $this->clonesCount = 0;
  206. $this->isCollected = true;
  207. $h = headers_list();
  208. $i = \count($h);
  209. array_unshift($h, 'Content-Type: '.ini_get('default_mimetype'));
  210. while (0 !== stripos($h[$i], 'Content-Type:')) {
  211. --$i;
  212. }
  213. if (!\in_array(\PHP_SAPI, array('cli', 'phpdbg'), true) && stripos($h[$i], 'html')) {
  214. $this->dumper = new HtmlDumper('php://output', $this->charset);
  215. } else {
  216. $this->dumper = new CliDumper('php://output', $this->charset);
  217. }
  218. foreach ($this->data as $i => $dump) {
  219. $this->data[$i] = null;
  220. $this->doDump($dump['data'], $dump['name'], $dump['file'], $dump['line']);
  221. }
  222. $this->data = array();
  223. $this->dataCount = 0;
  224. }
  225. }
  226. private function doDump($data, $name, $file, $line)
  227. {
  228. if (\PHP_VERSION_ID >= 50400 && $this->dumper instanceof CliDumper) {
  229. $contextDumper = function ($name, $file, $line, $fileLinkFormat) {
  230. if ($this instanceof HtmlDumper) {
  231. if ($file) {
  232. $s = $this->style('meta', '%s');
  233. $name = strip_tags($this->style('', $name));
  234. $file = strip_tags($this->style('', $file));
  235. if ($fileLinkFormat) {
  236. $link = strtr(strip_tags($this->style('', $fileLinkFormat)), array('%f' => $file, '%l' => (int) $line));
  237. $name = sprintf('<a href="%s" title="%s">'.$s.'</a>', $link, $file, $name);
  238. } else {
  239. $name = sprintf('<abbr title="%s">'.$s.'</abbr>', $file, $name);
  240. }
  241. } else {
  242. $name = $this->style('meta', $name);
  243. }
  244. $this->line = $name.' on line '.$this->style('meta', $line).':';
  245. } else {
  246. $this->line = $this->style('meta', $name).' on line '.$this->style('meta', $line).':';
  247. }
  248. $this->dumpLine(0);
  249. };
  250. $contextDumper = $contextDumper->bindTo($this->dumper, $this->dumper);
  251. $contextDumper($name, $file, $line, $this->fileLinkFormat);
  252. } else {
  253. $cloner = new VarCloner();
  254. $this->dumper->dump($cloner->cloneVar($name.' on line '.$line.':'));
  255. }
  256. $this->dumper->dump($data);
  257. }
  258. private function htmlEncode($s)
  259. {
  260. $html = '';
  261. $dumper = new HtmlDumper(function ($line) use (&$html) { $html .= $line; }, $this->charset);
  262. $dumper->setDumpHeader('');
  263. $dumper->setDumpBoundaries('', '');
  264. $cloner = new VarCloner();
  265. $dumper->dump($cloner->cloneVar($s));
  266. return substr(strip_tags($html), 1, -1);
  267. }
  268. }