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