No Description

DumpDataCollector.php 11KB

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