HtmlDumper.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. if (doc.createEvent && s.dispatchEvent) {
  127. var event = doc.createEvent('Event');
  128. event.initEvent('sf-dump-expanded' === newClass ? 'sfbeforedumpexpand' : 'sfbeforedumpcollapse', true, false);
  129. s.dispatchEvent(event);
  130. }
  131. a.lastChild.innerHTML = arrow;
  132. s.className = s.className.replace(/\bsf-dump-(compact|expanded)\b/, newClass);
  133. if (recursive) {
  134. try {
  135. a = s.querySelectorAll('.'+oldClass);
  136. for (s = 0; s < a.length; ++s) {
  137. if (-1 == a[s].className.indexOf(newClass)) {
  138. a[s].className = newClass;
  139. a[s].previousSibling.lastChild.innerHTML = arrow;
  140. }
  141. }
  142. } catch (e) {
  143. }
  144. }
  145. return true;
  146. };
  147. return function (root) {
  148. root = doc.getElementById(root);
  149. function a(e, f) {
  150. addEventListener(root, e, function (e) {
  151. if ('A' == e.target.tagName) {
  152. f(e.target, e);
  153. } else if ('A' == e.target.parentNode.tagName) {
  154. f(e.target.parentNode, e);
  155. }
  156. });
  157. };
  158. function isCtrlKey(e) {
  159. return e.ctrlKey || e.metaKey;
  160. }
  161. addEventListener(root, 'mouseover', function (e) {
  162. if ('' != refStyle.innerHTML) {
  163. refStyle.innerHTML = '';
  164. }
  165. });
  166. a('mouseover', function (a) {
  167. if (a = idRx.exec(a.className)) {
  168. try {
  169. refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}';
  170. } catch (e) {
  171. }
  172. }
  173. });
  174. a('click', function (a, e) {
  175. if (/\bsf-dump-toggle\b/.test(a.className)) {
  176. e.preventDefault();
  177. if (!toggle(a, isCtrlKey(e))) {
  178. var r = doc.getElementById(a.getAttribute('href').substr(1)),
  179. s = r.previousSibling,
  180. f = r.parentNode,
  181. t = a.parentNode;
  182. t.replaceChild(r, a);
  183. f.replaceChild(a, s);
  184. t.insertBefore(s, r);
  185. f = f.firstChild.nodeValue.match(indentRx);
  186. t = t.firstChild.nodeValue.match(indentRx);
  187. if (f && t && f[0] !== t[0]) {
  188. r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]);
  189. }
  190. if (/\bsf-dump-compact\b/.test(r.className)) {
  191. toggle(s, isCtrlKey(e));
  192. }
  193. }
  194. if (doc.getSelection) {
  195. try {
  196. doc.getSelection().removeAllRanges();
  197. } catch (e) {
  198. doc.getSelection().empty();
  199. }
  200. } else {
  201. doc.selection.empty();
  202. }
  203. }
  204. });
  205. var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'),
  206. elt = root.getElementsByTagName('A'),
  207. len = elt.length,
  208. i = 0,
  209. t = [];
  210. while (i < len) t.push(elt[i++]);
  211. elt = root.getElementsByTagName('SAMP');
  212. len = elt.length;
  213. i = 0;
  214. while (i < len) t.push(elt[i++]);
  215. root = t;
  216. len = t.length;
  217. i = t = 0;
  218. while (i < len) {
  219. elt = root[i];
  220. if ("SAMP" == elt.tagName) {
  221. elt.className = "sf-dump-expanded";
  222. a = elt.previousSibling || {};
  223. if ('A' != a.tagName) {
  224. a = doc.createElement('A');
  225. a.className = 'sf-dump-ref';
  226. elt.parentNode.insertBefore(a, elt);
  227. } else {
  228. a.innerHTML += ' ';
  229. }
  230. a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children';
  231. a.innerHTML += '<span>▼</span>';
  232. a.className += ' sf-dump-toggle';
  233. if (!/\bsf-dump\b/.test(elt.parentNode.className)) {
  234. toggle(a);
  235. }
  236. } else if (/\bsf-dump-ref\b/.test(elt.className) && (a = elt.getAttribute('href'))) {
  237. a = a.substr(1);
  238. elt.className += ' '+a;
  239. if (/[\[{]$/.test(elt.previousSibling.nodeValue)) {
  240. a = a != elt.nextSibling.id && doc.getElementById(a);
  241. try {
  242. t = a.nextSibling;
  243. elt.appendChild(a);
  244. t.parentNode.insertBefore(a, t);
  245. if (/^[@#]/.test(elt.innerHTML)) {
  246. elt.innerHTML += ' <span>▶</span>';
  247. } else {
  248. elt.innerHTML = '<span>▶</span>';
  249. elt.className = 'sf-dump-ref';
  250. }
  251. elt.className += ' sf-dump-toggle';
  252. } catch (e) {
  253. if ('&' == elt.innerHTML.charAt(0)) {
  254. elt.innerHTML = '…';
  255. elt.className = 'sf-dump-ref';
  256. }
  257. }
  258. }
  259. }
  260. ++i;
  261. }
  262. };
  263. })(document);
  264. </script><style>
  265. pre.sf-dump {
  266. display: block;
  267. white-space: pre;
  268. padding: 5px;
  269. }
  270. pre.sf-dump span {
  271. display: inline;
  272. }
  273. pre.sf-dump .sf-dump-compact {
  274. display: none;
  275. }
  276. pre.sf-dump abbr {
  277. text-decoration: none;
  278. border: none;
  279. cursor: help;
  280. }
  281. pre.sf-dump a {
  282. text-decoration: none;
  283. cursor: pointer;
  284. border: 0;
  285. outline: none;
  286. }
  287. EOHTML;
  288. foreach ($this->styles as $class => $style) {
  289. $line .= 'pre.sf-dump'.('default' !== $class ? ' .sf-dump-'.$class : '').'{'.$style.'}';
  290. }
  291. return $this->dumpHeader = preg_replace('/\s+/', ' ', $line).'</style>'.$this->dumpHeader;
  292. }
  293. /**
  294. * {@inheritdoc}
  295. */
  296. public function enterHash(Cursor $cursor, $type, $class, $hasChild)
  297. {
  298. parent::enterHash($cursor, $type, $class, false);
  299. if ($hasChild) {
  300. if ($cursor->refIndex) {
  301. $r = Cursor::HASH_OBJECT !== $type ? 1 - (Cursor::HASH_RESOURCE !== $type) : 2;
  302. $r .= $r && 0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->refIndex;
  303. $this->line .= sprintf('<samp id=%s-ref%s>', $this->dumpId, $r);
  304. } else {
  305. $this->line .= '<samp>';
  306. }
  307. $this->dumpLine($cursor->depth);
  308. }
  309. }
  310. /**
  311. * {@inheritdoc}
  312. */
  313. public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut)
  314. {
  315. $this->dumpEllipsis($cursor, $hasChild, $cut);
  316. if ($hasChild) {
  317. $this->line .= '</samp>';
  318. }
  319. parent::leaveHash($cursor, $type, $class, $hasChild, 0);
  320. }
  321. /**
  322. * {@inheritdoc}
  323. */
  324. protected function style($style, $value, $attr = array())
  325. {
  326. if ('' === $value) {
  327. return '';
  328. }
  329. $v = esc($value);
  330. if ('ref' === $style) {
  331. if (empty($attr['count'])) {
  332. return sprintf('<a class=sf-dump-ref>%s</a>', $v);
  333. }
  334. $r = ('#' !== $v[0] ? 1 - ('@' !== $v[0]) : 2).substr($value, 1);
  335. return sprintf('<a class=sf-dump-ref href=#%s-ref%s title="%d occurrences">%s</a>', $this->dumpId, $r, 1 + $attr['count'], $v);
  336. }
  337. if ('const' === $style && isset($attr['value'])) {
  338. $style .= sprintf(' title="%s"', esc(is_scalar($attr['value']) ? $attr['value'] : json_encode($attr['value'])));
  339. } elseif ('public' === $style) {
  340. $style .= sprintf(' title="%s"', empty($attr['dynamic']) ? 'Public property' : 'Runtime added dynamic property');
  341. } elseif ('str' === $style && 1 < $attr['length']) {
  342. $style .= sprintf(' title="%d%s characters"', $attr['length'], $attr['binary'] ? ' binary or non-UTF-8' : '');
  343. } elseif ('note' === $style && false !== $c = strrpos($v, '\\')) {
  344. return sprintf('<abbr title="%s" class=sf-dump-%s>%s</abbr>', $v, $style, substr($v, $c + 1));
  345. } elseif ('protected' === $style) {
  346. $style .= ' title="Protected property"';
  347. } elseif ('private' === $style) {
  348. $style .= sprintf(' title="Private property defined in class:&#10;`%s`"', esc($attr['class']));
  349. }
  350. $map = static::$controlCharsMap;
  351. $style = "<span class=sf-dump-{$style}>";
  352. $v = preg_replace_callback(static::$controlCharsRx, function ($c) use ($map, $style) {
  353. $s = '</span>';
  354. $c = $c[$i = 0];
  355. do {
  356. $s .= isset($map[$c[$i]]) ? $map[$c[$i]] : sprintf('\x%02X', ord($c[$i]));
  357. } while (isset($c[++$i]));
  358. return $s.$style;
  359. }, $v, -1, $cchrCount);
  360. if ($cchrCount && '<' === $v[0]) {
  361. $v = substr($v, 7);
  362. } else {
  363. $v = $style.$v;
  364. }
  365. if ($cchrCount && '>' === substr($v, -1)) {
  366. $v = substr($v, 0, -strlen($style));
  367. } else {
  368. $v .= '</span>';
  369. }
  370. return $v;
  371. }
  372. /**
  373. * {@inheritdoc}
  374. */
  375. protected function dumpLine($depth, $endOfValue = false)
  376. {
  377. if (-1 === $this->lastDepth) {
  378. $this->line = sprintf($this->dumpPrefix, $this->dumpId, $this->indentPad).$this->line;
  379. }
  380. if ($this->headerIsDumped !== (null !== $this->outputStream ? $this->outputStream : $this->lineDumper)) {
  381. $this->line = $this->getDumpHeader().$this->line;
  382. }
  383. if (-1 === $depth) {
  384. $this->line .= sprintf($this->dumpSuffix, $this->dumpId);
  385. }
  386. $this->lastDepth = $depth;
  387. $this->line = mb_convert_encoding($this->line, 'HTML-ENTITIES', 'UTF-8');
  388. if (-1 === $depth) {
  389. AbstractDumper::dumpLine(0);
  390. }
  391. AbstractDumper::dumpLine($depth);
  392. }
  393. }
  394. function esc($str)
  395. {
  396. return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
  397. }