Upgrade framework

This commit is contained in:
2023-11-14 16:54:35 +01:00
parent 1648a5cd42
commit 4fcf6fffcc
10548 changed files with 693138 additions and 466698 deletions

View File

@@ -21,35 +21,33 @@ use Symfony\Component\VarDumper\Cloner\DumperInterface;
*/
abstract class AbstractDumper implements DataDumperInterface, DumperInterface
{
const DUMP_LIGHT_ARRAY = 1;
const DUMP_STRING_LENGTH = 2;
const DUMP_COMMA_SEPARATOR = 4;
const DUMP_TRAILING_COMMA = 8;
public const DUMP_LIGHT_ARRAY = 1;
public const DUMP_STRING_LENGTH = 2;
public const DUMP_COMMA_SEPARATOR = 4;
public const DUMP_TRAILING_COMMA = 8;
public static $defaultOutput = 'php://output';
protected $line = '';
protected $lineDumper;
protected $outputStream;
protected $decimalPoint; // This is locale dependent
protected $decimalPoint = '.';
protected $indentPad = ' ';
protected $flags;
private $charset;
private string $charset = '';
/**
* @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path, defaults to static::$defaultOutput
* @param string $charset The default character encoding to use for non-UTF8 strings
* @param string|null $charset The default character encoding to use for non-UTF8 strings
* @param int $flags A bit field of static::DUMP_* constants to fine tune dumps representation
*/
public function __construct($output = null, $charset = null, $flags = 0)
public function __construct($output = null, string $charset = null, int $flags = 0)
{
$this->flags = (int) $flags;
$this->setCharset($charset ?: ini_get('php.output_encoding') ?: ini_get('default_charset') ?: 'UTF-8');
$this->decimalPoint = (string) 0.5;
$this->decimalPoint = $this->decimalPoint[1];
$this->flags = $flags;
$this->setCharset($charset ?: \ini_get('php.output_encoding') ?: \ini_get('default_charset') ?: 'UTF-8');
$this->setOutput($output ?: static::$defaultOutput);
if (!$output && is_string(static::$defaultOutput)) {
if (!$output && \is_string(static::$defaultOutput)) {
static::$defaultOutput = $this->outputStream;
}
}
@@ -63,17 +61,17 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
*/
public function setOutput($output)
{
$prev = null !== $this->outputStream ? $this->outputStream : $this->lineDumper;
$prev = $this->outputStream ?? $this->lineDumper;
if (is_callable($output)) {
if (\is_callable($output)) {
$this->outputStream = null;
$this->lineDumper = $output;
} else {
if (is_string($output)) {
$output = fopen($output, 'wb');
if (\is_string($output)) {
$output = fopen($output, 'w');
}
$this->outputStream = $output;
$this->lineDumper = array($this, 'echoLine');
$this->lineDumper = [$this, 'echoLine'];
}
return $prev;
@@ -82,11 +80,9 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
/**
* Sets the default character encoding to use for non-UTF8 strings.
*
* @param string $charset The default character encoding to use for non-UTF8 strings
*
* @return string The previous charset
*/
public function setCharset($charset)
public function setCharset(string $charset): string
{
$prev = $this->charset;
@@ -101,11 +97,11 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
/**
* Sets the indentation pad string.
*
* @param string $pad A string the will be prepended to dumped lines, repeated by nesting level
* @param string $pad A string that will be prepended to dumped lines, repeated by nesting level
*
* @return string The indent pad
* @return string The previous indent pad
*/
public function setIndentPad($pad)
public function setIndentPad(string $pad): string
{
$prev = $this->indentPad;
$this->indentPad = $pad;
@@ -116,15 +112,18 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
/**
* Dumps a Data object.
*
* @param Data $data A Data object
* @param callable|resource|string|true|null $output A line dumper callable, an opened stream, an output path or true to return the dump
*
* @return string|null The dump as string when $output is true
*/
public function dump(Data $data, $output = null)
public function dump(Data $data, $output = null): ?string
{
if ($locale = $this->flags & (self::DUMP_COMMA_SEPARATOR | self::DUMP_TRAILING_COMMA) ? setlocale(\LC_NUMERIC, 0) : null) {
setlocale(\LC_NUMERIC, 'C');
}
if ($returnDump = true === $output) {
$output = fopen('php://memory', 'r+b');
$output = fopen('php://memory', 'r+');
}
if ($output) {
$prevOutput = $this->setOutput($output);
@@ -143,28 +142,30 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
if ($output) {
$this->setOutput($prevOutput);
}
if ($locale) {
setlocale(\LC_NUMERIC, $locale);
}
}
return null;
}
/**
* Dumps the current line.
*
* @param int $depth The recursive depth in the dumped structure for the line being dumped
* @param int $depth The recursive depth in the dumped structure for the line being dumped,
* or -1 to signal the end-of-dump to the line dumper callable
*/
protected function dumpLine($depth)
protected function dumpLine(int $depth)
{
call_user_func($this->lineDumper, $this->line, $depth, $this->indentPad);
($this->lineDumper)($this->line, $depth, $this->indentPad);
$this->line = '';
}
/**
* Generic line dumper callback.
*
* @param string $line The line to write
* @param int $depth The recursive depth in the dumped structure
* @param string $indentPad The line indent pad
*/
protected function echoLine($line, $depth, $indentPad)
protected function echoLine(string $line, int $depth, string $indentPad)
{
if (-1 !== $depth) {
fwrite($this->outputStream, str_repeat($indentPad, $depth).$line."\n");
@@ -173,18 +174,14 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
/**
* Converts a non-UTF-8 string to UTF-8.
*
* @param string $s The non-UTF-8 string to convert
*
* @return string The string converted to UTF-8
*/
protected function utf8Encode($s)
protected function utf8Encode(?string $s): ?string
{
if (preg_match('//u', $s)) {
if (null === $s || preg_match('//u', $s)) {
return $s;
}
if (!function_exists('iconv')) {
if (!\function_exists('iconv')) {
throw new \RuntimeException('Unable to convert a non-UTF-8 string to UTF-8: required function iconv() does not exist. You should install ext-iconv or symfony/polyfill-iconv.');
}

View File

@@ -12,6 +12,7 @@
namespace Symfony\Component\VarDumper\Dumper;
use Symfony\Component\VarDumper\Cloner\Cursor;
use Symfony\Component\VarDumper\Cloner\Stub;
/**
* CliDumper dumps variables for command line output.
@@ -25,9 +26,9 @@ class CliDumper extends AbstractDumper
protected $colors;
protected $maxStringWidth = 0;
protected $styles = array(
protected $styles = [
// See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
'default' => '38;5;208',
'default' => '0;38;5;208',
'num' => '1;38;5;38',
'const' => '1;38;5;208',
'str' => '1;38;5;113',
@@ -39,28 +40,37 @@ class CliDumper extends AbstractDumper
'meta' => '38;5;170',
'key' => '38;5;113',
'index' => '38;5;38',
);
];
protected static $controlCharsRx = '/[\x00-\x1F\x7F]+/';
protected static $controlCharsMap = array(
protected static $controlCharsMap = [
"\t" => '\t',
"\n" => '\n',
"\v" => '\v',
"\f" => '\f',
"\r" => '\r',
"\033" => '\e',
);
];
protected $collapseNextHash = false;
protected $expandNextHash = false;
private array $displayOptions = [
'fileLinkFormat' => null,
];
private bool $handlesHrefGracefully;
/**
* {@inheritdoc}
*/
public function __construct($output = null, $charset = null, $flags = 0)
public function __construct($output = null, string $charset = null, int $flags = 0)
{
parent::__construct($output, $charset, $flags);
if ('\\' === DIRECTORY_SEPARATOR && 'ON' !== @getenv('ConEmuANSI') && 'xterm' !== @getenv('TERM')) {
if ('\\' === \DIRECTORY_SEPARATOR && !$this->isWindowsTrueColor()) {
// Use only the base 16 xterm colors when using ANSICON or standard Windows 10 CLI
$this->setStyles(array(
$this->setStyles([
'default' => '31',
'num' => '1;34',
'const' => '1;31',
@@ -70,28 +80,26 @@ class CliDumper extends AbstractDumper
'meta' => '35',
'key' => '32',
'index' => '34',
));
]);
}
$this->displayOptions['fileLinkFormat'] = \ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format') ?: 'file://%f#L%l';
}
/**
* Enables/disables colored output.
*
* @param bool $colors
*/
public function setColors($colors)
public function setColors(bool $colors)
{
$this->colors = (bool) $colors;
$this->colors = $colors;
}
/**
* Sets the maximum number of characters per line for dumped strings.
*
* @param int $maxStringWidth
*/
public function setMaxStringWidth($maxStringWidth)
public function setMaxStringWidth(int $maxStringWidth)
{
$this->maxStringWidth = (int) $maxStringWidth;
$this->maxStringWidth = $maxStringWidth;
}
/**
@@ -104,10 +112,20 @@ class CliDumper extends AbstractDumper
$this->styles = $styles + $this->styles;
}
/**
* Configures display options.
*
* @param array $displayOptions A map of display options to customize the behavior
*/
public function setDisplayOptions(array $displayOptions)
{
$this->displayOptions = $displayOptions + $this->displayOptions;
}
/**
* {@inheritdoc}
*/
public function dumpScalar(Cursor $cursor, $type, $value)
public function dumpScalar(Cursor $cursor, string $type, string|int|float|bool|null $value)
{
$this->dumpKey($cursor);
@@ -121,18 +139,27 @@ class CliDumper extends AbstractDumper
case 'integer':
$style = 'num';
if (isset($this->styles['integer'])) {
$style = 'integer';
}
break;
case 'double':
$style = 'num';
if (isset($this->styles['float'])) {
$style = 'float';
}
switch (true) {
case INF === $value: $value = 'INF'; break;
case -INF === $value: $value = '-INF'; break;
case \INF === $value: $value = 'INF'; break;
case -\INF === $value: $value = '-INF'; break;
case is_nan($value): $value = 'NAN'; break;
default:
$value = (string) $value;
if (false === strpos($value, $this->decimalPoint)) {
if (!str_contains($value, $this->decimalPoint)) {
$value .= $this->decimalPoint.'0';
}
break;
@@ -148,7 +175,7 @@ class CliDumper extends AbstractDumper
break;
default:
$attr += array('value' => $this->utf8Encode($value));
$attr += ['value' => $this->utf8Encode($value)];
$value = $this->utf8Encode($type);
break;
}
@@ -161,7 +188,7 @@ class CliDumper extends AbstractDumper
/**
* {@inheritdoc}
*/
public function dumpString(Cursor $cursor, $str, $bin, $cut)
public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut)
{
$this->dumpKey($cursor);
$attr = $cursor->attr;
@@ -173,16 +200,16 @@ class CliDumper extends AbstractDumper
$this->line .= '""';
$this->endValue($cursor);
} else {
$attr += array(
$attr += [
'length' => 0 <= $cut ? mb_strlen($str, 'UTF-8') + $cut : 0,
'binary' => $bin,
);
$str = explode("\n", $str);
];
$str = $bin && false !== strpos($str, "\0") ? [$str] : explode("\n", $str);
if (isset($str[1]) && !isset($str[2]) && !isset($str[1][0])) {
unset($str[1]);
$str[0] .= "\n";
}
$m = count($str) - 1;
$m = \count($str) - 1;
$i = $lineCut = 0;
if (self::DUMP_STRING_LENGTH & $this->flags) {
@@ -249,23 +276,33 @@ class CliDumper extends AbstractDumper
/**
* {@inheritdoc}
*/
public function enterHash(Cursor $cursor, $type, $class, $hasChild)
public function enterHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild)
{
if (null === $this->colors) {
$this->colors = $this->supportsColors();
}
$this->dumpKey($cursor);
$attr = $cursor->attr;
if ($this->collapseNextHash) {
$cursor->skipChildren = true;
$this->collapseNextHash = $hasChild = false;
}
$class = $this->utf8Encode($class);
if (Cursor::HASH_OBJECT === $type) {
$prefix = $class && 'stdClass' !== $class ? $this->style('note', $class).' {' : '{';
$prefix = $class && 'stdClass' !== $class ? $this->style('note', $class, $attr).(empty($attr['cut_hash']) ? ' {' : '') : '{';
} elseif (Cursor::HASH_RESOURCE === $type) {
$prefix = $this->style('note', $class.' resource').($hasChild ? ' {' : ' ');
$prefix = $this->style('note', $class.' resource', $attr).($hasChild ? ' {' : ' ');
} else {
$prefix = $class && !(self::DUMP_LIGHT_ARRAY & $this->flags) ? $this->style('note', 'array:'.$class).' [' : '[';
}
if ($cursor->softRefCount || 0 < $cursor->softRefHandle) {
$prefix .= $this->style('ref', (Cursor::HASH_RESOURCE === $type ? '@' : '#').(0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->softRefTo), array('count' => $cursor->softRefCount));
if (($cursor->softRefCount || 0 < $cursor->softRefHandle) && empty($attr['cut_hash'])) {
$prefix .= $this->style('ref', (Cursor::HASH_RESOURCE === $type ? '@' : '#').(0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->softRefTo), ['count' => $cursor->softRefCount]);
} elseif ($cursor->hardRefTo && !$cursor->refIndex && $class) {
$prefix .= $this->style('ref', '&'.$cursor->hardRefTo, array('count' => $cursor->hardRefCount));
$prefix .= $this->style('ref', '&'.$cursor->hardRefTo, ['count' => $cursor->hardRefCount]);
} elseif (!$hasChild && Cursor::HASH_RESOURCE === $type) {
$prefix = substr($prefix, 0, -1);
}
@@ -280,21 +317,23 @@ class CliDumper extends AbstractDumper
/**
* {@inheritdoc}
*/
public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut)
public function leaveHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild, int $cut)
{
$this->dumpEllipsis($cursor, $hasChild, $cut);
$this->line .= Cursor::HASH_OBJECT === $type ? '}' : (Cursor::HASH_RESOURCE !== $type ? ']' : ($hasChild ? '}' : ''));
if (empty($cursor->attr['cut_hash'])) {
$this->dumpEllipsis($cursor, $hasChild, $cut);
$this->line .= Cursor::HASH_OBJECT === $type ? '}' : (Cursor::HASH_RESOURCE !== $type ? ']' : ($hasChild ? '}' : ''));
}
$this->endValue($cursor);
}
/**
* Dumps an ellipsis for cut children.
*
* @param Cursor $cursor The Cursor position in the dump
* @param bool $hasChild When the dump of the hash has child item
* @param int $cut The number of items the hash has been cut by
* @param bool $hasChild When the dump of the hash has child item
* @param int $cut The number of items the hash has been cut by
*/
protected function dumpEllipsis(Cursor $cursor, $hasChild, $cut)
protected function dumpEllipsis(Cursor $cursor, bool $hasChild, int $cut)
{
if ($cut) {
$this->line .= ' …';
@@ -309,8 +348,6 @@ class CliDumper extends AbstractDumper
/**
* Dumps a key in a hash structure.
*
* @param Cursor $cursor The Cursor position in the dump
*/
protected function dumpKey(Cursor $cursor)
{
@@ -318,7 +355,7 @@ class CliDumper extends AbstractDumper
if ($cursor->hashKeyIsBinary) {
$key = $this->utf8Encode($key);
}
$attr = array('binary' => $cursor->hashKeyIsBinary);
$attr = ['binary' => $cursor->hashKeyIsBinary];
$bin = $cursor->hashKeyIsBinary ? 'b' : '';
$style = 'key';
switch ($cursor->hashType) {
@@ -328,8 +365,9 @@ class CliDumper extends AbstractDumper
break;
}
$style = 'index';
// no break
case Cursor::HASH_ASSOC:
if (is_int($key)) {
if (\is_int($key)) {
$this->line .= $this->style($style, $key).' => ';
} else {
$this->line .= $bin.'"'.$this->style($style, $key).'" => ';
@@ -338,7 +376,7 @@ class CliDumper extends AbstractDumper
case Cursor::HASH_RESOURCE:
$key = "\0~\0".$key;
// No break;
// no break
case Cursor::HASH_OBJECT:
if (!isset($key[0]) || "\0" !== $key[0]) {
$this->line .= '+'.$bin.$this->style('public', $key).': ';
@@ -354,7 +392,7 @@ class CliDumper extends AbstractDumper
$style = 'meta';
if (isset($key[0][1])) {
parse_str(substr($key[0], 1), $attr);
$attr += array('binary' => $cursor->hashKeyIsBinary);
$attr += ['binary' => $cursor->hashKeyIsBinary];
}
break;
case '*':
@@ -368,16 +406,24 @@ class CliDumper extends AbstractDumper
break;
}
$this->line .= $bin.$this->style($style, $key[1], $attr).': ';
if (isset($attr['collapse'])) {
if ($attr['collapse']) {
$this->collapseNextHash = true;
} else {
$this->expandNextHash = true;
}
}
$this->line .= $bin.$this->style($style, $key[1], $attr).($attr['separator'] ?? ': ');
} else {
// This case should not happen
$this->line .= '-'.$bin.'"'.$this->style('private', $key, array('class' => '')).'": ';
$this->line .= '-'.$bin.'"'.$this->style('private', $key, ['class' => '']).'": ';
}
break;
}
if ($cursor->hardRefTo) {
$this->line .= $this->style('ref', '&'.($cursor->hardRefCount ? $cursor->hardRefTo : ''), array('count' => $cursor->hardRefCount)).' ';
$this->line .= $this->style('ref', '&'.($cursor->hardRefCount ? $cursor->hardRefTo : ''), ['count' => $cursor->hardRefCount]).' ';
}
}
}
@@ -388,25 +434,41 @@ class CliDumper extends AbstractDumper
* @param string $style The type of style being applied
* @param string $value The value being styled
* @param array $attr Optional context information
*
* @return string The value with style decoration
*/
protected function style($style, $value, $attr = array())
protected function style(string $style, string $value, array $attr = []): string
{
if (null === $this->colors) {
$this->colors = $this->supportsColors();
}
$style = $this->styles[$style];
$this->handlesHrefGracefully ??= 'JetBrains-JediTerm' !== getenv('TERMINAL_EMULATOR')
&& (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100);
if (isset($attr['ellipsis'], $attr['ellipsis-type'])) {
$prefix = substr($value, 0, -$attr['ellipsis']);
if ('cli' === \PHP_SAPI && 'path' === $attr['ellipsis-type'] && isset($_SERVER[$pwd = '\\' === \DIRECTORY_SEPARATOR ? 'CD' : 'PWD']) && str_starts_with($prefix, $_SERVER[$pwd])) {
$prefix = '.'.substr($prefix, \strlen($_SERVER[$pwd]));
}
if (!empty($attr['ellipsis-tail'])) {
$prefix .= substr($value, -$attr['ellipsis'], $attr['ellipsis-tail']);
$value = substr($value, -$attr['ellipsis'] + $attr['ellipsis-tail']);
} else {
$value = substr($value, -$attr['ellipsis']);
}
$value = $this->style('default', $prefix).$this->style($style, $value);
goto href;
}
$map = static::$controlCharsMap;
$startCchr = $this->colors ? "\033[m\033[{$this->styles['default']}m" : '';
$endCchr = $this->colors ? "\033[m\033[{$style}m" : '';
$endCchr = $this->colors ? "\033[m\033[{$this->styles[$style]}m" : '';
$value = preg_replace_callback(static::$controlCharsRx, function ($c) use ($map, $startCchr, $endCchr) {
$s = $startCchr;
$c = $c[$i = 0];
do {
$s .= isset($map[$c[$i]]) ? $map[$c[$i]] : sprintf('\x%02X', ord($c[$i]));
$s .= $map[$c[$i]] ?? sprintf('\x%02X', \ord($c[$i]));
} while (isset($c[++$i]));
return $s.$endCchr;
@@ -414,34 +476,47 @@ class CliDumper extends AbstractDumper
if ($this->colors) {
if ($cchrCount && "\033" === $value[0]) {
$value = substr($value, strlen($startCchr));
$value = substr($value, \strlen($startCchr));
} else {
$value = "\033[{$style}m".$value;
$value = "\033[{$this->styles[$style]}m".$value;
}
if ($cchrCount && $endCchr === substr($value, -strlen($endCchr))) {
$value = substr($value, 0, -strlen($endCchr));
if ($cchrCount && str_ends_with($value, $endCchr)) {
$value = substr($value, 0, -\strlen($endCchr));
} else {
$value .= "\033[{$this->styles['default']}m";
}
}
href:
if ($this->colors && $this->handlesHrefGracefully) {
if (isset($attr['file']) && $href = $this->getSourceLink($attr['file'], $attr['line'] ?? 0)) {
if ('note' === $style) {
$value .= "\033]8;;{$href}\033\\^\033]8;;\033\\";
} else {
$attr['href'] = $href;
}
}
if (isset($attr['href'])) {
$value = "\033]8;;{$attr['href']}\033\\{$value}\033]8;;\033\\";
}
} elseif ($attr['if_links'] ?? false) {
return '';
}
return $value;
}
/**
* @return bool Tells if the current output stream supports ANSI colors or not
*/
protected function supportsColors()
protected function supportsColors(): bool
{
if ($this->outputStream !== static::$defaultOutput) {
return @(is_resource($this->outputStream) && function_exists('posix_isatty') && posix_isatty($this->outputStream));
return $this->hasColorSupport($this->outputStream);
}
if (null !== static::$defaultColors) {
return static::$defaultColors;
}
if (isset($_SERVER['argv'][1])) {
$colors = $_SERVER['argv'];
$i = count($colors);
$i = \count($colors);
while (--$i > 0) {
if (isset($colors[$i][5])) {
switch ($colors[$i]) {
@@ -450,40 +525,30 @@ class CliDumper extends AbstractDumper
case '--color=yes':
case '--color=force':
case '--color=always':
case '--colors=always':
return static::$defaultColors = true;
case '--no-ansi':
case '--color=no':
case '--color=none':
case '--color=never':
case '--colors=never':
return static::$defaultColors = false;
}
}
}
}
if ('\\' === DIRECTORY_SEPARATOR) {
static::$defaultColors = @(
'10.0.10586' === PHP_WINDOWS_VERSION_MAJOR.'.'.PHP_WINDOWS_VERSION_MINOR.'.'.PHP_WINDOWS_VERSION_BUILD
|| false !== getenv('ANSICON')
|| 'ON' === getenv('ConEmuANSI')
|| 'xterm' === getenv('TERM')
);
} elseif (function_exists('posix_isatty')) {
$h = stream_get_meta_data($this->outputStream) + array('wrapper_type' => null);
$h = 'Output' === $h['stream_type'] && 'PHP' === $h['wrapper_type'] ? fopen('php://stdout', 'wb') : $this->outputStream;
static::$defaultColors = @posix_isatty($h);
} else {
static::$defaultColors = false;
}
$h = stream_get_meta_data($this->outputStream) + ['wrapper_type' => null];
$h = 'Output' === $h['stream_type'] && 'PHP' === $h['wrapper_type'] ? fopen('php://stdout', 'w') : $this->outputStream;
return static::$defaultColors;
return static::$defaultColors = $this->hasColorSupport($h);
}
/**
* {@inheritdoc}
*/
protected function dumpLine($depth, $endOfValue = false)
protected function dumpLine(int $depth, bool $endOfValue = false)
{
if ($this->colors) {
$this->line = sprintf("\033[%sm%s\033[m", $this->styles['default'], $this->line);
@@ -493,12 +558,86 @@ class CliDumper extends AbstractDumper
protected function endValue(Cursor $cursor)
{
if (self::DUMP_TRAILING_COMMA & $this->flags && 0 < $cursor->depth) {
$this->line .= ',';
} elseif (self::DUMP_COMMA_SEPARATOR & $this->flags && 1 < $cursor->hashLength - $cursor->hashIndex) {
$this->line .= ',';
if (-1 === $cursor->hashType) {
return;
}
if (Stub::ARRAY_INDEXED === $cursor->hashType || Stub::ARRAY_ASSOC === $cursor->hashType) {
if (self::DUMP_TRAILING_COMMA & $this->flags && 0 < $cursor->depth) {
$this->line .= ',';
} elseif (self::DUMP_COMMA_SEPARATOR & $this->flags && 1 < $cursor->hashLength - $cursor->hashIndex) {
$this->line .= ',';
}
}
$this->dumpLine($cursor->depth, true);
}
/**
* Returns true if the stream supports colorization.
*
* Reference: Composer\XdebugHandler\Process::supportsColor
* https://github.com/composer/xdebug-handler
*/
private function hasColorSupport(mixed $stream): bool
{
if (!\is_resource($stream) || 'stream' !== get_resource_type($stream)) {
return false;
}
// Follow https://no-color.org/
if (isset($_SERVER['NO_COLOR']) || false !== getenv('NO_COLOR')) {
return false;
}
if ('Hyper' === getenv('TERM_PROGRAM')) {
return true;
}
if (\DIRECTORY_SEPARATOR === '\\') {
return (\function_exists('sapi_windows_vt100_support')
&& @sapi_windows_vt100_support($stream))
|| false !== getenv('ANSICON')
|| 'ON' === getenv('ConEmuANSI')
|| 'xterm' === getenv('TERM');
}
return stream_isatty($stream);
}
/**
* Returns true if the Windows terminal supports true color.
*
* Note that this does not check an output stream, but relies on environment
* variables from known implementations, or a PHP and Windows version that
* supports true color.
*/
private function isWindowsTrueColor(): bool
{
$result = 183 <= getenv('ANSICON_VER')
|| 'ON' === getenv('ConEmuANSI')
|| 'xterm' === getenv('TERM')
|| 'Hyper' === getenv('TERM_PROGRAM');
if (!$result) {
$version = sprintf(
'%s.%s.%s',
PHP_WINDOWS_VERSION_MAJOR,
PHP_WINDOWS_VERSION_MINOR,
PHP_WINDOWS_VERSION_BUILD
);
$result = $version >= '10.0.15063';
}
return $result;
}
private function getSourceLink(string $file, int $line)
{
if ($fmt = $this->displayOptions['fileLinkFormat']) {
return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : ($fmt->format($file, $line) ?: 'file://'.$file.'#L'.$line);
}
return false;
}
}

View File

@@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Dumper\ContextProvider;
/**
* Tries to provide context on CLI.
*
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
final class CliContextProvider implements ContextProviderInterface
{
public function getContext(): ?array
{
if ('cli' !== \PHP_SAPI) {
return null;
}
return [
'command_line' => $commandLine = implode(' ', $_SERVER['argv'] ?? []),
'identifier' => hash('crc32b', $commandLine.$_SERVER['REQUEST_TIME_FLOAT']),
];
}
}

View File

@@ -0,0 +1,22 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Dumper\ContextProvider;
/**
* Interface to provide contextual data about dump data clones sent to a server.
*
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
interface ContextProviderInterface
{
public function getContext(): ?array;
}

View File

@@ -0,0 +1,51 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Dumper\ContextProvider;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\VarDumper\Caster\ReflectionCaster;
use Symfony\Component\VarDumper\Cloner\VarCloner;
/**
* Tries to provide context from a request.
*
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
final class RequestContextProvider implements ContextProviderInterface
{
private $requestStack;
private $cloner;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
$this->cloner = new VarCloner();
$this->cloner->setMaxItems(0);
$this->cloner->addCasters(ReflectionCaster::UNSET_CLOSURE_FILE_INFO);
}
public function getContext(): ?array
{
if (null === $request = $this->requestStack->getCurrentRequest()) {
return null;
}
$controller = $request->attributes->get('_controller');
return [
'uri' => $request->getUri(),
'method' => $request->getMethod(),
'controller' => $controller ? $this->cloner->cloneVar($controller) : $controller,
'identifier' => spl_object_hash($request),
];
}
}

View File

@@ -0,0 +1,126 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Dumper\ContextProvider;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
use Symfony\Component\VarDumper\VarDumper;
use Twig\Template;
/**
* Tries to provide context from sources (class name, file, line, code excerpt, ...).
*
* @author Nicolas Grekas <p@tchwork.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
final class SourceContextProvider implements ContextProviderInterface
{
private int $limit;
private ?string $charset;
private ?string $projectDir;
private $fileLinkFormatter;
public function __construct(string $charset = null, string $projectDir = null, FileLinkFormatter $fileLinkFormatter = null, int $limit = 9)
{
$this->charset = $charset;
$this->projectDir = $projectDir;
$this->fileLinkFormatter = $fileLinkFormatter;
$this->limit = $limit;
}
public function getContext(): ?array
{
$trace = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS, $this->limit);
$file = $trace[1]['file'];
$line = $trace[1]['line'];
$name = false;
$fileExcerpt = false;
for ($i = 2; $i < $this->limit; ++$i) {
if (isset($trace[$i]['class'], $trace[$i]['function'])
&& 'dump' === $trace[$i]['function']
&& VarDumper::class === $trace[$i]['class']
) {
$file = $trace[$i]['file'] ?? $file;
$line = $trace[$i]['line'] ?? $line;
while (++$i < $this->limit) {
if (isset($trace[$i]['function'], $trace[$i]['file']) && empty($trace[$i]['class']) && !str_starts_with($trace[$i]['function'], 'call_user_func')) {
$file = $trace[$i]['file'];
$line = $trace[$i]['line'];
break;
} elseif (isset($trace[$i]['object']) && $trace[$i]['object'] instanceof Template) {
$template = $trace[$i]['object'];
$name = $template->getTemplateName();
$src = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getCode() : (method_exists($template, 'getSource') ? $template->getSource() : false);
$info = $template->getDebugInfo();
if (isset($info[$trace[$i - 1]['line']])) {
$line = $info[$trace[$i - 1]['line']];
$file = method_exists($template, 'getSourceContext') ? $template->getSourceContext()->getPath() : null;
if ($src) {
$src = explode("\n", $src);
$fileExcerpt = [];
for ($i = max($line - 3, 1), $max = min($line + 3, \count($src)); $i <= $max; ++$i) {
$fileExcerpt[] = '<li'.($i === $line ? ' class="selected"' : '').'><code>'.$this->htmlEncode($src[$i - 1]).'</code></li>';
}
$fileExcerpt = '<ol start="'.max($line - 3, 1).'">'.implode("\n", $fileExcerpt).'</ol>';
}
}
break;
}
}
break;
}
}
if (false === $name) {
$name = str_replace('\\', '/', $file);
$name = substr($name, strrpos($name, '/') + 1);
}
$context = ['name' => $name, 'file' => $file, 'line' => $line];
$context['file_excerpt'] = $fileExcerpt;
if (null !== $this->projectDir) {
$context['project_dir'] = $this->projectDir;
if (str_starts_with($file, $this->projectDir)) {
$context['file_relative'] = ltrim(substr($file, \strlen($this->projectDir)), \DIRECTORY_SEPARATOR);
}
}
if ($this->fileLinkFormatter && $fileLink = $this->fileLinkFormatter->format($context['file'], $context['line'])) {
$context['file_link'] = $fileLink;
}
return $context;
}
private function htmlEncode(string $s): string
{
$html = '';
$dumper = new HtmlDumper(function ($line) use (&$html) { $html .= $line; }, $this->charset);
$dumper->setDumpHeader('');
$dumper->setDumpBoundaries('', '');
$cloner = new VarCloner();
$dumper->dump($cloner->cloneVar($s));
return substr(strip_tags($html), 1, -1);
}
}

View File

@@ -0,0 +1,43 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Dumper;
use Symfony\Component\VarDumper\Cloner\Data;
use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface;
/**
* @author Kévin Thérage <therage.kevin@gmail.com>
*/
class ContextualizedDumper implements DataDumperInterface
{
private $wrappedDumper;
private array $contextProviders;
/**
* @param ContextProviderInterface[] $contextProviders
*/
public function __construct(DataDumperInterface $wrappedDumper, array $contextProviders)
{
$this->wrappedDumper = $wrappedDumper;
$this->contextProviders = $contextProviders;
}
public function dump(Data $data)
{
$context = [];
foreach ($this->contextProviders as $contextProvider) {
$context[\get_class($contextProvider)] = $contextProvider->getContext();
}
$this->wrappedDumper->dump($data->withContext($context));
}
}

View File

@@ -20,10 +20,5 @@ use Symfony\Component\VarDumper\Cloner\Data;
*/
interface DataDumperInterface
{
/**
* Dumps a Data object.
*
* @param Data $data A Data object
*/
public function dump(Data $data);
}

View File

@@ -23,6 +23,41 @@ class HtmlDumper extends CliDumper
{
public static $defaultOutput = 'php://output';
protected static $themes = [
'dark' => [
'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',
'num' => 'font-weight:bold; color:#1299DA',
'const' => 'font-weight:bold',
'str' => 'font-weight:bold; color:#56DB3A',
'note' => 'color:#1299DA',
'ref' => 'color:#A0A0A0',
'public' => 'color:#FFFFFF',
'protected' => 'color:#FFFFFF',
'private' => 'color:#FFFFFF',
'meta' => 'color:#B729D9',
'key' => 'color:#56DB3A',
'index' => 'color:#1299DA',
'ellipsis' => 'color:#FF8400',
'ns' => 'user-select:none;',
],
'light' => [
'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',
'num' => 'font-weight:bold; color:#1299DA',
'const' => 'font-weight:bold',
'str' => 'font-weight:bold; color:#629755;',
'note' => 'color:#6897BB',
'ref' => 'color:#6E6E6E',
'public' => 'color:#262626',
'protected' => 'color:#262626',
'private' => 'color:#262626',
'meta' => 'color:#B729D9',
'key' => 'color:#789339',
'index' => 'color:#1299DA',
'ellipsis' => 'color:#CC7832',
'ns' => 'user-select:none;',
],
];
protected $dumpHeader;
protected $dumpPrefix = '<pre class=sf-dump id=%s data-indent-pad="%s">';
protected $dumpSuffix = '</pre><script>Sfdump(%s)</script>';
@@ -30,37 +65,24 @@ class HtmlDumper extends CliDumper
protected $colors = true;
protected $headerIsDumped = false;
protected $lastDepth = -1;
protected $styles = array(
'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',
'num' => 'font-weight:bold; color:#1299DA',
'const' => 'font-weight:bold',
'str' => 'font-weight:bold; color:#56DB3A',
'note' => 'color:#1299DA',
'ref' => 'color:#A0A0A0',
'public' => 'color:#FFFFFF',
'protected' => 'color:#FFFFFF',
'private' => 'color:#FFFFFF',
'meta' => 'color:#B729D9',
'key' => 'color:#56DB3A',
'index' => 'color:#1299DA',
'ellipsis' => 'color:#FF8400',
);
protected $styles;
private $displayOptions = array(
private array $displayOptions = [
'maxDepth' => 1,
'maxStringLength' => 160,
'fileLinkFormat' => null,
);
private $extraDisplayOptions = array();
];
private array $extraDisplayOptions = [];
/**
* {@inheritdoc}
*/
public function __construct($output = null, $charset = null, $flags = 0)
public function __construct($output = null, string $charset = null, int $flags = 0)
{
AbstractDumper::__construct($output, $charset, $flags);
$this->dumpId = 'sf-dump-'.mt_rand();
$this->displayOptions['fileLinkFormat'] = ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
$this->displayOptions['fileLinkFormat'] = \ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
$this->styles = static::$themes['dark'] ?? self::$themes['dark'];
}
/**
@@ -72,6 +94,15 @@ class HtmlDumper extends CliDumper
$this->styles = $styles + $this->styles;
}
public function setTheme(string $themeName)
{
if (!isset(static::$themes[$themeName])) {
throw new \InvalidArgumentException(sprintf('Theme "%s" does not exist in class "%s".', $themeName, static::class));
}
$this->setStyles(static::$themes[$themeName]);
}
/**
* Configures display options.
*
@@ -85,21 +116,16 @@ class HtmlDumper extends CliDumper
/**
* Sets an HTML header that will be dumped once in the output stream.
*
* @param string $header An HTML string
*/
public function setDumpHeader($header)
public function setDumpHeader(?string $header)
{
$this->dumpHeader = $header;
}
/**
* Sets an HTML prefix and suffix that will encapse every single dump.
*
* @param string $prefix The prepended HTML string
* @param string $suffix The appended HTML string
*/
public function setDumpBoundaries($prefix, $suffix)
public function setDumpBoundaries(string $prefix, string $suffix)
{
$this->dumpPrefix = $prefix;
$this->dumpSuffix = $suffix;
@@ -108,7 +134,7 @@ class HtmlDumper extends CliDumper
/**
* {@inheritdoc}
*/
public function dump(Data $data, $output = null, array $extraDisplayOptions = array())
public function dump(Data $data, $output = null, array $extraDisplayOptions = []): ?string
{
$this->extraDisplayOptions = $extraDisplayOptions;
$result = parent::dump($data, $output);
@@ -122,13 +148,13 @@ class HtmlDumper extends CliDumper
*/
protected function getDumpHeader()
{
$this->headerIsDumped = null !== $this->outputStream ? $this->outputStream : $this->lineDumper;
$this->headerIsDumped = $this->outputStream ?? $this->lineDumper;
if (null !== $this->dumpHeader) {
return $this->dumpHeader;
}
$line = str_replace('{$options}', json_encode($this->displayOptions, JSON_FORCE_OBJECT), <<<'EOHTML'
$line = str_replace('{$options}', json_encode($this->displayOptions, \JSON_FORCE_OBJECT), <<<'EOHTML'
<script>
Sfdump = window.Sfdump || (function (doc) {
@@ -140,6 +166,9 @@ var refStyle = doc.createElement('style'),
e.addEventListener(n, cb, false);
};
refStyle.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; }';
(doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle);
refStyle = doc.createElement('style');
(doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle);
if (!doc.addEventListener) {
@@ -155,24 +184,31 @@ if (!doc.addEventListener) {
function toggle(a, recursive) {
var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass;
if ('sf-dump-compact' == oldClass) {
if (/\bsf-dump-compact\b/.test(oldClass)) {
arrow = '▼';
newClass = 'sf-dump-expanded';
} else if ('sf-dump-expanded' == oldClass) {
} else if (/\bsf-dump-expanded\b/.test(oldClass)) {
arrow = '▶';
newClass = 'sf-dump-compact';
} else {
return false;
}
if (doc.createEvent && s.dispatchEvent) {
var event = doc.createEvent('Event');
event.initEvent('sf-dump-expanded' === newClass ? 'sfbeforedumpexpand' : 'sfbeforedumpcollapse', true, false);
s.dispatchEvent(event);
}
a.lastChild.innerHTML = arrow;
s.className = newClass;
s.className = s.className.replace(/\bsf-dump-(compact|expanded)\b/, newClass);
if (recursive) {
try {
a = s.querySelectorAll('.'+oldClass);
for (s = 0; s < a.length; ++s) {
if (a[s].className !== newClass) {
if (-1 == a[s].className.indexOf(newClass)) {
a[s].className = newClass;
a[s].previousSibling.lastChild.innerHTML = arrow;
}
@@ -187,7 +223,7 @@ function toggle(a, recursive) {
function collapse(a, recursive) {
var s = a.nextSibling || {}, oldClass = s.className;
if ('sf-dump-expanded' == oldClass) {
if (/\bsf-dump-expanded\b/.test(oldClass)) {
toggle(a, recursive);
return true;
@@ -199,7 +235,7 @@ function collapse(a, recursive) {
function expand(a, recursive) {
var s = a.nextSibling || {}, oldClass = s.className;
if ('sf-dump-compact' == oldClass) {
if (/\bsf-dump-compact\b/.test(oldClass)) {
toggle(a, recursive);
return true;
@@ -254,8 +290,8 @@ function highlight(root, activeNode, nodes) {
function resetHighlightedNodes(root) {
Array.from(root.querySelectorAll('.sf-dump-str, .sf-dump-key, .sf-dump-public, .sf-dump-protected, .sf-dump-private')).forEach(function (strNode) {
strNode.className = strNode.className.replace(/\b sf-dump-highlight\b/, '');
strNode.className = strNode.className.replace(/\b sf-dump-highlight-active\b/, '');
strNode.className = strNode.className.replace(/\bsf-dump-highlight\b/, '');
strNode.className = strNode.className.replace(/\bsf-dump-highlight-active\b/, '');
});
}
@@ -276,13 +312,21 @@ return function (root, x) {
}
function a(e, f) {
addEventListener(root, e, function (e) {
addEventListener(root, e, function (e, n) {
if ('A' == e.target.tagName) {
f(e.target, e);
} else if ('A' == e.target.parentNode.tagName) {
f(e.target.parentNode, e);
} else if (e.target.nextElementSibling && 'A' == e.target.nextElementSibling.tagName) {
f(e.target.nextElementSibling, e, true);
} else {
n = /\bsf-dump-ellipsis\b/.test(e.target.className) ? e.target.parentNode : e.target;
if ((n = n.nextElementSibling) && 'A' == n.tagName) {
if (!/\bsf-dump-toggle\b/.test(n.className)) {
n = n.nextElementSibling || n;
}
f(n, e, true);
}
}
});
};
@@ -303,6 +347,9 @@ return function (root, x) {
return "concat(" + parts.join(",") + ", '')";
}
function xpathHasClass(className) {
return "contains(concat(' ', normalize-space(@class), ' '), ' " + className +" ')";
}
addEventListener(root, 'mouseover', function (e) {
if ('' != refStyle.innerHTML) {
refStyle.innerHTML = '';
@@ -322,7 +369,7 @@ return function (root, x) {
if (/\bsf-dump-toggle\b/.test(a.className)) {
e.preventDefault();
if (!toggle(a, isCtrlKey(e))) {
var r = doc.getElementById(a.getAttribute('href').substr(1)),
var r = doc.getElementById(a.getAttribute('href').slice(1)),
s = r.previousSibling,
f = r.parentNode,
t = a.parentNode;
@@ -334,7 +381,7 @@ return function (root, x) {
if (f && t && f[0] !== t[0]) {
r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]);
}
if ('sf-dump-compact' == r.className) {
if (/\bsf-dump-compact\b/.test(r.className)) {
toggle(s, isCtrlKey(e));
}
}
@@ -352,7 +399,7 @@ return function (root, x) {
} else if (/\bsf-dump-str-toggle\b/.test(a.className)) {
e.preventDefault();
e = a.parentNode.parentNode;
e.className = e.className.replace(/sf-dump-str-(expand|collapse)/, a.parentNode.className);
e.className = e.className.replace(/\bsf-dump-str-(expand|collapse)\b/, a.parentNode.className);
}
});
@@ -366,7 +413,6 @@ return function (root, x) {
for (i = 0; i < len; ++i) {
elt = t[i];
if ('SAMP' == elt.tagName) {
elt.className = 'sf-dump-expanded';
a = elt.previousSibling || {};
if ('A' != a.tagName) {
a = doc.createElement('A');
@@ -376,18 +422,15 @@ return function (root, x) {
a.innerHTML += ' ';
}
a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children';
a.innerHTML += '<span>▼</span>';
a.innerHTML += elt.className == 'sf-dump-compact' ? '<span>▶</span>' : '<span>▼</span>';
a.className += ' sf-dump-toggle';
x = 1;
if ('sf-dump' != elt.parentNode.className) {
x += elt.parentNode.getAttribute('data-depth')/1;
}
elt.setAttribute('data-depth', x);
if (x > options.maxDepth) {
toggle(a);
}
} else if ('sf-dump-ref' == elt.className && (a = elt.getAttribute('href'))) {
a = a.substr(1);
} else if (/\bsf-dump-ref\b/.test(elt.className) && (a = elt.getAttribute('href'))) {
a = a.slice(1);
elt.className += ' '+a;
if (/[\[{]$/.test(elt.previousSibling.nodeValue)) {
@@ -425,16 +468,16 @@ return function (root, x) {
if (this.isEmpty()) {
return this.current();
}
this.idx = this.idx < (this.nodes.length - 1) ? this.idx + 1 : this.idx;
this.idx = this.idx < (this.nodes.length - 1) ? this.idx + 1 : 0;
return this.current();
},
previous: function () {
if (this.isEmpty()) {
return this.current();
}
this.idx = this.idx > 0 ? this.idx - 1 : this.idx;
this.idx = this.idx > 0 ? this.idx - 1 : (this.nodes.length - 1);
return this.current();
},
isEmpty: function () {
@@ -457,10 +500,18 @@ return function (root, x) {
function showCurrent(state)
{
var currentNode = state.current();
var currentNode = state.current(), currentRect, searchRect;
if (currentNode) {
reveal(currentNode);
highlight(root, currentNode, state.nodes);
if ('scrollIntoView' in currentNode) {
currentNode.scrollIntoView(true);
currentRect = currentNode.getBoundingClientRect();
searchRect = search.getBoundingClientRect();
if (currentRect.top < (searchRect.top + searchRect.height)) {
window.scrollBy(0, -(searchRect.top + searchRect.height + 5));
}
}
}
counter.textContent = (state.isEmpty() ? 0 : state.idx + 1) + ' of ' + state.count();
}
@@ -471,14 +522,10 @@ return function (root, x) {
<input type="text" class="sf-dump-search-input">
<span class="sf-dump-search-count">0 of 0<\/span>
<button type="button" class="sf-dump-search-input-previous" tabindex="-1">
<svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
<path d="M1683 1331l-166 165q-19 19-45 19t-45-19l-531-531-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>
<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>
<\/button>
<button type="button" class="sf-dump-search-input-next" tabindex="-1">
<svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
<path d="M1683 808l-742 741q-19 19-45 19t-45-19l-742-741q-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>
<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>
<\/button>
';
root.insertBefore(search, root.firstChild);
@@ -507,10 +554,18 @@ return function (root, x) {
return;
}
var xpathResult = doc.evaluate('//pre[@id="' + root.id + '"]//span[@class="sf-dump-str" or @class="sf-dump-key" or @class="sf-dump-public" or @class="sf-dump-protected" or @class="sf-dump-private"][contains(child::text(), ' + xpathString(searchQuery) + ')]', document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
var classMatches = [
"sf-dump-str",
"sf-dump-key",
"sf-dump-public",
"sf-dump-protected",
"sf-dump-private",
].map(xpathHasClass).join(' or ');
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);
while (node = xpathResult.iterateNext()) state.nodes.push(node);
showCurrent(state);
}, 400);
});
@@ -518,8 +573,7 @@ return function (root, x) {
Array.from(search.querySelectorAll('.sf-dump-search-input-next, .sf-dump-search-input-previous')).forEach(function (btn) {
addEventListener(btn, 'click', function (e) {
e.preventDefault();
var direction = -1 !== e.target.className.indexOf('next') ? 'next' : 'previous';
'next' === direction ? state.next() : state.previous();
-1 !== e.target.className.indexOf('next') ? state.next() : state.previous();
searchInput.focus();
collapseAll(root);
showCurrent(state);
@@ -530,6 +584,15 @@ return function (root, x) {
var isSearchActive = !/\bsf-dump-search-hidden\b/.test(search.className);
if ((114 === e.keyCode && !isSearchActive) || (isCtrlKey(e) && 70 === e.keyCode)) {
/* F3 or CMD/CTRL + F */
if (70 === e.keyCode && document.activeElement === searchInput) {
/*
* If CMD/CTRL + F is hit while having focus on search input,
* the user probably meant to trigger browser search instead.
* Let the browser execute its behavior:
*/
return;
}
e.preventDefault();
search.className = search.className.replace(/\bsf-dump-search-hidden\b/, '');
searchInput.focus();
@@ -588,6 +651,7 @@ pre.sf-dump {
display: block;
white-space: pre;
padding: 5px;
overflow: initial !important;
}
pre.sf-dump:after {
content: "";
@@ -599,14 +663,6 @@ pre.sf-dump:after {
pre.sf-dump span {
display: inline;
}
pre.sf-dump .sf-dump-compact {
display: none;
}
pre.sf-dump abbr {
text-decoration: none;
border: none;
cursor: help;
}
pre.sf-dump a {
text-decoration: none;
cursor: pointer;
@@ -614,6 +670,13 @@ pre.sf-dump a {
outline: none;
color: inherit;
}
pre.sf-dump img {
max-width: 50em;
max-height: 50em;
margin: .5em 0 0 0;
padding: 0;
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAHUlEQVQY02O8zAABilCaiQEN0EeA8QuUcX9g3QEAAjcC5piyhyEAAAAASUVORK5CYII=) #D3D3D3;
}
pre.sf-dump .sf-dump-ellipsis {
display: inline-block;
overflow: visible;
@@ -631,12 +694,6 @@ pre.sf-dump code {
padding:0;
background:none;
}
.sf-dump-str-collapse .sf-dump-str-collapse {
display: none;
}
.sf-dump-str-expand .sf-dump-str-expand {
display: none;
}
.sf-dump-public.sf-dump-highlight,
.sf-dump-protected.sf-dump-highlight,
.sf-dump-private.sf-dump-highlight,
@@ -656,14 +713,16 @@ pre.sf-dump code {
border-radius: 3px;
}
pre.sf-dump .sf-dump-search-hidden {
display: none;
display: none !important;
}
pre.sf-dump .sf-dump-search-wrapper {
float: right;
font-size: 0;
white-space: nowrap;
max-width: 100%;
text-align: right;
margin-bottom: 5px;
display: flex;
position: -webkit-sticky;
position: sticky;
top: 5px;
}
pre.sf-dump .sf-dump-search-wrapper > * {
vertical-align: top;
@@ -680,10 +739,11 @@ pre.sf-dump .sf-dump-search-wrapper > input.sf-dump-search-input {
height: 21px;
font-size: 12px;
border-right: none;
width: 140px;
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
color: #000;
min-width: 15px;
width: 100%;
}
pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next,
pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous {
@@ -717,6 +777,7 @@ EOHTML
foreach ($this->styles as $class => $style) {
$line .= 'pre.sf-dump'.('default' === $class ? ', pre.sf-dump' : '').' .sf-dump-'.$class.'{'.$style.'}';
}
$line .= 'pre.sf-dump .sf-dump-ellipsis-note{'.$this->styles['note'].'}';
return $this->dumpHeader = preg_replace('/\s+/', ' ', $line).'</style>'.$this->dumpHeader;
}
@@ -724,19 +785,48 @@ EOHTML
/**
* {@inheritdoc}
*/
public function enterHash(Cursor $cursor, $type, $class, $hasChild)
public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut)
{
if ('' === $str && isset($cursor->attr['img-data'], $cursor->attr['content-type'])) {
$this->dumpKey($cursor);
$this->line .= $this->style('default', $cursor->attr['img-size'] ?? '', []);
$this->line .= $cursor->depth >= $this->displayOptions['maxDepth'] ? ' <samp class=sf-dump-compact>' : ' <samp class=sf-dump-expanded>';
$this->endValue($cursor);
$this->line .= $this->indentPad;
$this->line .= sprintf('<img src="data:%s;base64,%s" /></samp>', $cursor->attr['content-type'], base64_encode($cursor->attr['img-data']));
$this->endValue($cursor);
} else {
parent::dumpString($cursor, $str, $bin, $cut);
}
}
/**
* {@inheritdoc}
*/
public function enterHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild)
{
if (Cursor::HASH_OBJECT === $type) {
$cursor->attr['depth'] = $cursor->depth;
}
parent::enterHash($cursor, $type, $class, false);
if ($cursor->skipChildren || $cursor->depth >= $this->displayOptions['maxDepth']) {
$cursor->skipChildren = false;
$eol = ' class=sf-dump-compact>';
} else {
$this->expandNextHash = false;
$eol = ' class=sf-dump-expanded>';
}
if ($hasChild) {
$this->line .= '<samp data-depth='.($cursor->depth + 1);
if ($cursor->refIndex) {
$r = Cursor::HASH_OBJECT !== $type ? 1 - (Cursor::HASH_RESOURCE !== $type) : 2;
$r .= $r && 0 < $cursor->softRefHandle ? $cursor->softRefHandle : $cursor->refIndex;
$this->line .= sprintf('<samp id=%s-ref%s>', $this->dumpId, $r);
} else {
$this->line .= '<samp>';
$this->line .= sprintf(' id=%s-ref%s', $this->dumpId, $r);
}
$this->line .= $eol;
$this->dumpLine($cursor->depth);
}
}
@@ -744,7 +834,7 @@ EOHTML
/**
* {@inheritdoc}
*/
public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut)
public function leaveHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild, int $cut)
{
$this->dumpEllipsis($cursor, $hasChild, $cut);
if ($hasChild) {
@@ -756,7 +846,7 @@ EOHTML
/**
* {@inheritdoc}
*/
protected function style($style, $value, $attr = array())
protected function style(string $style, string $value, array $attr = []): string
{
if ('' === $value) {
return '';
@@ -774,13 +864,18 @@ EOHTML
}
if ('const' === $style && isset($attr['value'])) {
$style .= sprintf(' title="%s"', esc(is_scalar($attr['value']) ? $attr['value'] : json_encode($attr['value'])));
$style .= sprintf(' title="%s"', esc(\is_scalar($attr['value']) ? $attr['value'] : json_encode($attr['value'])));
} elseif ('public' === $style) {
$style .= sprintf(' title="%s"', empty($attr['dynamic']) ? 'Public property' : 'Runtime added dynamic property');
} elseif ('str' === $style && 1 < $attr['length']) {
$style .= sprintf(' title="%d%s characters"', $attr['length'], $attr['binary'] ? ' binary or non-UTF-8' : '');
} elseif ('note' === $style && false !== $c = strrpos($v, '\\')) {
return sprintf('<abbr title="%s" class=sf-dump-%s>%s</abbr>', $v, $style, substr($v, $c + 1));
} elseif ('note' === $style && 0 < ($attr['depth'] ?? 0) && false !== $c = strrpos($value, '\\')) {
$style .= ' title=""';
$attr += [
'ellipsis' => \strlen($value) - $c,
'ellipsis-type' => 'note',
'ellipsis-tail' => 1,
];
} elseif ('protected' === $style) {
$style .= ' title="Protected property"';
} elseif ('meta' === $style && isset($attr['title'])) {
@@ -797,31 +892,44 @@ EOHTML
}
$label = esc(substr($value, -$attr['ellipsis']));
$style = str_replace(' title="', " title=\"$v\n", $style);
$v = sprintf('<span class=%s>%s</span>', $class, substr($v, 0, -strlen($label)));
$v = sprintf('<span class=%s>%s</span>', $class, substr($v, 0, -\strlen($label)));
if (!empty($attr['ellipsis-tail'])) {
$tail = strlen(esc(substr($value, -$attr['ellipsis'], $attr['ellipsis-tail'])));
$v .= sprintf('<span class=sf-dump-ellipsis>%s</span>%s', substr($label, 0, $tail), substr($label, $tail));
$tail = \strlen(esc(substr($value, -$attr['ellipsis'], $attr['ellipsis-tail'])));
$v .= sprintf('<span class=%s>%s</span>%s', $class, substr($label, 0, $tail), substr($label, $tail));
} else {
$v .= $label;
}
}
$v = "<span class=sf-dump-{$style}>".preg_replace_callback(static::$controlCharsRx, function ($c) use ($map) {
$s = '<span class=sf-dump-default>';
$s = $b = '<span class="sf-dump-default';
$c = $c[$i = 0];
if ($ns = "\r" === $c[$i] || "\n" === $c[$i]) {
$s .= ' sf-dump-ns';
}
$s .= '">';
do {
$s .= isset($map[$c[$i]]) ? $map[$c[$i]] : sprintf('\x%02X', ord($c[$i]));
if (("\r" === $c[$i] || "\n" === $c[$i]) !== $ns) {
$s .= '</span>'.$b;
if ($ns = !$ns) {
$s .= ' sf-dump-ns';
}
$s .= '">';
}
$s .= $map[$c[$i]] ?? sprintf('\x%02X', \ord($c[$i]));
} while (isset($c[++$i]));
return $s.'</span>';
}, $v).'</span>';
if (isset($attr['file']) && $href = $this->getSourceLink($attr['file'], isset($attr['line']) ? $attr['line'] : 0)) {
if (isset($attr['file']) && $href = $this->getSourceLink($attr['file'], $attr['line'] ?? 0)) {
$attr['href'] = $href;
}
if (isset($attr['href'])) {
$v = sprintf('<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>', esc($this->utf8Encode($attr['href'])), $v);
$target = isset($attr['file']) ? '' : ' target="_blank"';
$v = sprintf('<a href="%s"%s rel="noopener noreferrer">%s</a>', esc($this->utf8Encode($attr['href'])), $target, $v);
}
if (isset($attr['lang'])) {
$v = sprintf('<code class="%s">%s</code>', esc($attr['lang']), $v);
@@ -833,26 +941,26 @@ EOHTML
/**
* {@inheritdoc}
*/
protected function dumpLine($depth, $endOfValue = false)
protected function dumpLine(int $depth, bool $endOfValue = false)
{
if (-1 === $this->lastDepth) {
$this->line = sprintf($this->dumpPrefix, $this->dumpId, $this->indentPad).$this->line;
}
if ($this->headerIsDumped !== (null !== $this->outputStream ? $this->outputStream : $this->lineDumper)) {
if ($this->headerIsDumped !== ($this->outputStream ?? $this->lineDumper)) {
$this->line = $this->getDumpHeader().$this->line;
}
if (-1 === $depth) {
$args = array('"'.$this->dumpId.'"');
$args = ['"'.$this->dumpId.'"'];
if ($this->extraDisplayOptions) {
$args[] = json_encode($this->extraDisplayOptions, JSON_FORCE_OBJECT);
$args[] = json_encode($this->extraDisplayOptions, \JSON_FORCE_OBJECT);
}
// Replace is for BC
$this->line .= sprintf(str_replace('"%s"', '%s', $this->dumpSuffix), implode(', ', $args));
}
$this->lastDepth = $depth;
$this->line = mb_convert_encoding($this->line, 'HTML-ENTITIES', 'UTF-8');
$this->line = mb_encode_numericentity($this->line, [0x80, 0x10FFFF, 0, 0x1FFFFF], 'UTF-8');
if (-1 === $depth) {
AbstractDumper::dumpLine(0);
@@ -860,19 +968,19 @@ EOHTML
AbstractDumper::dumpLine($depth);
}
private function getSourceLink($file, $line)
private function getSourceLink(string $file, int $line)
{
$options = $this->extraDisplayOptions + $this->displayOptions;
if ($fmt = $options['fileLinkFormat']) {
return is_string($fmt) ? strtr($fmt, array('%f' => $file, '%l' => $line)) : $fmt->format($file, $line);
return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line);
}
return false;
}
}
function esc($str)
function esc(string $str)
{
return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
return htmlspecialchars($str, \ENT_QUOTES, 'UTF-8');
}

View File

@@ -0,0 +1,53 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Dumper;
use Symfony\Component\VarDumper\Cloner\Data;
use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface;
use Symfony\Component\VarDumper\Server\Connection;
/**
* ServerDumper forwards serialized Data clones to a server.
*
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
class ServerDumper implements DataDumperInterface
{
private $connection;
private $wrappedDumper;
/**
* @param string $host The server host
* @param DataDumperInterface|null $wrappedDumper A wrapped instance used whenever we failed contacting the server
* @param ContextProviderInterface[] $contextProviders Context providers indexed by context name
*/
public function __construct(string $host, DataDumperInterface $wrappedDumper = null, array $contextProviders = [])
{
$this->connection = new Connection($host, $contextProviders);
$this->wrappedDumper = $wrappedDumper;
}
public function getContextProviders(): array
{
return $this->connection->getContextProviders();
}
/**
* {@inheritdoc}
*/
public function dump(Data $data)
{
if (!$this->connection->write($data) && $this->wrappedDumper) {
$this->wrappedDumper->dump($data);
}
}
}