1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\VarDumper\Dumper;
13
14use Symfony\Component\VarDumper\Cloner\Cursor;
15use Symfony\Component\VarDumper\Cloner\Data;
16
17/**
18 * HtmlDumper dumps variables as HTML.
19 *
20 * @author Nicolas Grekas <p@tchwork.com>
21 */
22class HtmlDumper extends CliDumper
23{
24    public static $defaultOutput = 'php://output';
25
26    protected static $themes = [
27        'dark' => [
28            '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: break-all',
29            'num' => 'font-weight:bold; color:#1299DA',
30            'const' => 'font-weight:bold',
31            'str' => 'font-weight:bold; color:#56DB3A',
32            'note' => 'color:#1299DA',
33            'ref' => 'color:#A0A0A0',
34            'public' => 'color:#FFFFFF',
35            'protected' => 'color:#FFFFFF',
36            'private' => 'color:#FFFFFF',
37            'meta' => 'color:#B729D9',
38            'key' => 'color:#56DB3A',
39            'index' => 'color:#1299DA',
40            'ellipsis' => 'color:#FF8400',
41            'ns' => 'user-select:none;',
42        ],
43        'light' => [
44            'default' => 'background:none; color:#CC7832; 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: break-all',
45            'num' => 'font-weight:bold; color:#1299DA',
46            'const' => 'font-weight:bold',
47            'str' => 'font-weight:bold; color:#629755;',
48            'note' => 'color:#6897BB',
49            'ref' => 'color:#6E6E6E',
50            'public' => 'color:#262626',
51            'protected' => 'color:#262626',
52            'private' => 'color:#262626',
53            'meta' => 'color:#B729D9',
54            'key' => 'color:#789339',
55            'index' => 'color:#1299DA',
56            'ellipsis' => 'color:#CC7832',
57            'ns' => 'user-select:none;',
58        ],
59    ];
60
61    protected $dumpHeader;
62    protected $dumpPrefix = '<pre class=sf-dump id=%s data-indent-pad="%s">';
63    protected $dumpSuffix = '</pre><script>Sfdump(%s)</script>';
64    protected $dumpId = 'sf-dump';
65    protected $colors = true;
66    protected $headerIsDumped = false;
67    protected $lastDepth = -1;
68    protected $styles;
69
70    private $displayOptions = [
71        'maxDepth' => 1,
72        'maxStringLength' => 160,
73        'fileLinkFormat' => null,
74    ];
75    private $extraDisplayOptions = [];
76
77    /**
78     * {@inheritdoc}
79     */
80    public function __construct($output = null, string $charset = null, int $flags = 0)
81    {
82        AbstractDumper::__construct($output, $charset, $flags);
83        $this->dumpId = 'sf-dump-'.mt_rand();
84        $this->displayOptions['fileLinkFormat'] = ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
85        $this->styles = static::$themes['dark'] ?? self::$themes['dark'];
86    }
87
88    /**
89     * {@inheritdoc}
90     */
91    public function setStyles(array $styles)
92    {
93        $this->headerIsDumped = false;
94        $this->styles = $styles + $this->styles;
95    }
96
97    public function setTheme(string $themeName)
98    {
99        if (!isset(static::$themes[$themeName])) {
100            throw new \InvalidArgumentException(sprintf('Theme "%s" does not exist in class "%s".', $themeName, static::class));
101        }
102
103        $this->setStyles(static::$themes[$themeName]);
104    }
105
106    /**
107     * Configures display options.
108     *
109     * @param array $displayOptions A map of display options to customize the behavior
110     */
111    public function setDisplayOptions(array $displayOptions)
112    {
113        $this->headerIsDumped = false;
114        $this->displayOptions = $displayOptions + $this->displayOptions;
115    }
116
117    /**
118     * Sets an HTML header that will be dumped once in the output stream.
119     *
120     * @param string $header An HTML string
121     */
122    public function setDumpHeader($header)
123    {
124        $this->dumpHeader = $header;
125    }
126
127    /**
128     * Sets an HTML prefix and suffix that will encapse every single dump.
129     *
130     * @param string $prefix The prepended HTML string
131     * @param string $suffix The appended HTML string
132     */
133    public function setDumpBoundaries($prefix, $suffix)
134    {
135        $this->dumpPrefix = $prefix;
136        $this->dumpSuffix = $suffix;
137    }
138
139    /**
140     * {@inheritdoc}
141     */
142    public function dump(Data $data, $output = null, array $extraDisplayOptions = [])
143    {
144        $this->extraDisplayOptions = $extraDisplayOptions;
145        $result = parent::dump($data, $output);
146        $this->dumpId = 'sf-dump-'.mt_rand();
147
148        return $result;
149    }
150
151    /**
152     * Dumps the HTML header.
153     */
154    protected function getDumpHeader()
155    {
156        $this->headerIsDumped = null !== $this->outputStream ? $this->outputStream : $this->lineDumper;
157
158        if (null !== $this->dumpHeader) {
159            return $this->dumpHeader;
160        }
161
162        $line = str_replace('{$options}', json_encode($this->displayOptions, \JSON_FORCE_OBJECT), <<<'EOHTML'
163<script>
164Sfdump = window.Sfdump || (function (doc) {
165
166var refStyle = doc.createElement('style'),
167    rxEsc = /([.*+?^${}()|\[\]\/\\])/g,
168    idRx = /\bsf-dump-\d+-ref[012]\w+\b/,
169    keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl',
170    addEventListener = function (e, n, cb) {
171        e.addEventListener(n, cb, false);
172    };
173
174refStyle.innerHTML = 'pre.sf-dump .sf-dump-compact, .sf-dump-str-collapse .sf-dump-str-collapse, .sf-dump-str-expand .sf-dump-str-expand { display: none; }';
175(doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle);
176refStyle = doc.createElement('style');
177(doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle);
178
179if (!doc.addEventListener) {
180    addEventListener = function (element, eventName, callback) {
181        element.attachEvent('on' + eventName, function (e) {
182            e.preventDefault = function () {e.returnValue = false;};
183            e.target = e.srcElement;
184            callback(e);
185        });
186    };
187}
188
189function toggle(a, recursive) {
190    var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass;
191
192    if (/\bsf-dump-compact\b/.test(oldClass)) {
193        arrow = '▼';
194        newClass = 'sf-dump-expanded';
195    } else if (/\bsf-dump-expanded\b/.test(oldClass)) {
196        arrow = '▶';
197        newClass = 'sf-dump-compact';
198    } else {
199        return false;
200    }
201
202    if (doc.createEvent && s.dispatchEvent) {
203        var event = doc.createEvent('Event');
204        event.initEvent('sf-dump-expanded' === newClass ? 'sfbeforedumpexpand' : 'sfbeforedumpcollapse', true, false);
205
206        s.dispatchEvent(event);
207    }
208
209    a.lastChild.innerHTML = arrow;
210    s.className = s.className.replace(/\bsf-dump-(compact|expanded)\b/, newClass);
211
212    if (recursive) {
213        try {
214            a = s.querySelectorAll('.'+oldClass);
215            for (s = 0; s < a.length; ++s) {
216                if (-1 == a[s].className.indexOf(newClass)) {
217                    a[s].className = newClass;
218                    a[s].previousSibling.lastChild.innerHTML = arrow;
219                }
220            }
221        } catch (e) {
222        }
223    }
224
225    return true;
226};
227
228function collapse(a, recursive) {
229    var s = a.nextSibling || {}, oldClass = s.className;
230
231    if (/\bsf-dump-expanded\b/.test(oldClass)) {
232        toggle(a, recursive);
233
234        return true;
235    }
236
237    return false;
238};
239
240function expand(a, recursive) {
241    var s = a.nextSibling || {}, oldClass = s.className;
242
243    if (/\bsf-dump-compact\b/.test(oldClass)) {
244        toggle(a, recursive);
245
246        return true;
247    }
248
249    return false;
250};
251
252function collapseAll(root) {
253    var a = root.querySelector('a.sf-dump-toggle');
254    if (a) {
255        collapse(a, true);
256        expand(a);
257
258        return true;
259    }
260
261    return false;
262}
263
264function reveal(node) {
265    var previous, parents = [];
266
267    while ((node = node.parentNode || {}) && (previous = node.previousSibling) && 'A' === previous.tagName) {
268        parents.push(previous);
269    }
270
271    if (0 !== parents.length) {
272        parents.forEach(function (parent) {
273            expand(parent);
274        });
275
276        return true;
277    }
278
279    return false;
280}
281
282function highlight(root, activeNode, nodes) {
283    resetHighlightedNodes(root);
284
285    Array.from(nodes||[]).forEach(function (node) {
286        if (!/\bsf-dump-highlight\b/.test(node.className)) {
287            node.className = node.className + ' sf-dump-highlight';
288        }
289    });
290
291    if (!/\bsf-dump-highlight-active\b/.test(activeNode.className)) {
292        activeNode.className = activeNode.className + ' sf-dump-highlight-active';
293    }
294}
295
296function resetHighlightedNodes(root) {
297    Array.from(root.querySelectorAll('.sf-dump-str, .sf-dump-key, .sf-dump-public, .sf-dump-protected, .sf-dump-private')).forEach(function (strNode) {
298        strNode.className = strNode.className.replace(/\bsf-dump-highlight\b/, '');
299        strNode.className = strNode.className.replace(/\bsf-dump-highlight-active\b/, '');
300    });
301}
302
303return function (root, x) {
304    root = doc.getElementById(root);
305
306    var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || '  ').replace(rxEsc, '\\$1')+')+', 'm'),
307        options = {$options},
308        elt = root.getElementsByTagName('A'),
309        len = elt.length,
310        i = 0, s, h,
311        t = [];
312
313    while (i < len) t.push(elt[i++]);
314
315    for (i in x) {
316        options[i] = x[i];
317    }
318
319    function a(e, f) {
320        addEventListener(root, e, function (e, n) {
321            if ('A' == e.target.tagName) {
322                f(e.target, e);
323            } else if ('A' == e.target.parentNode.tagName) {
324                f(e.target.parentNode, e);
325            } else {
326                n = /\bsf-dump-ellipsis\b/.test(e.target.className) ? e.target.parentNode : e.target;
327
328                if ((n = n.nextElementSibling) && 'A' == n.tagName) {
329                    if (!/\bsf-dump-toggle\b/.test(n.className)) {
330                        n = n.nextElementSibling || n;
331                    }
332
333                    f(n, e, true);
334                }
335            }
336        });
337    };
338    function isCtrlKey(e) {
339        return e.ctrlKey || e.metaKey;
340    }
341    function xpathString(str) {
342        var parts = str.match(/[^'"]+|['"]/g).map(function (part) {
343            if ("'" == part)  {
344                return '"\'"';
345            }
346            if ('"' == part) {
347                return "'\"'";
348            }
349
350            return "'" + part + "'";
351        });
352
353        return "concat(" + parts.join(",") + ", '')";
354    }
355    function xpathHasClass(className) {
356        return "contains(concat(' ', normalize-space(@class), ' '), ' " + className +" ')";
357    }
358    addEventListener(root, 'mouseover', function (e) {
359        if ('' != refStyle.innerHTML) {
360            refStyle.innerHTML = '';
361        }
362    });
363    a('mouseover', function (a, e, c) {
364        if (c) {
365            e.target.style.cursor = "pointer";
366        } else if (a = idRx.exec(a.className)) {
367            try {
368                refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}';
369            } catch (e) {
370            }
371        }
372    });
373    a('click', function (a, e, c) {
374        if (/\bsf-dump-toggle\b/.test(a.className)) {
375            e.preventDefault();
376            if (!toggle(a, isCtrlKey(e))) {
377                var r = doc.getElementById(a.getAttribute('href').substr(1)),
378                    s = r.previousSibling,
379                    f = r.parentNode,
380                    t = a.parentNode;
381                t.replaceChild(r, a);
382                f.replaceChild(a, s);
383                t.insertBefore(s, r);
384                f = f.firstChild.nodeValue.match(indentRx);
385                t = t.firstChild.nodeValue.match(indentRx);
386                if (f && t && f[0] !== t[0]) {
387                    r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]);
388                }
389                if (/\bsf-dump-compact\b/.test(r.className)) {
390                    toggle(s, isCtrlKey(e));
391                }
392            }
393
394            if (c) {
395            } else if (doc.getSelection) {
396                try {
397                    doc.getSelection().removeAllRanges();
398                } catch (e) {
399                    doc.getSelection().empty();
400                }
401            } else {
402                doc.selection.empty();
403            }
404        } else if (/\bsf-dump-str-toggle\b/.test(a.className)) {
405            e.preventDefault();
406            e = a.parentNode.parentNode;
407            e.className = e.className.replace(/\bsf-dump-str-(expand|collapse)\b/, a.parentNode.className);
408        }
409    });
410
411    elt = root.getElementsByTagName('SAMP');
412    len = elt.length;
413    i = 0;
414
415    while (i < len) t.push(elt[i++]);
416    len = t.length;
417
418    for (i = 0; i < len; ++i) {
419        elt = t[i];
420        if ('SAMP' == elt.tagName) {
421            a = elt.previousSibling || {};
422            if ('A' != a.tagName) {
423                a = doc.createElement('A');
424                a.className = 'sf-dump-ref';
425                elt.parentNode.insertBefore(a, elt);
426            } else {
427                a.innerHTML += ' ';
428            }
429            a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children';
430            a.innerHTML += elt.className == 'sf-dump-compact' ? '<span>▶</span>' : '<span>▼</span>';
431            a.className += ' sf-dump-toggle';
432
433            x = 1;
434            if ('sf-dump' != elt.parentNode.className) {
435                x += elt.parentNode.getAttribute('data-depth')/1;
436            }
437        } else if (/\bsf-dump-ref\b/.test(elt.className) && (a = elt.getAttribute('href'))) {
438            a = a.substr(1);
439            elt.className += ' '+a;
440
441            if (/[\[{]$/.test(elt.previousSibling.nodeValue)) {
442                a = a != elt.nextSibling.id && doc.getElementById(a);
443                try {
444                    s = a.nextSibling;
445                    elt.appendChild(a);
446                    s.parentNode.insertBefore(a, s);
447                    if (/^[@#]/.test(elt.innerHTML)) {
448                        elt.innerHTML += ' <span>▶</span>';
449                    } else {
450                        elt.innerHTML = '<span>▶</span>';
451                        elt.className = 'sf-dump-ref';
452                    }
453                    elt.className += ' sf-dump-toggle';
454                } catch (e) {
455                    if ('&' == elt.innerHTML.charAt(0)) {
456                        elt.innerHTML = '…';
457                        elt.className = 'sf-dump-ref';
458                    }
459                }
460            }
461        }
462    }
463
464    if (doc.evaluate && Array.from && root.children.length > 1) {
465        root.setAttribute('tabindex', 0);
466
467        SearchState = function () {
468            this.nodes = [];
469            this.idx = 0;
470        };
471        SearchState.prototype = {
472            next: function () {
473                if (this.isEmpty()) {
474                    return this.current();
475                }
476                this.idx = this.idx < (this.nodes.length - 1) ? this.idx + 1 : 0;
477
478                return this.current();
479            },
480            previous: function () {
481                if (this.isEmpty()) {
482                    return this.current();
483                }
484                this.idx = this.idx > 0 ? this.idx - 1 : (this.nodes.length - 1);
485
486                return this.current();
487            },
488            isEmpty: function () {
489                return 0 === this.count();
490            },
491            current: function () {
492                if (this.isEmpty()) {
493                    return null;
494                }
495                return this.nodes[this.idx];
496            },
497            reset: function () {
498                this.nodes = [];
499                this.idx = 0;
500            },
501            count: function () {
502                return this.nodes.length;
503            },
504        };
505
506        function showCurrent(state)
507        {
508            var currentNode = state.current(), currentRect, searchRect;
509            if (currentNode) {
510                reveal(currentNode);
511                highlight(root, currentNode, state.nodes);
512                if ('scrollIntoView' in currentNode) {
513                    currentNode.scrollIntoView(true);
514                    currentRect = currentNode.getBoundingClientRect();
515                    searchRect = search.getBoundingClientRect();
516                    if (currentRect.top < (searchRect.top + searchRect.height)) {
517                        window.scrollBy(0, -(searchRect.top + searchRect.height + 5));
518                    }
519                }
520            }
521            counter.textContent = (state.isEmpty() ? 0 : state.idx + 1) + ' of ' + state.count();
522        }
523
524        var search = doc.createElement('div');
525        search.className = 'sf-dump-search-wrapper sf-dump-search-hidden';
526        search.innerHTML = '
527            <input type="text" class="sf-dump-search-input">
528            <span class="sf-dump-search-count">0 of 0<\/span>
529            <button type="button" class="sf-dump-search-input-previous" tabindex="-1">
530                <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1683 1331l-166 165q-19 19-45 19t-45-19L896 965l-531 531q-19 19-45 19t-45-19l-166-165q-19-19-19-45.5t19-45.5l742-741q19-19 45-19t45 19l742 741q19 19 19 45.5t-19 45.5z"\/><\/svg>
531            <\/button>
532            <button type="button" class="sf-dump-search-input-next" tabindex="-1">
533                <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1683 808l-742 741q-19 19-45 19t-45-19L109 808q-19-19-19-45.5t19-45.5l166-165q19-19 45-19t45 19l531 531 531-531q19-19 45-19t45 19l166 165q19 19 19 45.5t-19 45.5z"\/><\/svg>
534            <\/button>
535        ';
536        root.insertBefore(search, root.firstChild);
537
538        var state = new SearchState();
539        var searchInput = search.querySelector('.sf-dump-search-input');
540        var counter = search.querySelector('.sf-dump-search-count');
541        var searchInputTimer = 0;
542        var previousSearchQuery = '';
543
544        addEventListener(searchInput, 'keyup', function (e) {
545            var searchQuery = e.target.value;
546            /* Don't perform anything if the pressed key didn't change the query */
547            if (searchQuery === previousSearchQuery) {
548                return;
549            }
550            previousSearchQuery = searchQuery;
551            clearTimeout(searchInputTimer);
552            searchInputTimer = setTimeout(function () {
553                state.reset();
554                collapseAll(root);
555                resetHighlightedNodes(root);
556                if ('' === searchQuery) {
557                    counter.textContent = '0 of 0';
558
559                    return;
560                }
561
562                var classMatches = [
563                    "sf-dump-str",
564                    "sf-dump-key",
565                    "sf-dump-public",
566                    "sf-dump-protected",
567                    "sf-dump-private",
568                ].map(xpathHasClass).join(' or ');
569
570                var xpathResult = doc.evaluate('.//span[' + classMatches + '][contains(translate(child::text(), ' + xpathString(searchQuery.toUpperCase()) + ', ' + xpathString(searchQuery.toLowerCase()) + '), ' + xpathString(searchQuery.toLowerCase()) + ')]', root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
571
572                while (node = xpathResult.iterateNext()) state.nodes.push(node);
573
574                showCurrent(state);
575            }, 400);
576        });
577
578        Array.from(search.querySelectorAll('.sf-dump-search-input-next, .sf-dump-search-input-previous')).forEach(function (btn) {
579            addEventListener(btn, 'click', function (e) {
580                e.preventDefault();
581                -1 !== e.target.className.indexOf('next') ? state.next() : state.previous();
582                searchInput.focus();
583                collapseAll(root);
584                showCurrent(state);
585            })
586        });
587
588        addEventListener(root, 'keydown', function (e) {
589            var isSearchActive = !/\bsf-dump-search-hidden\b/.test(search.className);
590            if ((114 === e.keyCode && !isSearchActive) || (isCtrlKey(e) && 70 === e.keyCode)) {
591                /* F3 or CMD/CTRL + F */
592                if (70 === e.keyCode && document.activeElement === searchInput) {
593                   /*
594                    * If CMD/CTRL + F is hit while having focus on search input,
595                    * the user probably meant to trigger browser search instead.
596                    * Let the browser execute its behavior:
597                    */
598                    return;
599                }
600
601                e.preventDefault();
602                search.className = search.className.replace(/\bsf-dump-search-hidden\b/, '');
603                searchInput.focus();
604            } else if (isSearchActive) {
605                if (27 === e.keyCode) {
606                    /* ESC key */
607                    search.className += ' sf-dump-search-hidden';
608                    e.preventDefault();
609                    resetHighlightedNodes(root);
610                    searchInput.value = '';
611                } else if (
612                    (isCtrlKey(e) && 71 === e.keyCode) /* CMD/CTRL + G */
613                    || 13 === e.keyCode /* Enter */
614                    || 114 === e.keyCode /* F3 */
615                ) {
616                    e.preventDefault();
617                    e.shiftKey ? state.previous() : state.next();
618                    collapseAll(root);
619                    showCurrent(state);
620                }
621            }
622        });
623    }
624
625    if (0 >= options.maxStringLength) {
626        return;
627    }
628    try {
629        elt = root.querySelectorAll('.sf-dump-str');
630        len = elt.length;
631        i = 0;
632        t = [];
633
634        while (i < len) t.push(elt[i++]);
635        len = t.length;
636
637        for (i = 0; i < len; ++i) {
638            elt = t[i];
639            s = elt.innerText || elt.textContent;
640            x = s.length - options.maxStringLength;
641            if (0 < x) {
642                h = elt.innerHTML;
643                elt[elt.innerText ? 'innerText' : 'textContent'] = s.substring(0, options.maxStringLength);
644                elt.className += ' sf-dump-str-collapse';
645                elt.innerHTML = '<span class=sf-dump-str-collapse>'+h+'<a class="sf-dump-ref sf-dump-str-toggle" title="Collapse"> ◀</a></span>'+
646                    '<span class=sf-dump-str-expand>'+elt.innerHTML+'<a class="sf-dump-ref sf-dump-str-toggle" title="'+x+' remaining characters"> ▶</a></span>';
647            }
648        }
649    } catch (e) {
650    }
651};
652
653})(document);
654</script><style>
655pre.sf-dump {
656    display: block;
657    white-space: pre;
658    padding: 5px;
659    overflow: initial !important;
660}
661pre.sf-dump:after {
662   content: "";
663   visibility: hidden;
664   display: block;
665   height: 0;
666   clear: both;
667}
668pre.sf-dump span {
669    display: inline;
670}
671pre.sf-dump a {
672    text-decoration: none;
673    cursor: pointer;
674    border: 0;
675    outline: none;
676    color: inherit;
677}
678pre.sf-dump img {
679    max-width: 50em;
680    max-height: 50em;
681    margin: .5em 0 0 0;
682    padding: 0;
683    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAHUlEQVQY02O8zAABilCaiQEN0EeA8QuUcX9g3QEAAjcC5piyhyEAAAAASUVORK5CYII=) #D3D3D3;
684}
685pre.sf-dump .sf-dump-ellipsis {
686    display: inline-block;
687    overflow: visible;
688    text-overflow: ellipsis;
689    max-width: 5em;
690    white-space: nowrap;
691    overflow: hidden;
692    vertical-align: top;
693}
694pre.sf-dump .sf-dump-ellipsis+.sf-dump-ellipsis {
695    max-width: none;
696}
697pre.sf-dump code {
698    display:inline;
699    padding:0;
700    background:none;
701}
702.sf-dump-public.sf-dump-highlight,
703.sf-dump-protected.sf-dump-highlight,
704.sf-dump-private.sf-dump-highlight,
705.sf-dump-str.sf-dump-highlight,
706.sf-dump-key.sf-dump-highlight {
707    background: rgba(111, 172, 204, 0.3);
708    border: 1px solid #7DA0B1;
709    border-radius: 3px;
710}
711.sf-dump-public.sf-dump-highlight-active,
712.sf-dump-protected.sf-dump-highlight-active,
713.sf-dump-private.sf-dump-highlight-active,
714.sf-dump-str.sf-dump-highlight-active,
715.sf-dump-key.sf-dump-highlight-active {
716    background: rgba(253, 175, 0, 0.4);
717    border: 1px solid #ffa500;
718    border-radius: 3px;
719}
720pre.sf-dump .sf-dump-search-hidden {
721    display: none !important;
722}
723pre.sf-dump .sf-dump-search-wrapper {
724    font-size: 0;
725    white-space: nowrap;
726    margin-bottom: 5px;
727    display: flex;
728    position: -webkit-sticky;
729    position: sticky;
730    top: 5px;
731}
732pre.sf-dump .sf-dump-search-wrapper > * {
733    vertical-align: top;
734    box-sizing: border-box;
735    height: 21px;
736    font-weight: normal;
737    border-radius: 0;
738    background: #FFF;
739    color: #757575;
740    border: 1px solid #BBB;
741}
742pre.sf-dump .sf-dump-search-wrapper > input.sf-dump-search-input {
743    padding: 3px;
744    height: 21px;
745    font-size: 12px;
746    border-right: none;
747    border-top-left-radius: 3px;
748    border-bottom-left-radius: 3px;
749    color: #000;
750    min-width: 15px;
751    width: 100%;
752}
753pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next,
754pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous {
755    background: #F2F2F2;
756    outline: none;
757    border-left: none;
758    font-size: 0;
759    line-height: 0;
760}
761pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next {
762    border-top-right-radius: 3px;
763    border-bottom-right-radius: 3px;
764}
765pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next > svg,
766pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous > svg {
767    pointer-events: none;
768    width: 12px;
769    height: 12px;
770}
771pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-count {
772    display: inline-block;
773    padding: 0 5px;
774    margin: 0;
775    border-left: none;
776    line-height: 21px;
777    font-size: 12px;
778}
779EOHTML
780        );
781
782        foreach ($this->styles as $class => $style) {
783            $line .= 'pre.sf-dump'.('default' === $class ? ', pre.sf-dump' : '').' .sf-dump-'.$class.'{'.$style.'}';
784        }
785        $line .= 'pre.sf-dump .sf-dump-ellipsis-note{'.$this->styles['note'].'}';
786
787        return $this->dumpHeader = preg_replace('/\s+/', ' ', $line).'</style>'.$this->dumpHeader;
788    }
789
790    /**
791     * {@inheritdoc}
792     */
793    public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut)
794    {
795        if ('' === $str && isset($cursor->attr['img-data'], $cursor->attr['content-type'])) {
796            $this->dumpKey($cursor);
797            $this->line .= $this->style('default', $cursor->attr['img-size'] ?? '', []);
798            $this->line .= $cursor->depth >= $this->displayOptions['maxDepth'] ? ' <samp class=sf-dump-compact>' : ' <samp class=sf-dump-expanded>';
799            $this->endValue($cursor);
800            $this->line .= $this->indentPad;
801            $this->line .= sprintf('<img src="data:%s;base64,%s" /></samp>', $cursor->attr['content-type'], base64_encode($cursor->attr['img-data']));
802            $this->endValue($cursor);
803        } else {
804            parent::dumpString($cursor, $str, $bin, $cut);
805        }
806    }
807
808    /**
809     * {@inheritdoc}
810     */
811    public function enterHash(Cursor $cursor, int $type, $class, bool $hasChild)
812    {
813        if (Cursor::HASH_OBJECT === $type) {
814            $cursor->attr['depth'] = $cursor->depth;
815        }
816        parent::enterHash($cursor, $type, $class, false);
817
818        if ($cursor->skipChildren || $cursor->depth >= $this->displayOptions['maxDepth']) {
819            $cursor->skipChildren = false;
820            $eol = ' class=sf-dump-compact>';
821        } else {
822            $this->expandNextHash = false;
823            $eol = ' class=sf-dump-expanded>';
824        }
825
826        if ($hasChild) {
827            $this->line .= '<samp data-depth='.($cursor->depth + 1);
828            if ($cursor->refIndex) {
829                $r = Cursor::HASH_OBJECT !== $type ? 1 - (Cursor::HASH_RESOURCE !== $type) : 2;
830                $r .= $r && 0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->refIndex;
831
832                $this->line .= sprintf(' id=%s-ref%s', $this->dumpId, $r);
833            }
834            $this->line .= $eol;
835            $this->dumpLine($cursor->depth);
836        }
837    }
838
839    /**
840     * {@inheritdoc}
841     */
842    public function leaveHash(Cursor $cursor, int $type, $class, bool $hasChild, int $cut)
843    {
844        $this->dumpEllipsis($cursor, $hasChild, $cut);
845        if ($hasChild) {
846            $this->line .= '</samp>';
847        }
848        parent::leaveHash($cursor, $type, $class, $hasChild, 0);
849    }
850
851    /**
852     * {@inheritdoc}
853     */
854    protected function style($style, $value, $attr = [])
855    {
856        if ('' === $value) {
857            return '';
858        }
859
860        $v = esc($value);
861
862        if ('ref' === $style) {
863            if (empty($attr['count'])) {
864                return sprintf('<a class=sf-dump-ref>%s</a>', $v);
865            }
866            $r = ('#' !== $v[0] ? 1 - ('@' !== $v[0]) : 2).substr($value, 1);
867
868            return sprintf('<a class=sf-dump-ref href=#%s-ref%s title="%d occurrences">%s</a>', $this->dumpId, $r, 1 + $attr['count'], $v);
869        }
870
871        if ('const' === $style && isset($attr['value'])) {
872            $style .= sprintf(' title="%s"', esc(is_scalar($attr['value']) ? $attr['value'] : json_encode($attr['value'])));
873        } elseif ('public' === $style) {
874            $style .= sprintf(' title="%s"', empty($attr['dynamic']) ? 'Public property' : 'Runtime added dynamic property');
875        } elseif ('str' === $style && 1 < $attr['length']) {
876            $style .= sprintf(' title="%d%s characters"', $attr['length'], $attr['binary'] ? ' binary or non-UTF-8' : '');
877        } elseif ('note' === $style && 0 < ($attr['depth'] ?? 0) && false !== $c = strrpos($value, '\\')) {
878            $style .= ' title=""';
879            $attr += [
880                'ellipsis' => \strlen($value) - $c,
881                'ellipsis-type' => 'note',
882                'ellipsis-tail' => 1,
883            ];
884        } elseif ('protected' === $style) {
885            $style .= ' title="Protected property"';
886        } elseif ('meta' === $style && isset($attr['title'])) {
887            $style .= sprintf(' title="%s"', esc($this->utf8Encode($attr['title'])));
888        } elseif ('private' === $style) {
889            $style .= sprintf(' title="Private property defined in class:&#10;`%s`"', esc($this->utf8Encode($attr['class'])));
890        }
891        $map = static::$controlCharsMap;
892
893        if (isset($attr['ellipsis'])) {
894            $class = 'sf-dump-ellipsis';
895            if (isset($attr['ellipsis-type'])) {
896                $class = sprintf('"%s sf-dump-ellipsis-%s"', $class, $attr['ellipsis-type']);
897            }
898            $label = esc(substr($value, -$attr['ellipsis']));
899            $style = str_replace(' title="', " title=\"$v\n", $style);
900            $v = sprintf('<span class=%s>%s</span>', $class, substr($v, 0, -\strlen($label)));
901
902            if (!empty($attr['ellipsis-tail'])) {
903                $tail = \strlen(esc(substr($value, -$attr['ellipsis'], $attr['ellipsis-tail'])));
904                $v .= sprintf('<span class=%s>%s</span>%s', $class, substr($label, 0, $tail), substr($label, $tail));
905            } else {
906                $v .= $label;
907            }
908        }
909
910        $v = "<span class=sf-dump-{$style}>".preg_replace_callback(static::$controlCharsRx, function ($c) use ($map) {
911            $s = $b = '<span class="sf-dump-default';
912            $c = $c[$i = 0];
913            if ($ns = "\r" === $c[$i] || "\n" === $c[$i]) {
914                $s .= ' sf-dump-ns';
915            }
916            $s .= '">';
917            do {
918                if (("\r" === $c[$i] || "\n" === $c[$i]) !== $ns) {
919                    $s .= '</span>'.$b;
920                    if ($ns = !$ns) {
921                        $s .= ' sf-dump-ns';
922                    }
923                    $s .= '">';
924                }
925
926                $s .= $map[$c[$i]] ?? sprintf('\x%02X', \ord($c[$i]));
927            } while (isset($c[++$i]));
928
929            return $s.'</span>';
930        }, $v).'</span>';
931
932        if (isset($attr['file']) && $href = $this->getSourceLink($attr['file'], $attr['line'] ?? 0)) {
933            $attr['href'] = $href;
934        }
935        if (isset($attr['href'])) {
936            $target = isset($attr['file']) ? '' : ' target="_blank"';
937            $v = sprintf('<a href="%s"%s rel="noopener noreferrer">%s</a>', esc($this->utf8Encode($attr['href'])), $target, $v);
938        }
939        if (isset($attr['lang'])) {
940            $v = sprintf('<code class="%s">%s</code>', esc($attr['lang']), $v);
941        }
942
943        return $v;
944    }
945
946    /**
947     * {@inheritdoc}
948     */
949    protected function dumpLine(int $depth, bool $endOfValue = false)
950    {
951        if (-1 === $this->lastDepth) {
952            $this->line = sprintf($this->dumpPrefix, $this->dumpId, $this->indentPad).$this->line;
953        }
954        if ($this->headerIsDumped !== (null !== $this->outputStream ? $this->outputStream : $this->lineDumper)) {
955            $this->line = $this->getDumpHeader().$this->line;
956        }
957
958        if (-1 === $depth) {
959            $args = ['"'.$this->dumpId.'"'];
960            if ($this->extraDisplayOptions) {
961                $args[] = json_encode($this->extraDisplayOptions, \JSON_FORCE_OBJECT);
962            }
963            // Replace is for BC
964            $this->line .= sprintf(str_replace('"%s"', '%s', $this->dumpSuffix), implode(', ', $args));
965        }
966        $this->lastDepth = $depth;
967
968        $this->line = mb_convert_encoding($this->line, 'HTML-ENTITIES', 'UTF-8');
969
970        if (-1 === $depth) {
971            AbstractDumper::dumpLine(0);
972        }
973        AbstractDumper::dumpLine($depth);
974    }
975
976    private function getSourceLink(string $file, int $line)
977    {
978        $options = $this->extraDisplayOptions + $this->displayOptions;
979
980        if ($fmt = $options['fileLinkFormat']) {
981            return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line);
982        }
983
984        return false;
985    }
986}
987
988function esc($str)
989{
990    return htmlspecialchars($str, \ENT_QUOTES, 'UTF-8');
991}
992