DumpDataCollector.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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\HtmlDumper;
  19. use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
  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) {
  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 = array();
  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(array('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 serialize()
  144. {
  145. if ($this->clonesCount !== $this->clonesIndex) {
  146. return 'a:0:{}';
  147. }
  148. $this->data[] = $this->fileLinkFormat;
  149. $this->data[] = $this->charset;
  150. $ser = serialize($this->data);
  151. $this->data = array();
  152. $this->dataCount = 0;
  153. $this->isCollected = true;
  154. if (!$this->dumperIsInjected) {
  155. $this->dumper = null;
  156. }
  157. return $ser;
  158. }
  159. public function unserialize($data)
  160. {
  161. parent::unserialize($data);
  162. $charset = array_pop($this->data);
  163. $fileLinkFormat = array_pop($this->data);
  164. $this->dataCount = count($this->data);
  165. self::__construct($this->stopwatch, $fileLinkFormat, $charset);
  166. }
  167. public function getDumpsCount()
  168. {
  169. return $this->dataCount;
  170. }
  171. public function getDumps($format, $maxDepthLimit = -1, $maxItemsPerDepth = -1)
  172. {
  173. $data = fopen('php://memory', 'r+b');
  174. if ('html' === $format) {
  175. $dumper = new HtmlDumper($data, $this->charset);
  176. $dumper->setDisplayOptions(array('fileLinkFormat' => $this->fileLinkFormat));
  177. } else {
  178. throw new \InvalidArgumentException(sprintf('Invalid dump format: %s', $format));
  179. }
  180. $dumps = array();
  181. foreach ($this->data as $dump) {
  182. $dumper->dump($dump['data']->withMaxDepth($maxDepthLimit)->withMaxItemsPerDepth($maxItemsPerDepth));
  183. $dump['data'] = stream_get_contents($data, -1, 0);
  184. ftruncate($data, 0);
  185. rewind($data);
  186. $dumps[] = $dump;
  187. }
  188. return $dumps;
  189. }
  190. public function getName()
  191. {
  192. return 'dump';
  193. }
  194. public function __destruct()
  195. {
  196. if (0 === $this->clonesCount-- && !$this->isCollected && $this->data) {
  197. $this->clonesCount = 0;
  198. $this->isCollected = true;
  199. $h = headers_list();
  200. $i = count($h);
  201. array_unshift($h, 'Content-Type: '.ini_get('default_mimetype'));
  202. while (0 !== stripos($h[$i], 'Content-Type:')) {
  203. --$i;
  204. }
  205. if ('cli' !== PHP_SAPI && stripos($h[$i], 'html')) {
  206. $this->dumper = new HtmlDumper('php://output', $this->charset);
  207. $this->dumper->setDisplayOptions(array('fileLinkFormat' => $this->fileLinkFormat));
  208. } else {
  209. $this->dumper = new CliDumper('php://output', $this->charset);
  210. }
  211. foreach ($this->data as $i => $dump) {
  212. $this->data[$i] = null;
  213. $this->doDump($dump['data'], $dump['name'], $dump['file'], $dump['line']);
  214. }
  215. $this->data = array();
  216. $this->dataCount = 0;
  217. }
  218. }
  219. private function doDump($data, $name, $file, $line)
  220. {
  221. if ($this->dumper instanceof CliDumper) {
  222. $contextDumper = function ($name, $file, $line, $fmt) {
  223. if ($this instanceof HtmlDumper) {
  224. if ($file) {
  225. $s = $this->style('meta', '%s');
  226. $f = strip_tags($this->style('', $file));
  227. $name = strip_tags($this->style('', $name));
  228. if ($fmt && $link = is_string($fmt) ? strtr($fmt, array('%f' => $file, '%l' => $line)) : $fmt->format($file, $line)) {
  229. $name = sprintf('<a href="%s" title="%s">'.$s.'</a>', strip_tags($this->style('', $link)), $f, $name);
  230. } else {
  231. $name = sprintf('<abbr title="%s">'.$s.'</abbr>', $f, $name);
  232. }
  233. } else {
  234. $name = $this->style('meta', $name);
  235. }
  236. $this->line = $name.' on line '.$this->style('meta', $line).':';
  237. } else {
  238. $this->line = $this->style('meta', $name).' on line '.$this->style('meta', $line).':';
  239. }
  240. $this->dumpLine(0);
  241. };
  242. $contextDumper = $contextDumper->bindTo($this->dumper, $this->dumper);
  243. $contextDumper($name, $file, $line, $this->fileLinkFormat);
  244. } else {
  245. $cloner = new VarCloner();
  246. $this->dumper->dump($cloner->cloneVar($name.' on line '.$line.':'));
  247. }
  248. $this->dumper->dump($data);
  249. }
  250. private function htmlEncode($s)
  251. {
  252. $html = '';
  253. $dumper = new HtmlDumper(function ($line) use (&$html) { $html .= $line; }, $this->charset);
  254. $dumper->setDumpHeader('');
  255. $dumper->setDumpBoundaries('', '');
  256. $cloner = new VarCloner();
  257. $dumper->dump($cloner->cloneVar($s));
  258. return substr(strip_tags($html), 1, -1);
  259. }
  260. }