Bez popisu

HtmlDumper.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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\VarDumper\Dumper;
  11. use Symfony\Component\VarDumper\Cloner\Cursor;
  12. use Symfony\Component\VarDumper\Cloner\Data;
  13. /**
  14. * HtmlDumper dumps variables as HTML.
  15. *
  16. * @author Nicolas Grekas <p@tchwork.com>
  17. */
  18. class HtmlDumper extends CliDumper
  19. {
  20. public static $defaultOutput = 'php://output';
  21. protected $dumpHeader;
  22. protected $dumpPrefix = '<pre class=sf-dump id=%s data-indent-pad="%s">';
  23. protected $dumpSuffix = '</pre><script>Sfdump(%s)</script>';
  24. protected $dumpId = 'sf-dump';
  25. protected $colors = true;
  26. protected $headerIsDumped = false;
  27. protected $lastDepth = -1;
  28. protected $styles = array(
  29. 'default' => 'background-color:#18171B; color:#FF8400; line-height:1.2em; font:12px Menlo, Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:99999; word-break: normal',
  30. 'num' => 'font-weight:bold; color:#1299DA',
  31. 'const' => 'font-weight:bold',
  32. 'str' => 'font-weight:bold; color:#56DB3A',
  33. 'note' => 'color:#1299DA',
  34. 'ref' => 'color:#A0A0A0',
  35. 'public' => 'color:#FFFFFF',
  36. 'protected' => 'color:#FFFFFF',
  37. 'private' => 'color:#FFFFFF',
  38. 'meta' => 'color:#B729D9',
  39. 'key' => 'color:#56DB3A',
  40. 'index' => 'color:#1299DA',
  41. 'ellipsis' => 'color:#FF8400',
  42. );
  43. private $displayOptions = array(
  44. 'maxDepth' => 1,
  45. 'maxStringLength' => 160,
  46. 'fileLinkFormat' => null,
  47. );
  48. private $extraDisplayOptions = array();
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function __construct($output = null, $charset = null, $flags = 0)
  53. {
  54. AbstractDumper::__construct($output, $charset, $flags);
  55. $this->dumpId = 'sf-dump-'.mt_rand();
  56. $this->displayOptions['fileLinkFormat'] = ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function setStyles(array $styles)
  62. {
  63. $this->headerIsDumped = false;
  64. $this->styles = $styles + $this->styles;
  65. }
  66. /**
  67. * Configures display options.
  68. *
  69. * @param array $displayOptions A map of display options to customize the behavior
  70. */
  71. public function setDisplayOptions(array $displayOptions)
  72. {
  73. $this->headerIsDumped = false;
  74. $this->displayOptions = $displayOptions + $this->displayOptions;
  75. }
  76. /**
  77. * Sets an HTML header that will be dumped once in the output stream.
  78. *
  79. * @param string $header An HTML string
  80. */
  81. public function setDumpHeader($header)
  82. {
  83. $this->dumpHeader = $header;
  84. }
  85. /**
  86. * Sets an HTML prefix and suffix that will encapse every single dump.
  87. *
  88. * @param string $prefix The prepended HTML string
  89. * @param string $suffix The appended HTML string
  90. */
  91. public function setDumpBoundaries($prefix, $suffix)
  92. {
  93. $this->dumpPrefix = $prefix;
  94. $this->dumpSuffix = $suffix;
  95. }
  96. /**
  97. * {@inheritdoc}
  98. */
  99. public function dump(Data $data, $output = null, array $extraDisplayOptions = array())
  100. {
  101. $this->extraDisplayOptions = $extraDisplayOptions;
  102. $result = parent::dump($data, $output);
  103. $this->dumpId = 'sf-dump-'.mt_rand();
  104. return $result;
  105. }
  106. /**
  107. * Dumps the HTML header.
  108. */
  109. protected function getDumpHeader()
  110. {
  111. $this->headerIsDumped = null !== $this->outputStream ? $this->outputStream : $this->lineDumper;
  112. if (null !== $this->dumpHeader) {
  113. return $this->dumpHeader;
  114. }
  115. $line = str_replace('{$options}', json_encode($this->displayOptions, JSON_FORCE_OBJECT), <<<'EOHTML'
  116. <script>
  117. Sfdump = window.Sfdump || (function (doc) {
  118. var refStyle = doc.createElement('style'),
  119. rxEsc = /([.*+?^${}()|\[\]\/\\])/g,
  120. idRx = /\bsf-dump-\d+-ref[012]\w+\b/,
  121. keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl',
  122. addEventListener = function (e, n, cb) {
  123. e.addEventListener(n, cb, false);
  124. };
  125. (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle);
  126. if (!doc.addEventListener) {
  127. addEventListener = function (element, eventName, callback) {
  128. element.attachEvent('on' + eventName, function (e) {
  129. e.preventDefault = function () {e.returnValue = false;};
  130. e.target = e.srcElement;
  131. callback(e);
  132. });
  133. };
  134. }
  135. function toggle(a, recursive) {
  136. var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass;
  137. if ('sf-dump-compact' == oldClass) {
  138. arrow = '▼';
  139. newClass = 'sf-dump-expanded';
  140. } else if ('sf-dump-expanded' == oldClass) {
  141. arrow = '▶';
  142. newClass = 'sf-dump-compact';
  143. } else {
  144. return false;
  145. }
  146. a.lastChild.innerHTML = arrow;
  147. s.className = newClass;
  148. if (recursive) {
  149. try {
  150. a = s.querySelectorAll('.'+oldClass);
  151. for (s = 0; s < a.length; ++s) {
  152. if (a[s].className !== newClass) {
  153. a[s].className = newClass;
  154. a[s].previousSibling.lastChild.innerHTML = arrow;
  155. }
  156. }
  157. } catch (e) {
  158. }
  159. }
  160. return true;
  161. };
  162. return function (root, x) {
  163. root = doc.getElementById(root);
  164. var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'),
  165. options = {$options},
  166. elt = root.getElementsByTagName('A'),
  167. len = elt.length,
  168. i = 0, s, h,
  169. t = [];
  170. while (i < len) t.push(elt[i++]);
  171. for (i in x) {
  172. options[i] = x[i];
  173. }
  174. function a(e, f) {
  175. addEventListener(root, e, function (e) {
  176. if ('A' == e.target.tagName) {
  177. f(e.target, e);
  178. } else if ('A' == e.target.parentNode.tagName) {
  179. f(e.target.parentNode, e);
  180. } else if (e.target.nextElementSibling && 'A' == e.target.nextElementSibling.tagName) {
  181. f(e.target.nextElementSibling, e, true);
  182. }
  183. });
  184. };
  185. function isCtrlKey(e) {
  186. return e.ctrlKey || e.metaKey;
  187. }
  188. addEventListener(root, 'mouseover', function (e) {
  189. if ('' != refStyle.innerHTML) {
  190. refStyle.innerHTML = '';
  191. }
  192. });
  193. a('mouseover', function (a, e, c) {
  194. if (c) {
  195. e.target.style.cursor = "pointer";
  196. } else if (a = idRx.exec(a.className)) {
  197. try {
  198. refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}';
  199. } catch (e) {
  200. }
  201. }
  202. });
  203. a('click', function (a, e, c) {
  204. if (/\bsf-dump-toggle\b/.test(a.className)) {
  205. e.preventDefault();
  206. if (!toggle(a, isCtrlKey(e))) {
  207. var r = doc.getElementById(a.getAttribute('href').substr(1)),
  208. s = r.previousSibling,
  209. f = r.parentNode,
  210. t = a.parentNode;
  211. t.replaceChild(r, a);
  212. f.replaceChild(a, s);
  213. t.insertBefore(s, r);
  214. f = f.firstChild.nodeValue.match(indentRx);
  215. t = t.firstChild.nodeValue.match(indentRx);
  216. if (f && t && f[0] !== t[0]) {
  217. r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]);
  218. }
  219. if ('sf-dump-compact' == r.className) {
  220. toggle(s, isCtrlKey(e));
  221. }
  222. }
  223. if (c) {
  224. } else if (doc.getSelection) {
  225. try {
  226. doc.getSelection().removeAllRanges();
  227. } catch (e) {
  228. doc.getSelection().empty();
  229. }
  230. } else {
  231. doc.selection.empty();
  232. }
  233. } else if (/\bsf-dump-str-toggle\b/.test(a.className)) {
  234. e.preventDefault();
  235. e = a.parentNode.parentNode;
  236. e.className = e.className.replace(/sf-dump-str-(expand|collapse)/, a.parentNode.className);
  237. }
  238. });
  239. elt = root.getElementsByTagName('SAMP');
  240. len = elt.length;
  241. i = 0;
  242. while (i < len) t.push(elt[i++]);
  243. len = t.length;
  244. for (i = 0; i < len; ++i) {
  245. elt = t[i];
  246. if ('SAMP' == elt.tagName) {
  247. elt.className = 'sf-dump-expanded';
  248. a = elt.previousSibling || {};
  249. if ('A' != a.tagName) {
  250. a = doc.createElement('A');
  251. a.className = 'sf-dump-ref';
  252. elt.parentNode.insertBefore(a, elt);
  253. } else {
  254. a.innerHTML += ' ';
  255. }
  256. a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children';
  257. a.innerHTML += '<span>▼</span>';
  258. a.className += ' sf-dump-toggle';
  259. x = 1;
  260. if ('sf-dump' != elt.parentNode.className) {
  261. x += elt.parentNode.getAttribute('data-depth')/1;
  262. }
  263. elt.setAttribute('data-depth', x);
  264. if (x > options.maxDepth) {
  265. toggle(a);
  266. }
  267. } else if ('sf-dump-ref' == elt.className && (a = elt.getAttribute('href'))) {
  268. a = a.substr(1);
  269. elt.className += ' '+a;
  270. if (/[\[{]$/.test(elt.previousSibling.nodeValue)) {
  271. a = a != elt.nextSibling.id && doc.getElementById(a);
  272. try {
  273. s = a.nextSibling;
  274. elt.appendChild(a);
  275. s.parentNode.insertBefore(a, s);
  276. if (/^[@#]/.test(elt.innerHTML)) {
  277. elt.innerHTML += ' <span>▶</span>';
  278. } else {
  279. elt.innerHTML = '<span>▶</span>';
  280. elt.className = 'sf-dump-ref';
  281. }
  282. elt.className += ' sf-dump-toggle';
  283. } catch (e) {
  284. if ('&' == elt.innerHTML.charAt(0)) {
  285. elt.innerHTML = '…';
  286. elt.className = 'sf-dump-ref';
  287. }
  288. }
  289. }
  290. }
  291. }
  292. if (0 >= options.maxStringLength) {
  293. return;
  294. }
  295. try {
  296. elt = root.querySelectorAll('.sf-dump-str');
  297. len = elt.length;
  298. i = 0;
  299. t = [];
  300. while (i < len) t.push(elt[i++]);
  301. len = t.length;
  302. for (i = 0; i < len; ++i) {
  303. elt = t[i];
  304. s = elt.innerText || elt.textContent;
  305. x = s.length - options.maxStringLength;
  306. if (0 < x) {
  307. h = elt.innerHTML;
  308. elt[elt.innerText ? 'innerText' : 'textContent'] = s.substring(0, options.maxStringLength);
  309. elt.className += ' sf-dump-str-collapse';
  310. elt.innerHTML = '<span class=sf-dump-str-collapse>'+h+'<a class="sf-dump-ref sf-dump-str-toggle" title="Collapse"> ◀</a></span>'+
  311. '<span class=sf-dump-str-expand>'+elt.innerHTML+'<a class="sf-dump-ref sf-dump-str-toggle" title="'+x+' remaining characters"> ▶</a></span>';
  312. }
  313. }
  314. } catch (e) {
  315. }
  316. };
  317. })(document);
  318. </script><style>
  319. pre.sf-dump {
  320. display: block;
  321. white-space: pre;
  322. padding: 5px;
  323. }
  324. pre.sf-dump span {
  325. display: inline;
  326. }
  327. pre.sf-dump .sf-dump-compact {
  328. display: none;
  329. }
  330. pre.sf-dump abbr {
  331. text-decoration: none;
  332. border: none;
  333. cursor: help;
  334. }
  335. pre.sf-dump a {
  336. text-decoration: none;
  337. cursor: pointer;
  338. border: 0;
  339. outline: none;
  340. color: inherit;
  341. }
  342. pre.sf-dump .sf-dump-ellipsis {
  343. display: inline-block;
  344. overflow: visible;
  345. text-overflow: ellipsis;
  346. max-width: 5em;
  347. white-space: nowrap;
  348. overflow: hidden;
  349. vertical-align: top;
  350. }
  351. pre.sf-dump code {
  352. display:inline;
  353. padding:0;
  354. background:none;
  355. }
  356. .sf-dump-str-collapse .sf-dump-str-collapse {
  357. display: none;
  358. }
  359. .sf-dump-str-expand .sf-dump-str-expand {
  360. display: none;
  361. }
  362. EOHTML
  363. );
  364. foreach ($this->styles as $class => $style) {
  365. $line .= 'pre.sf-dump'.('default' === $class ? ', pre.sf-dump' : '').' .sf-dump-'.$class.'{'.$style.'}';
  366. }
  367. return $this->dumpHeader = preg_replace('/\s+/', ' ', $line).'</style>'.$this->dumpHeader;
  368. }
  369. /**
  370. * {@inheritdoc}
  371. */
  372. public function enterHash(Cursor $cursor, $type, $class, $hasChild)
  373. {
  374. parent::enterHash($cursor, $type, $class, false);
  375. if ($hasChild) {
  376. if ($cursor->refIndex) {
  377. $r = Cursor::HASH_OBJECT !== $type ? 1 - (Cursor::HASH_RESOURCE !== $type) : 2;
  378. $r .= $r && 0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->refIndex;
  379. $this->line .= sprintf('<samp id=%s-ref%s>', $this->dumpId, $r);
  380. } else {
  381. $this->line .= '<samp>';
  382. }
  383. $this->dumpLine($cursor->depth);
  384. }
  385. }
  386. /**
  387. * {@inheritdoc}
  388. */
  389. public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut)
  390. {
  391. $this->dumpEllipsis($cursor, $hasChild, $cut);
  392. if ($hasChild) {
  393. $this->line .= '</samp>';
  394. }
  395. parent::leaveHash($cursor, $type, $class, $hasChild, 0);
  396. }
  397. /**
  398. * {@inheritdoc}
  399. */
  400. protected function style($style, $value, $attr = array())
  401. {
  402. if ('' === $value) {
  403. return '';
  404. }
  405. $v = esc($value);
  406. if ('ref' === $style) {
  407. if (empty($attr['count'])) {
  408. return sprintf('<a class=sf-dump-ref>%s</a>', $v);
  409. }
  410. $r = ('#' !== $v[0] ? 1 - ('@' !== $v[0]) : 2).substr($value, 1);
  411. return sprintf('<a class=sf-dump-ref href=#%s-ref%s title="%d occurrences">%s</a>', $this->dumpId, $r, 1 + $attr['count'], $v);
  412. }
  413. if ('const' === $style && isset($attr['value'])) {
  414. $style .= sprintf(' title="%s"', esc(is_scalar($attr['value']) ? $attr['value'] : json_encode($attr['value'])));
  415. } elseif ('public' === $style) {
  416. $style .= sprintf(' title="%s"', empty($attr['dynamic']) ? 'Public property' : 'Runtime added dynamic property');
  417. } elseif ('str' === $style && 1 < $attr['length']) {
  418. $style .= sprintf(' title="%d%s characters"', $attr['length'], $attr['binary'] ? ' binary or non-UTF-8' : '');
  419. } elseif ('note' === $style && false !== $c = strrpos($v, '\\')) {
  420. return sprintf('<abbr title="%s" class=sf-dump-%s>%s</abbr>', $v, $style, substr($v, $c + 1));
  421. } elseif ('protected' === $style) {
  422. $style .= ' title="Protected property"';
  423. } elseif ('meta' === $style && isset($attr['title'])) {
  424. $style .= sprintf(' title="%s"', esc($this->utf8Encode($attr['title'])));
  425. } elseif ('private' === $style) {
  426. $style .= sprintf(' title="Private property defined in class:&#10;`%s`"', esc($this->utf8Encode($attr['class'])));
  427. }
  428. $map = static::$controlCharsMap;
  429. if (isset($attr['ellipsis'])) {
  430. $label = esc(substr($value, -$attr['ellipsis']));
  431. $style = str_replace(' title="', " title=\"$v\n", $style);
  432. $v = sprintf('<span class=sf-dump-ellipsis>%s</span>%s', substr($v, 0, -strlen($label)), $label);
  433. }
  434. $v = "<span class=sf-dump-{$style}>".preg_replace_callback(static::$controlCharsRx, function ($c) use ($map) {
  435. $s = '<span class=sf-dump-default>';
  436. $c = $c[$i = 0];
  437. do {
  438. $s .= isset($map[$c[$i]]) ? $map[$c[$i]] : sprintf('\x%02X', ord($c[$i]));
  439. } while (isset($c[++$i]));
  440. return $s.'</span>';
  441. }, $v).'</span>';
  442. if (isset($attr['file']) && $href = $this->getSourceLink($attr['file'], isset($attr['line']) ? $attr['line'] : 0)) {
  443. $attr['href'] = $href;
  444. }
  445. if (isset($attr['href'])) {
  446. $v = sprintf('<a href="%s">%s</a>', esc($this->utf8Encode($attr['href'])), $v);
  447. }
  448. if (isset($attr['lang'])) {
  449. $v = sprintf('<code class="%s">%s</code>', esc($attr['lang']), $v);
  450. }
  451. return $v;
  452. }
  453. /**
  454. * {@inheritdoc}
  455. */
  456. protected function dumpLine($depth, $endOfValue = false)
  457. {
  458. if (-1 === $this->lastDepth) {
  459. $this->line = sprintf($this->dumpPrefix, $this->dumpId, $this->indentPad).$this->line;
  460. }
  461. if ($this->headerIsDumped !== (null !== $this->outputStream ? $this->outputStream : $this->lineDumper)) {
  462. $this->line = $this->getDumpHeader().$this->line;
  463. }
  464. if (-1 === $depth) {
  465. $args = array('"'.$this->dumpId.'"');
  466. if ($this->extraDisplayOptions) {
  467. $args[] = json_encode($this->extraDisplayOptions, JSON_FORCE_OBJECT);
  468. }
  469. // Replace is for BC
  470. $this->line .= sprintf(str_replace('"%s"', '%s', $this->dumpSuffix), implode(', ', $args));
  471. }
  472. $this->lastDepth = $depth;
  473. $this->line = mb_convert_encoding($this->line, 'HTML-ENTITIES', 'UTF-8');
  474. if (-1 === $depth) {
  475. AbstractDumper::dumpLine(0);
  476. }
  477. AbstractDumper::dumpLine($depth);
  478. }
  479. private function getSourceLink($file, $line)
  480. {
  481. $options = $this->extraDisplayOptions + $this->displayOptions;
  482. if ($fmt = $options['fileLinkFormat']) {
  483. return is_string($fmt) ? strtr($fmt, array('%f' => $file, '%l' => $line)) : $fmt->format($file, $line);
  484. }
  485. return false;
  486. }
  487. }
  488. function esc($str)
  489. {
  490. return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
  491. }