4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\VarDumper\Dumper;
14 use Symfony\Component\VarDumper\Cloner\Cursor;
15 use Symfony\Component\VarDumper\Cloner\Data;
18 * HtmlDumper dumps variables as HTML.
20 * @author Nicolas Grekas <p@tchwork.com>
22 class HtmlDumper extends CliDumper
24 public static $defaultOutput = 'php://output';
26 protected $dumpHeader;
27 protected $dumpPrefix = '<pre class=sf-dump id=%s data-indent-pad="%s">';
28 protected $dumpSuffix = '</pre><script>Sfdump("%s")</script>';
29 protected $dumpId = 'sf-dump';
30 protected $colors = true;
31 protected $headerIsDumped = false;
32 protected $lastDepth = -1;
33 protected $styles = array(
34 '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',
35 'num' => 'font-weight:bold; color:#1299DA',
36 'const' => 'font-weight:bold',
37 'str' => 'font-weight:bold; color:#56DB3A',
38 'note' => 'color:#1299DA',
39 'ref' => 'color:#A0A0A0',
40 'public' => 'color:#FFFFFF',
41 'protected' => 'color:#FFFFFF',
42 'private' => 'color:#FFFFFF',
43 'meta' => 'color:#B729D9',
44 'key' => 'color:#56DB3A',
45 'index' => 'color:#1299DA',
51 public function __construct($output = null, $charset = null)
53 AbstractDumper::__construct($output, $charset);
54 $this->dumpId = 'sf-dump-'.mt_rand();
60 public function setStyles(array $styles)
62 $this->headerIsDumped = false;
63 $this->styles = $styles + $this->styles;
67 * Sets an HTML header that will be dumped once in the output stream.
69 * @param string $header An HTML string
71 public function setDumpHeader($header)
73 $this->dumpHeader = $header;
77 * Sets an HTML prefix and suffix that will encapse every single dump.
79 * @param string $prefix The prepended HTML string
80 * @param string $suffix The appended HTML string
82 public function setDumpBoundaries($prefix, $suffix)
84 $this->dumpPrefix = $prefix;
85 $this->dumpSuffix = $suffix;
91 public function dump(Data $data, $output = null)
93 parent::dump($data, $output);
94 $this->dumpId = 'sf-dump-'.mt_rand();
98 * Dumps the HTML header.
100 protected function getDumpHeader()
102 $this->headerIsDumped = null !== $this->outputStream ? $this->outputStream : $this->lineDumper;
104 if (null !== $this->dumpHeader) {
105 return $this->dumpHeader;
110 Sfdump = window.Sfdump || (function (doc) {
112 var refStyle = doc.createElement('style'),
113 rxEsc = /([.*+?^${}()|\[\]\/\\])/g,
114 idRx = /\bsf-dump-\d+-ref[012]\w+\b/,
115 keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl',
116 addEventListener = function (e, n, cb) {
117 e.addEventListener(n, cb, false);
120 (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle);
122 if (!doc.addEventListener) {
123 addEventListener = function (element, eventName, callback) {
124 element.attachEvent('on' + eventName, function (e) {
125 e.preventDefault = function () {e.returnValue = false;};
126 e.target = e.srcElement;
132 function toggle(a, recursive) {
133 var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass;
135 if ('sf-dump-compact' == oldClass) {
137 newClass = 'sf-dump-expanded';
138 } else if ('sf-dump-expanded' == oldClass) {
140 newClass = 'sf-dump-compact';
145 a.lastChild.innerHTML = arrow;
146 s.className = newClass;
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;
164 return function (root) {
165 root = doc.getElementById(root);
168 addEventListener(root, e, function (e) {
169 if ('A' == e.target.tagName) {
171 } else if ('A' == e.target.parentNode.tagName) {
172 f(e.target.parentNode, e);
176 function isCtrlKey(e) {
177 return e.ctrlKey || e.metaKey;
179 addEventListener(root, 'mouseover', function (e) {
180 if ('' != refStyle.innerHTML) {
181 refStyle.innerHTML = '';
184 a('mouseover', function (a) {
185 if (a = idRx.exec(a.className)) {
187 refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}';
192 a('click', function (a, e) {
193 if (/\bsf-dump-toggle\b/.test(a.className)) {
195 if (!toggle(a, isCtrlKey(e))) {
196 var r = doc.getElementById(a.getAttribute('href').substr(1)),
197 s = r.previousSibling,
200 t.replaceChild(r, a);
201 f.replaceChild(a, s);
202 t.insertBefore(s, r);
203 f = f.firstChild.nodeValue.match(indentRx);
204 t = t.firstChild.nodeValue.match(indentRx);
205 if (f && t && f[0] !== t[0]) {
206 r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]);
208 if ('sf-dump-compact' == r.className) {
209 toggle(s, isCtrlKey(e));
213 if (doc.getSelection) {
215 doc.getSelection().removeAllRanges();
217 doc.getSelection().empty();
220 doc.selection.empty();
225 var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'),
226 elt = root.getElementsByTagName('A'),
231 while (i < len) t.push(elt[i++]);
233 elt = root.getElementsByTagName('SAMP');
237 while (i < len) t.push(elt[i++]);
245 if ("SAMP" == elt.tagName) {
246 elt.className = "sf-dump-expanded";
247 a = elt.previousSibling || {};
248 if ('A' != a.tagName) {
249 a = doc.createElement('A');
250 a.className = 'sf-dump-ref';
251 elt.parentNode.insertBefore(a, elt);
255 a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children';
256 a.innerHTML += '<span>▼</span>';
257 a.className += ' sf-dump-toggle';
258 if ('sf-dump' != elt.parentNode.className) {
261 } else if ("sf-dump-ref" == elt.className && (a = elt.getAttribute('href'))) {
263 elt.className += ' '+a;
265 if (/[\[{]$/.test(elt.previousSibling.nodeValue)) {
266 a = a != elt.nextSibling.id && doc.getElementById(a);
270 t.parentNode.insertBefore(a, t);
271 if (/^[@#]/.test(elt.innerHTML)) {
272 elt.innerHTML += ' <span>▶</span>';
274 elt.innerHTML = '<span>▶</span>';
275 elt.className = 'sf-dump-ref';
277 elt.className += ' sf-dump-toggle';
279 if ('&' == elt.innerHTML.charAt(0)) {
281 elt.className = 'sf-dump-ref';
300 pre.sf-dump .sf-dump-compact {
304 text-decoration: none;
309 text-decoration: none;
316 foreach ($this->styles as $class => $style) {
317 $line .= 'pre.sf-dump'.('default' !== $class ? ' .sf-dump-'.$class : '').'{'.$style.'}';
320 return $this->dumpHeader = preg_replace('/\s+/', ' ', $line).'</style>'.$this->dumpHeader;
326 public function enterHash(Cursor $cursor, $type, $class, $hasChild)
328 parent::enterHash($cursor, $type, $class, false);
331 if ($cursor->refIndex) {
332 $r = Cursor::HASH_OBJECT !== $type ? 1 - (Cursor::HASH_RESOURCE !== $type) : 2;
333 $r .= $r && 0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->refIndex;
335 $this->line .= sprintf('<samp id=%s-ref%s>', $this->dumpId, $r);
337 $this->line .= '<samp>';
339 $this->dumpLine($cursor->depth);
346 public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut)
348 $this->dumpEllipsis($cursor, $hasChild, $cut);
350 $this->line .= '</samp>';
352 parent::leaveHash($cursor, $type, $class, $hasChild, 0);
358 protected function style($style, $value, $attr = array())
366 if ('ref' === $style) {
367 if (empty($attr['count'])) {
368 return sprintf('<a class=sf-dump-ref>%s</a>', $v);
370 $r = ('#' !== $v[0] ? 1 - ('@' !== $v[0]) : 2).substr($value, 1);
372 return sprintf('<a class=sf-dump-ref href=#%s-ref%s title="%d occurrences">%s</a>', $this->dumpId, $r, 1 + $attr['count'], $v);
375 if ('const' === $style && isset($attr['value'])) {
376 $style .= sprintf(' title="%s"', esc(is_scalar($attr['value']) ? $attr['value'] : json_encode($attr['value'])));
377 } elseif ('public' === $style) {
378 $style .= sprintf(' title="%s"', empty($attr['dynamic']) ? 'Public property' : 'Runtime added dynamic property');
379 } elseif ('str' === $style && 1 < $attr['length']) {
380 $style .= sprintf(' title="%d%s characters"', $attr['length'], $attr['binary'] ? ' binary or non-UTF-8' : '');
381 } elseif ('note' === $style && false !== $c = strrpos($v, '\\')) {
382 return sprintf('<abbr title="%s" class=sf-dump-%s>%s</abbr>', $v, $style, substr($v, $c + 1));
383 } elseif ('protected' === $style) {
384 $style .= ' title="Protected property"';
385 } elseif ('private' === $style) {
386 $style .= sprintf(' title="Private property defined in class: `%s`"', esc($attr['class']));
389 $map = static::$controlCharsMap;
390 $style = "<span class=sf-dump-{$style}>";
391 $v = preg_replace_callback(static::$controlCharsRx, function ($c) use ($map, $style) {
395 $s .= isset($map[$c[$i]]) ? $map[$c[$i]] : sprintf('\x%02X', ord($c[$i]));
396 } while (isset($c[++$i]));
399 }, $v, -1, $cchrCount);
401 if ($cchrCount && '<' === $v[0]) {
406 if ($cchrCount && '>' === substr($v, -1)) {
407 $v = substr($v, 0, -strlen($style));
418 protected function dumpLine($depth, $endOfValue = false)
420 if (-1 === $this->lastDepth) {
421 $this->line = sprintf($this->dumpPrefix, $this->dumpId, $this->indentPad).$this->line;
423 if ($this->headerIsDumped !== (null !== $this->outputStream ? $this->outputStream : $this->lineDumper)) {
424 $this->line = $this->getDumpHeader().$this->line;
428 $this->line .= sprintf($this->dumpSuffix, $this->dumpId);
430 $this->lastDepth = $depth;
432 $this->line = mb_convert_encoding($this->line, 'HTML-ENTITIES', 'UTF-8');
435 AbstractDumper::dumpLine(0);
437 AbstractDumper::dumpLine($depth);
443 return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');