HtmlDumper.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. );
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function __construct($output = null, $charset = null)
  46. {
  47. AbstractDumper::__construct($output, $charset);
  48. $this->dumpId = 'sf-dump-'.mt_rand();
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function setStyles(array $styles)
  54. {
  55. $this->headerIsDumped = false;
  56. $this->styles = $styles + $this->styles;
  57. }
  58. /**
  59. * Sets an HTML header that will be dumped once in the output stream.
  60. *
  61. * @param string $header An HTML string
  62. */
  63. public function setDumpHeader($header)
  64. {
  65. $this->dumpHeader = $header;
  66. }
  67. /**
  68. * Sets an HTML prefix and suffix that will encapse every single dump.
  69. *
  70. * @param string $prefix The prepended HTML string
  71. * @param string $suffix The appended HTML string
  72. */
  73. public function setDumpBoundaries($prefix, $suffix)
  74. {
  75. $this->dumpPrefix = $prefix;
  76. $this->dumpSuffix = $suffix;
  77. }
  78. /**
  79. * {@inheritdoc}
  80. */
  81. public function dump(Data $data, $output = null)
  82. {
  83. parent::dump($data, $output);
  84. $this->dumpId = 'sf-dump-'.mt_rand();
  85. }
  86. /**
  87. * Dumps the HTML header.
  88. */
  89. protected function getDumpHeader()
  90. {
  91. $this->headerIsDumped = null !== $this->outputStream ? $this->outputStream : $this->lineDumper;
  92. if (null !== $this->dumpHeader) {
  93. return $this->dumpHeader;
  94. }
  95. $line = <<<'EOHTML'
  96. <script>
  97. Sfdump = window.Sfdump || (function (doc) {
  98. var refStyle = doc.createElement('style'),
  99. rxEsc = /([.*+?^${}()|\[\]\/\\])/g,
  100. idRx = /\bsf-dump-\d+-ref[012]\w+\b/,
  101. keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl',
  102. addEventListener = function (e, n, cb) {
  103. e.addEventListener(n, cb, false);
  104. };
  105. (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle);
  106. if (!doc.addEventListener) {
  107. addEventListener = function (element, eventName, callback) {
  108. element.attachEvent('on' + eventName, function (e) {
  109. e.preventDefault = function () {e.returnValue = false;};
  110. e.target = e.srcElement;
  111. callback(e);
  112. });
  113. };
  114. }
  115. function toggle(a, recursive) {
  116. var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass;
  117. if (/\bsf-dump-compact\b/.test(oldClass)) {
  118. arrow = '▼';
  119. newClass = 'sf-dump-expanded';
  120. } else if (/\bsf-dump-expanded\b/.test(oldClass)) {
  121. arrow = '▶';
  122. newClass = 'sf-dump-compact';
  123. } else {
  124. return false;
  125. }
  126. a.lastChild.innerHTML = arrow;
  127. s.className = s.className.replace(/\bsf-dump-(compact|expanded)\b/, newClass);
  128. if (recursive) {
  129. try {
  130. a = s.querySelectorAll('.'+oldClass);
  131. for (s = 0; s < a.length; ++s) {
  132. if (-1 == a[s].className.indexOf(newClass)) {
  133. a[s].className = newClass;
  134. a[s].previousSibling.lastChild.innerHTML = arrow;
  135. }
  136. }
  137. } catch (e) {
  138. }
  139. }
  140. return true;
  141. };
  142. return function (root) {
  143. root = doc.getElementById(root);
  144. function a(e, f) {
  145. addEventListener(root, e, function (e) {
  146. if ('A' == e.target.tagName) {
  147. f(e.target, e);
  148. } else if ('A' == e.target.parentNode.tagName) {
  149. f(e.target.parentNode, e);
  150. }
  151. });
  152. };
  153. function isCtrlKey(e) {
  154. return e.ctrlKey || e.metaKey;
  155. }
  156. addEventListener(root, 'mouseover', function (e) {
  157. if ('' != refStyle.innerHTML) {
  158. refStyle.innerHTML = '';
  159. }
  160. });
  161. a('mouseover', function (a) {
  162. if (a = idRx.exec(a.className)) {
  163. try {
  164. refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}';
  165. } catch (e) {
  166. }
  167. }
  168. });
  169. a('click', function (a, e) {
  170. if (/\bsf-dump-toggle\b/.test(a.className)) {
  171. e.preventDefault();
  172. if (!toggle(a, isCtrlKey(e))) {
  173. var r = doc.getElementById(a.getAttribute('href').substr(1)),
  174. s = r.previousSibling,
  175. f = r.parentNode,
  176. t = a.parentNode;
  177. t.replaceChild(r, a);
  178. f.replaceChild(a, s);
  179. t.insertBefore(s, r);
  180. f = f.firstChild.nodeValue.match(indentRx);
  181. t = t.firstChild.nodeValue.match(indentRx);
  182. if (f && t && f[0] !== t[0]) {
  183. r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]);
  184. }
  185. if (/\bsf-dump-compact\b/.test(r.className)) {
  186. toggle(s, isCtrlKey(e));
  187. }
  188. }
  189. if (doc.getSelection) {
  190. try {
  191. doc.getSelection().removeAllRanges();
  192. } catch (e) {
  193. doc.getSelection().empty();
  194. }
  195. } else {
  196. doc.selection.empty();
  197. }
  198. }
  199. });
  200. var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'),
  201. elt = root.getElementsByTagName('A'),
  202. len = elt.length,
  203. i = 0,
  204. t = [];
  205. while (i < len) t.push(elt[i++]);
  206. elt = root.getElementsByTagName('SAMP');
  207. len = elt.length;
  208. i = 0;
  209. while (i < len) t.push(elt[i++]);
  210. root = t;
  211. len = t.length;
  212. i = t = 0;
  213. while (i < len) {
  214. elt = root[i];
  215. if ("SAMP" == elt.tagName) {
  216. elt.className = "sf-dump-expanded";
  217. a = elt.previousSibling || {};
  218. if ('A' != a.tagName) {
  219. a = doc.createElement('A');
  220. a.className = 'sf-dump-ref';
  221. elt.parentNode.insertBefore(a, elt);
  222. } else {
  223. a.innerHTML += ' ';
  224. }
  225. a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children';
  226. a.innerHTML += '<span>▼</span>';
  227. a.className += ' sf-dump-toggle';
  228. if (!/\bsf-dump\b/.test(elt.parentNode.className)) {
  229. toggle(a);
  230. }
  231. } else if (/\bsf-dump-ref\b/.test(elt.className) && (a = elt.getAttribute('href'))) {
  232. a = a.substr(1);
  233. elt.className += ' '+a;
  234. if (/[\[{]$/.test(elt.previousSibling.nodeValue)) {
  235. a = a != elt.nextSibling.id && doc.getElementById(a);
  236. try {
  237. t = a.nextSibling;
  238. elt.appendChild(a);
  239. t.parentNode.insertBefore(a, t);
  240. if (/^[@#]/.test(elt.innerHTML)) {
  241. elt.innerHTML += ' <span>▶</span>';
  242. } else {
  243. elt.innerHTML = '<span>▶</span>';
  244. elt.className = 'sf-dump-ref';
  245. }
  246. elt.className += ' sf-dump-toggle';
  247. } catch (e) {
  248. if ('&' == elt.innerHTML.charAt(0)) {
  249. elt.innerHTML = '…';
  250. elt.className = 'sf-dump-ref';
  251. }
  252. }
  253. }
  254. }
  255. ++i;
  256. }
  257. };
  258. })(document);
  259. </script><style>
  260. pre.sf-dump {
  261. display: block;
  262. white-space: pre;
  263. padding: 5px;
  264. }
  265. pre.sf-dump span {
  266. display: inline;
  267. }
  268. pre.sf-dump .sf-dump-compact {
  269. display: none;
  270. }
  271. pre.sf-dump abbr {
  272. text-decoration: none;
  273. border: none;
  274. cursor: help;
  275. }
  276. pre.sf-dump a {
  277. text-decoration: none;
  278. cursor: pointer;
  279. border: 0;
  280. outline: none;
  281. }
  282. EOHTML;
  283. foreach ($this->styles as $class => $style) {
  284. $line .= 'pre.sf-dump'.('default' !== $class ? ' .sf-dump-'.$class : '').'{'.$style.'}';
  285. }
  286. return $this->dumpHeader = preg_replace('/\s+/', ' ', $line).'</style>'.$this->dumpHeader;
  287. }
  288. /**
  289. * {@inheritdoc}
  290. */
  291. public function enterHash(Cursor $cursor, $type, $class, $hasChild)
  292. {
  293. parent::enterHash($cursor, $type, $class, false);
  294. if ($hasChild) {
  295. if ($cursor->refIndex) {
  296. $r = Cursor::HASH_OBJECT !== $type ? 1 - (Cursor::HASH_RESOURCE !== $type) : 2;
  297. $r .= $r && 0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->refIndex;
  298. $this->line .= sprintf('<samp id=%s-ref%s>', $this->dumpId, $r);
  299. } else {
  300. $this->line .= '<samp>';
  301. }
  302. $this->dumpLine($cursor->depth);
  303. }
  304. }
  305. /**
  306. * {@inheritdoc}
  307. */
  308. public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut)
  309. {
  310. $this->dumpEllipsis($cursor, $hasChild, $cut);
  311. if ($hasChild) {
  312. $this->line .= '</samp>';
  313. }
  314. parent::leaveHash($cursor, $type, $class, $hasChild, 0);
  315. }
  316. /**
  317. * {@inheritdoc}
  318. */
  319. protected function style($style, $value, $attr = array())
  320. {
  321. if ('' === $value) {
  322. return '';
  323. }
  324. $v = esc($value);
  325. if ('ref' === $style) {
  326. if (empty($attr['count'])) {
  327. return sprintf('<a class=sf-dump-ref>%s</a>', $v);
  328. }
  329. $r = ('#' !== $v[0] ? 1 - ('@' !== $v[0]) : 2).substr($value, 1);
  330. return sprintf('<a class=sf-dump-ref href=#%s-ref%s title="%d occurrences">%s</a>', $this->dumpId, $r, 1 + $attr['count'], $v);
  331. }
  332. if ('const' === $style && isset($attr['value'])) {
  333. $style .= sprintf(' title="%s"', esc(is_scalar($attr['value']) ? $attr['value'] : json_encode($attr['value'])));
  334. } elseif ('public' === $style) {
  335. $style .= sprintf(' title="%s"', empty($attr['dynamic']) ? 'Public property' : 'Runtime added dynamic property');
  336. } elseif ('str' === $style && 1 < $attr['length']) {
  337. $style .= sprintf(' title="%d%s characters"', $attr['length'], $attr['binary'] ? ' binary or non-UTF-8' : '');
  338. } elseif ('note' === $style && false !== $c = strrpos($v, '\\')) {
  339. return sprintf('<abbr title="%s" class=sf-dump-%s>%s</abbr>', $v, $style, substr($v, $c + 1));
  340. } elseif ('protected' === $style) {
  341. $style .= ' title="Protected property"';
  342. } elseif ('private' === $style) {
  343. $style .= sprintf(' title="Private property defined in class:&#10;`%s`"', esc($attr['class']));
  344. }
  345. $map = static::$controlCharsMap;
  346. $style = "<span class=sf-dump-{$style}>";
  347. $v = preg_replace_callback(static::$controlCharsRx, function ($c) use ($map, $style) {
  348. $s = '</span>';
  349. $c = $c[$i = 0];
  350. do {
  351. $s .= isset($map[$c[$i]]) ? $map[$c[$i]] : sprintf('\x%02X', ord($c[$i]));
  352. } while (isset($c[++$i]));
  353. return $s.$style;
  354. }, $v, -1, $cchrCount);
  355. if ($cchrCount && '<' === $v[0]) {
  356. $v = substr($v, 7);
  357. } else {
  358. $v = $style.$v;
  359. }
  360. if ($cchrCount && '>' === substr($v, -1)) {
  361. $v = substr($v, 0, -strlen($style));
  362. } else {
  363. $v .= '</span>';
  364. }
  365. return $v;
  366. }
  367. /**
  368. * {@inheritdoc}
  369. */
  370. protected function dumpLine($depth, $endOfValue = false)
  371. {
  372. if (-1 === $this->lastDepth) {
  373. $this->line = sprintf($this->dumpPrefix, $this->dumpId, $this->indentPad).$this->line;
  374. }
  375. if ($this->headerIsDumped !== (null !== $this->outputStream ? $this->outputStream : $this->lineDumper)) {
  376. $this->line = $this->getDumpHeader().$this->line;
  377. }
  378. if (-1 === $depth) {
  379. $this->line .= sprintf($this->dumpSuffix, $this->dumpId);
  380. }
  381. $this->lastDepth = $depth;
  382. $this->line = mb_convert_encoding($this->line, 'HTML-ENTITIES', 'UTF-8');
  383. if (-1 === $depth) {
  384. AbstractDumper::dumpLine(0);
  385. }
  386. AbstractDumper::dumpLine($depth);
  387. }
  388. }
  389. function esc($str)
  390. {
  391. return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
  392. }