1
0
mirror of https://github.com/mailcow/mailcow-dockerized.git synced 2025-12-22 06:11:32 +00:00

[Web] update directorytree/ldaprecord

This commit is contained in:
FreddleSpl0it
2024-02-20 10:30:11 +01:00
parent 40146839ef
commit d479d18507
481 changed files with 13919 additions and 6171 deletions

View File

@@ -1,6 +1,25 @@
CHANGELOG
=========
6.4
---
* Dump uninitialized properties
6.3
---
* Add caster for `WeakMap`
* Add support of named arguments to `dd()` and `dump()` to display the argument name
* Add support for `Relay\Relay`
* Add display of invisible characters
6.2
---
* Add support for `FFI\CData` and `FFI\CType`
* Deprecate calling `VarDumper::setHandler()` without arguments
5.4
---

View File

@@ -46,6 +46,9 @@ class AmqpCaster
\AMQP_EX_TYPE_HEADERS => 'AMQP_EX_TYPE_HEADERS',
];
/**
* @return array
*/
public static function castConnection(\AMQPConnection $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -79,6 +82,9 @@ class AmqpCaster
return $a;
}
/**
* @return array
*/
public static function castChannel(\AMQPChannel $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -102,6 +108,9 @@ class AmqpCaster
return $a;
}
/**
* @return array
*/
public static function castQueue(\AMQPQueue $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -125,6 +134,9 @@ class AmqpCaster
return $a;
}
/**
* @return array
*/
public static function castExchange(\AMQPExchange $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -153,6 +165,9 @@ class AmqpCaster
return $a;
}
/**
* @return array
*/
public static function castEnvelope(\AMQPEnvelope $c, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
$prefix = Caster::PREFIX_VIRTUAL;

View File

@@ -28,7 +28,7 @@ class ArgsStub extends EnumStub
$values = [];
foreach ($args as $k => $v) {
$values[$k] = !is_scalar($v) && !$v instanceof Stub ? new CutStub($v) : $v;
$values[$k] = !\is_scalar($v) && !$v instanceof Stub ? new CutStub($v) : $v;
}
if (null === $params) {
parent::__construct($values, false);
@@ -57,7 +57,7 @@ class ArgsStub extends EnumStub
try {
$r = null !== $class ? new \ReflectionMethod($class, $function) : new \ReflectionFunction($function);
} catch (\ReflectionException $e) {
} catch (\ReflectionException) {
return [null, null];
}

View File

@@ -32,22 +32,27 @@ class Caster
public const EXCLUDE_EMPTY = 128;
public const EXCLUDE_NOT_IMPORTANT = 256;
public const EXCLUDE_STRICT = 512;
public const EXCLUDE_UNINITIALIZED = 1024;
public const PREFIX_VIRTUAL = "\0~\0";
public const PREFIX_DYNAMIC = "\0+\0";
public const PREFIX_PROTECTED = "\0*\0";
// usage: sprintf(Caster::PATTERN_PRIVATE, $class, $property)
public const PATTERN_PRIVATE = "\0%s\0%s";
private static array $classProperties = [];
/**
* Casts objects to arrays and adds the dynamic property prefix.
*
* @param bool $hasDebugInfo Whether the __debugInfo method exists on $obj or not
*/
public static function castObject(object $obj, string $class, bool $hasDebugInfo = false, string $debugClass = null): array
public static function castObject(object $obj, string $class, bool $hasDebugInfo = false, ?string $debugClass = null): array
{
if ($hasDebugInfo) {
try {
$debugInfo = $obj->__debugInfo();
} catch (\Exception $e) {
} catch (\Throwable) {
// ignore failing __debugInfo()
$hasDebugInfo = false;
}
@@ -59,20 +64,17 @@ class Caster
return $a;
}
$classProperties = self::$classProperties[$class] ??= self::getClassProperties(new \ReflectionClass($class));
$a = array_replace($classProperties, $a);
if ($a) {
static $publicProperties = [];
$debugClass = $debugClass ?? get_debug_type($obj);
$debugClass ??= get_debug_type($obj);
$i = 0;
$prefixedKeys = [];
foreach ($a as $k => $v) {
if ("\0" !== ($k[0] ?? '')) {
if (!isset($publicProperties[$class])) {
foreach ((new \ReflectionClass($class))->getProperties(\ReflectionProperty::IS_PUBLIC) as $prop) {
$publicProperties[$class][$prop->name] = true;
}
}
if (!isset($publicProperties[$class][$k])) {
if (!isset($classProperties[$k])) {
$prefixedKeys[$i] = self::PREFIX_DYNAMIC.$k;
}
} elseif ($debugClass !== $class && 1 === strpos($k, $class)) {
@@ -115,7 +117,7 @@ class Caster
* @param array $a The array containing the properties to filter
* @param int $filter A bit field of Caster::EXCLUDE_* constants specifying which properties to filter out
* @param string[] $listedProperties List of properties to exclude when Caster::EXCLUDE_VERBOSE is set, and to preserve when Caster::EXCLUDE_NOT_IMPORTANT is set
* @param int &$count Set to the number of removed properties
* @param int|null &$count Set to the number of removed properties
*/
public static function filter(array $a, int $filter, array $listedProperties = [], ?int &$count = 0): array
{
@@ -129,6 +131,8 @@ class Caster
$type |= self::EXCLUDE_EMPTY & $filter;
} elseif (false === $v || '' === $v || '0' === $v || 0 === $v || 0.0 === $v || [] === $v) {
$type |= self::EXCLUDE_EMPTY & $filter;
} elseif ($v instanceof UninitializedStub) {
$type |= self::EXCLUDE_UNINITIALIZED & $filter;
}
if ((self::EXCLUDE_NOT_IMPORTANT & $filter) && !\in_array($k, $listedProperties, true)) {
$type |= self::EXCLUDE_NOT_IMPORTANT;
@@ -167,4 +171,28 @@ class Caster
return $a;
}
private static function getClassProperties(\ReflectionClass $class): array
{
$classProperties = [];
$className = $class->name;
if ($parent = $class->getParentClass()) {
$classProperties += self::$classProperties[$parent->name] ??= self::getClassProperties($parent);
}
foreach ($class->getProperties() as $p) {
if ($p->isStatic()) {
continue;
}
$classProperties[match (true) {
$p->isPublic() => $p->name,
$p->isProtected() => self::PREFIX_PROTECTED.$p->name,
default => "\0".$className."\0".$p->name,
}] = new UninitializedStub($p);
}
return $classProperties;
}
}

View File

@@ -24,7 +24,7 @@ class ClassStub extends ConstStub
* @param string $identifier A PHP identifier, e.g. a class, method, interface, etc. name
* @param callable $callable The callable targeted by the identifier when it is ambiguous or not a real PHP identifier
*/
public function __construct(string $identifier, callable|array|string $callable = null)
public function __construct(string $identifier, callable|array|string|null $callable = null)
{
$this->value = $identifier;
@@ -50,15 +50,13 @@ class ClassStub extends ConstStub
if (\is_array($r)) {
try {
$r = new \ReflectionMethod($r[0], $r[1]);
} catch (\ReflectionException $e) {
} catch (\ReflectionException) {
$r = new \ReflectionClass($r[0]);
}
}
if (str_contains($identifier, "@anonymous\0")) {
$this->value = $identifier = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', function ($m) {
return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0];
}, $identifier);
$this->value = $identifier = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $identifier);
}
if (null !== $callable && $r instanceof \ReflectionFunctionAbstract) {
@@ -71,7 +69,7 @@ class ClassStub extends ConstStub
$this->value .= $s;
}
}
} catch (\ReflectionException $e) {
} catch (\ReflectionException) {
return;
} finally {
if (0 < $i = strrpos($this->value, '\\')) {
@@ -87,6 +85,9 @@ class ClassStub extends ConstStub
}
}
/**
* @return mixed
*/
public static function wrapCallable(mixed $callable)
{
if (\is_object($callable) || !\is_callable($callable)) {

View File

@@ -20,7 +20,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class ConstStub extends Stub
{
public function __construct(string $name, string|int|float $value = null)
public function __construct(string $name, string|int|float|null $value = null)
{
$this->class = $name;
$this->value = 1 < \func_num_args() ? $value : $name;

View File

@@ -27,7 +27,7 @@ class CutStub extends Stub
switch (\gettype($value)) {
case 'object':
$this->type = self::TYPE_OBJECT;
$this->class = \get_class($value);
$this->class = $value::class;
if ($value instanceof \Closure) {
ReflectionCaster::castClosure($value, [], $this, true, Caster::EXCLUDE_VERBOSE);

View File

@@ -63,6 +63,9 @@ class DOMCaster
\XML_NAMESPACE_DECL_NODE => 'XML_NAMESPACE_DECL_NODE',
];
/**
* @return array
*/
public static function castException(\DOMException $e, array $a, Stub $stub, bool $isNested)
{
$k = Caster::PREFIX_PROTECTED.'code';
@@ -73,6 +76,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castLength($dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -82,6 +88,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castImplementation(\DOMImplementation $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -92,6 +101,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castNode(\DOMNode $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -116,6 +128,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castNameSpaceNode(\DOMNameSpaceNode $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -132,6 +147,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castDocument(\DOMDocument $dom, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
$a += [
@@ -166,6 +184,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castCharacterData(\DOMCharacterData $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -176,6 +197,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castAttr(\DOMAttr $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -189,6 +213,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castElement(\DOMElement $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -199,6 +226,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castText(\DOMText $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -208,43 +238,9 @@ class DOMCaster
return $a;
}
public static function castTypeinfo(\DOMTypeinfo $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
'typeName' => $dom->typeName,
'typeNamespace' => $dom->typeNamespace,
];
return $a;
}
public static function castDomError(\DOMDomError $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
'severity' => $dom->severity,
'message' => $dom->message,
'type' => $dom->type,
'relatedException' => $dom->relatedException,
'related_data' => $dom->related_data,
'location' => $dom->location,
];
return $a;
}
public static function castLocator(\DOMLocator $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
'lineNumber' => $dom->lineNumber,
'columnNumber' => $dom->columnNumber,
'offset' => $dom->offset,
'relatedNode' => $dom->relatedNode,
'uri' => $dom->uri ? new LinkStub($dom->uri, $dom->lineNumber) : $dom->uri,
];
return $a;
}
/**
* @return array
*/
public static function castDocumentType(\DOMDocumentType $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -259,6 +255,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castNotation(\DOMNotation $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -269,6 +268,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castEntity(\DOMEntity $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -283,6 +285,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castProcessingInstruction(\DOMProcessingInstruction $dom, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -293,6 +298,9 @@ class DOMCaster
return $a;
}
/**
* @return array
*/
public static function castXPath(\DOMXPath $dom, array $a, Stub $stub, bool $isNested)
{
$a += [

View File

@@ -24,11 +24,14 @@ class DateCaster
{
private const PERIOD_LIMIT = 3;
/**
* @return array
*/
public static function castDateTime(\DateTimeInterface $d, array $a, Stub $stub, bool $isNested, int $filter)
{
$prefix = Caster::PREFIX_VIRTUAL;
$location = $d->getTimezone()->getLocation();
$fromNow = (new \DateTime())->diff($d);
$location = $d->getTimezone() ? $d->getTimezone()->getLocation() : null;
$fromNow = (new \DateTimeImmutable())->diff($d);
$title = $d->format('l, F j, Y')
."\n".self::formatInterval($fromNow).' from now'
@@ -47,6 +50,9 @@ class DateCaster
return $a;
}
/**
* @return array
*/
public static function castInterval(\DateInterval $interval, array $a, Stub $stub, bool $isNested, int $filter)
{
$now = new \DateTimeImmutable('@0', new \DateTimeZone('UTC'));
@@ -76,10 +82,13 @@ class DateCaster
return $i->format(rtrim($format));
}
/**
* @return array
*/
public static function castTimeZone(\DateTimeZone $timeZone, array $a, Stub $stub, bool $isNested, int $filter)
{
$location = $timeZone->getLocation();
$formatted = (new \DateTime('now', $timeZone))->format($location ? 'e (P)' : 'P');
$formatted = (new \DateTimeImmutable('now', $timeZone))->format($location ? 'e (P)' : 'P');
$title = $location && \extension_loaded('intl') ? \Locale::getDisplayRegion('-'.$location['country_code']) : '';
$z = [Caster::PREFIX_VIRTUAL.'timezone' => new ConstStub($formatted, $title)];
@@ -87,6 +96,9 @@ class DateCaster
return $filter & Caster::EXCLUDE_VERBOSE ? $z : $z + $a;
}
/**
* @return array
*/
public static function castPeriod(\DatePeriod $p, array $a, Stub $stub, bool $isNested, int $filter)
{
$dates = [];
@@ -103,11 +115,11 @@ class DateCaster
}
$period = sprintf(
'every %s, from %s (%s) %s',
'every %s, from %s%s %s',
self::formatInterval($p->getDateInterval()),
$p->include_start_date ? '[' : ']',
self::formatDateTime($p->getStartDate()),
$p->include_start_date ? 'included' : 'excluded',
($end = $p->getEndDate()) ? 'to '.self::formatDateTime($end) : 'recurring '.$p->recurrences.' time/s'
($end = $p->getEndDate()) ? 'to '.self::formatDateTime($end).(\PHP_VERSION_ID >= 80200 && $p->include_end_date ? ']' : '[') : 'recurring '.$p->recurrences.' time/s'
);
$p = [Caster::PREFIX_VIRTUAL.'period' => new ConstStub($period, implode("\n", $dates))];

View File

@@ -25,6 +25,9 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class DoctrineCaster
{
/**
* @return array
*/
public static function castCommonProxy(CommonProxy $proxy, array $a, Stub $stub, bool $isNested)
{
foreach (['__cloner__', '__initializer__'] as $k) {
@@ -37,6 +40,9 @@ class DoctrineCaster
return $a;
}
/**
* @return array
*/
public static function castOrmProxy(OrmProxy $proxy, array $a, Stub $stub, bool $isNested)
{
foreach (['_entityPersister', '_identifier'] as $k) {
@@ -49,6 +55,9 @@ class DoctrineCaster
return $a;
}
/**
* @return array
*/
public static function castPersistentCollection(PersistentCollection $coll, array $a, Stub $stub, bool $isNested)
{
foreach (['snapshot', 'association', 'typeClass'] as $k) {

View File

@@ -18,7 +18,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class DsPairStub extends Stub
{
public function __construct(string|int $key, mixed $value)
public function __construct(mixed $key, mixed $value)
{
$this->value = [
Caster::PREFIX_VIRTUAL.'key' => $key,

View File

@@ -11,6 +11,7 @@
namespace Symfony\Component\VarDumper\Caster;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext;
use Symfony\Component\VarDumper\Cloner\Stub;
use Symfony\Component\VarDumper\Exception\ThrowingCasterException;
@@ -46,16 +47,25 @@ class ExceptionCaster
private static array $framesCache = [];
/**
* @return array
*/
public static function castError(\Error $e, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
return self::filterExceptionArray($stub->class, $a, "\0Error\0", $filter);
}
/**
* @return array
*/
public static function castException(\Exception $e, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
return self::filterExceptionArray($stub->class, $a, "\0Exception\0", $filter);
}
/**
* @return array
*/
public static function castErrorException(\ErrorException $e, array $a, Stub $stub, bool $isNested)
{
if (isset($a[$s = Caster::PREFIX_PROTECTED.'severity'], self::$errorTypes[$a[$s]])) {
@@ -65,6 +75,9 @@ class ExceptionCaster
return $a;
}
/**
* @return array
*/
public static function castThrowingCasterException(ThrowingCasterException $e, array $a, Stub $stub, bool $isNested)
{
$trace = Caster::PREFIX_VIRTUAL.'trace';
@@ -83,6 +96,9 @@ class ExceptionCaster
return $a;
}
/**
* @return array
*/
public static function castSilencedErrorContext(SilencedErrorContext $e, array $a, Stub $stub, bool $isNested)
{
$sPrefix = "\0".SilencedErrorContext::class."\0";
@@ -110,6 +126,9 @@ class ExceptionCaster
return $a;
}
/**
* @return array
*/
public static function castTraceStub(TraceStub $trace, array $a, Stub $stub, bool $isNested)
{
if (!$isNested) {
@@ -184,6 +203,9 @@ class ExceptionCaster
return $a;
}
/**
* @return array
*/
public static function castFrameStub(FrameStub $frame, array $a, Stub $stub, bool $isNested)
{
if (!$isNested) {
@@ -267,6 +289,19 @@ class ExceptionCaster
return $a;
}
/**
* @return array
*/
public static function castFlattenException(FlattenException $e, array $a, Stub $stub, bool $isNested)
{
if ($isNested) {
$k = sprintf(Caster::PATTERN_PRIVATE, FlattenException::class, 'traceAsString');
$a[$k] = new CutStub($a[$k]);
}
return $a;
}
private static function filterExceptionArray(string $xClass, array $a, string $xPrefix, int $filter): array
{
if (isset($a[$xPrefix.'trace'])) {
@@ -285,12 +320,10 @@ class ExceptionCaster
if (empty($a[$xPrefix.'previous'])) {
unset($a[$xPrefix.'previous']);
}
unset($a[$xPrefix.'string'], $a[Caster::PREFIX_DYNAMIC.'xdebug_message'], $a[Caster::PREFIX_DYNAMIC.'__destructorException']);
unset($a[$xPrefix.'string'], $a[Caster::PREFIX_DYNAMIC.'xdebug_message']);
if (isset($a[Caster::PREFIX_PROTECTED.'message']) && str_contains($a[Caster::PREFIX_PROTECTED.'message'], "@anonymous\0")) {
$a[Caster::PREFIX_PROTECTED.'message'] = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', function ($m) {
return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0];
}, $a[Caster::PREFIX_PROTECTED.'message']);
$a[Caster::PREFIX_PROTECTED.'message'] = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)[0-9a-fA-F]++/', fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $a[Caster::PREFIX_PROTECTED.'message']);
}
if (isset($a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line'])) {
@@ -337,7 +370,7 @@ class ExceptionCaster
$stub->attr['file'] = $f;
$stub->attr['line'] = $caller->getStartLine();
}
} catch (\ReflectionException $e) {
} catch (\ReflectionException) {
// ignore fake class/function
}
@@ -352,9 +385,7 @@ class ExceptionCaster
$pad = null;
for ($i = $srcContext << 1; $i >= 0; --$i) {
if (isset($src[$i][$ltrim]) && "\r" !== ($c = $src[$i][$ltrim]) && "\n" !== $c) {
if (null === $pad) {
$pad = $c;
}
$pad ??= $c;
if ((' ' !== $c && "\t" !== $c) || $pad !== $c) {
break;
}

View File

@@ -0,0 +1,161 @@
<?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\Caster;
use FFI\CData;
use FFI\CType;
use Symfony\Component\VarDumper\Cloner\Stub;
/**
* Casts FFI extension classes to array representation.
*
* @author Nesmeyanov Kirill <nesk@xakep.ru>
*/
final class FFICaster
{
/**
* In case of "char*" contains a string, the length of which depends on
* some other parameter, then during the generation of the string it is
* possible to go beyond the allowable memory area.
*
* This restriction serves to ensure that processing does not take
* up the entire allowable PHP memory limit.
*/
private const MAX_STRING_LENGTH = 255;
public static function castCTypeOrCData(CData|CType $data, array $args, Stub $stub): array
{
if ($data instanceof CType) {
$type = $data;
$data = null;
} else {
$type = \FFI::typeof($data);
}
$stub->class = sprintf('%s<%s> size %d align %d', ($data ?? $type)::class, $type->getName(), $type->getSize(), $type->getAlignment());
return match ($type->getKind()) {
CType::TYPE_FLOAT,
CType::TYPE_DOUBLE,
\defined('\FFI\CType::TYPE_LONGDOUBLE') ? CType::TYPE_LONGDOUBLE : -1,
CType::TYPE_UINT8,
CType::TYPE_SINT8,
CType::TYPE_UINT16,
CType::TYPE_SINT16,
CType::TYPE_UINT32,
CType::TYPE_SINT32,
CType::TYPE_UINT64,
CType::TYPE_SINT64,
CType::TYPE_BOOL,
CType::TYPE_CHAR,
CType::TYPE_ENUM => null !== $data ? [Caster::PREFIX_VIRTUAL.'cdata' => $data->cdata] : [],
CType::TYPE_POINTER => self::castFFIPointer($stub, $type, $data),
CType::TYPE_STRUCT => self::castFFIStructLike($type, $data),
CType::TYPE_FUNC => self::castFFIFunction($stub, $type),
default => $args,
};
}
private static function castFFIFunction(Stub $stub, CType $type): array
{
$arguments = [];
for ($i = 0, $count = $type->getFuncParameterCount(); $i < $count; ++$i) {
$param = $type->getFuncParameterType($i);
$arguments[] = $param->getName();
}
$abi = match ($type->getFuncABI()) {
CType::ABI_DEFAULT,
CType::ABI_CDECL => '[cdecl]',
CType::ABI_FASTCALL => '[fastcall]',
CType::ABI_THISCALL => '[thiscall]',
CType::ABI_STDCALL => '[stdcall]',
CType::ABI_PASCAL => '[pascal]',
CType::ABI_REGISTER => '[register]',
CType::ABI_MS => '[ms]',
CType::ABI_SYSV => '[sysv]',
CType::ABI_VECTORCALL => '[vectorcall]',
default => '[unknown abi]'
};
$returnType = $type->getFuncReturnType();
$stub->class = $abi.' callable('.implode(', ', $arguments).'): '
.$returnType->getName();
return [Caster::PREFIX_VIRTUAL.'returnType' => $returnType];
}
private static function castFFIPointer(Stub $stub, CType $type, ?CData $data = null): array
{
$ptr = $type->getPointerType();
if (null === $data) {
return [Caster::PREFIX_VIRTUAL.'0' => $ptr];
}
return match ($ptr->getKind()) {
CType::TYPE_CHAR => [Caster::PREFIX_VIRTUAL.'cdata' => self::castFFIStringValue($data)],
CType::TYPE_FUNC => self::castFFIFunction($stub, $ptr),
default => [Caster::PREFIX_VIRTUAL.'cdata' => $data[0]],
};
}
private static function castFFIStringValue(CData $data): string|CutStub
{
$result = [];
for ($i = 0; $i < self::MAX_STRING_LENGTH; ++$i) {
$result[$i] = $data[$i];
if ("\0" === $result[$i]) {
return implode('', $result);
}
}
$string = implode('', $result);
$stub = new CutStub($string);
$stub->cut = -1;
$stub->value = $string;
return $stub;
}
private static function castFFIStructLike(CType $type, ?CData $data = null): array
{
$isUnion = ($type->getAttributes() & CType::ATTR_UNION) === CType::ATTR_UNION;
$result = [];
foreach ($type->getStructFieldNames() as $name) {
$field = $type->getStructFieldType($name);
// Retrieving the value of a field from a union containing
// a pointer is not a safe operation, because may contain
// incorrect data.
$isUnsafe = $isUnion && CType::TYPE_POINTER === $field->getKind();
if ($isUnsafe) {
$result[Caster::PREFIX_VIRTUAL.$name.'?'] = $field;
} elseif (null === $data) {
$result[Caster::PREFIX_VIRTUAL.$name] = $field;
} else {
$fieldName = $data->{$name} instanceof CData ? '' : $field->getName().' ';
$result[Caster::PREFIX_VIRTUAL.$fieldName.$name] = $data->{$name};
}
}
return $result;
}
}

View File

@@ -20,6 +20,9 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
final class FiberCaster
{
/**
* @return array
*/
public static function castFiber(\Fiber $fiber, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
$prefix = Caster::PREFIX_VIRTUAL;

View File

@@ -21,6 +21,9 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class IntlCaster
{
/**
* @return array
*/
public static function castMessageFormatter(\MessageFormatter $c, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -31,6 +34,9 @@ class IntlCaster
return self::castError($c, $a);
}
/**
* @return array
*/
public static function castNumberFormatter(\NumberFormatter $c, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
$a += [
@@ -102,12 +108,15 @@ class IntlCaster
'SIGNIFICANT_DIGIT_SYMBOL' => $c->getSymbol(\NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL),
'MONETARY_GROUPING_SEPARATOR_SYMBOL' => $c->getSymbol(\NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL),
]
),
),
];
return self::castError($c, $a);
}
/**
* @return array
*/
public static function castIntlTimeZone(\IntlTimeZone $c, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -125,6 +134,9 @@ class IntlCaster
return self::castError($c, $a);
}
/**
* @return array
*/
public static function castIntlCalendar(\IntlCalendar $c, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
$a += [
@@ -142,6 +154,9 @@ class IntlCaster
return self::castError($c, $a);
}
/**
* @return array
*/
public static function castIntlDateFormatter(\IntlDateFormatter $c, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
$a += [

View File

@@ -23,14 +23,11 @@ class LinkStub extends ConstStub
private static array $vendorRoots;
private static array $composerRoots = [];
public function __construct(string $label, int $line = 0, string $href = null)
public function __construct(string $label, int $line = 0, ?string $href = null)
{
$this->value = $label;
if (null === $href) {
$href = $label;
}
if (!\is_string($href)) {
if (!\is_string($href ??= $label)) {
return;
}
if (str_starts_with($href, 'file://')) {
@@ -63,7 +60,7 @@ class LinkStub extends ConstStub
}
}
private function getComposerRoot(string $file, bool &$inVendor)
private function getComposerRoot(string $file, bool &$inVendor): string|false
{
if (!isset(self::$vendorRoots)) {
self::$vendorRoots = [];

View File

@@ -23,6 +23,9 @@ class MemcachedCaster
private static array $optionConstants;
private static array $defaultOptions;
/**
* @return array
*/
public static function castMemcached(\Memcached $c, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -37,8 +40,8 @@ class MemcachedCaster
private static function getNonDefaultOptions(\Memcached $c): array
{
self::$defaultOptions = self::$defaultOptions ?? self::discoverDefaultOptions();
self::$optionConstants = self::$optionConstants ?? self::getOptionConstants();
self::$defaultOptions ??= self::discoverDefaultOptions();
self::$optionConstants ??= self::getOptionConstants();
$nonDefaultOptions = [];
foreach (self::$optionConstants as $constantKey => $value) {
@@ -56,7 +59,7 @@ class MemcachedCaster
$defaultMemcached->addServer('127.0.0.1', 11211);
$defaultOptions = [];
self::$optionConstants = self::$optionConstants ?? self::getOptionConstants();
self::$optionConstants ??= self::getOptionConstants();
foreach (self::$optionConstants as $constantKey => $value) {
$defaultOptions[$constantKey] = $defaultMemcached->getOption($value);

View File

@@ -59,6 +59,9 @@ class PdoCaster
],
];
/**
* @return array
*/
public static function castPdo(\PDO $c, array $a, Stub $stub, bool $isNested)
{
$attr = [];
@@ -76,7 +79,7 @@ class PdoCaster
if ($v && isset($v[$attr[$k]])) {
$attr[$k] = new ConstStub($v[$attr[$k]], $attr[$k]);
}
} catch (\Exception $e) {
} catch (\Exception) {
}
}
if (isset($attr[$k = 'STATEMENT_CLASS'][1])) {
@@ -108,6 +111,9 @@ class PdoCaster
return $a;
}
/**
* @return array
*/
public static function castPdoStatement(\PDOStatement $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;

View File

@@ -69,6 +69,9 @@ class PgSqlCaster
'function' => \PGSQL_DIAG_SOURCE_FUNCTION,
];
/**
* @return array
*/
public static function castLargeObject($lo, array $a, Stub $stub, bool $isNested)
{
$a['seek position'] = pg_lo_tell($lo);
@@ -76,6 +79,9 @@ class PgSqlCaster
return $a;
}
/**
* @return array
*/
public static function castLink($link, array $a, Stub $stub, bool $isNested)
{
$a['status'] = pg_connection_status($link);
@@ -108,6 +114,9 @@ class PgSqlCaster
return $a;
}
/**
* @return array
*/
public static function castResult($result, array $a, Stub $stub, bool $isNested)
{
$a['num rows'] = pg_num_rows($result);

View File

@@ -21,6 +21,9 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class ProxyManagerCaster
{
/**
* @return array
*/
public static function castProxy(ProxyInterface $c, array $a, Stub $stub, bool $isNested)
{
if ($parent = get_parent_class($c)) {

View File

@@ -31,13 +31,16 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class RdKafkaCaster
{
/**
* @return array
*/
public static function castKafkaConsumer(KafkaConsumer $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
try {
$assignment = $c->getAssignment();
} catch (RdKafkaException $e) {
} catch (RdKafkaException) {
$assignment = [];
}
@@ -51,6 +54,9 @@ class RdKafkaCaster
return $a;
}
/**
* @return array
*/
public static function castTopic(Topic $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -62,6 +68,9 @@ class RdKafkaCaster
return $a;
}
/**
* @return array
*/
public static function castTopicPartition(TopicPartition $c, array $a)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -75,6 +84,9 @@ class RdKafkaCaster
return $a;
}
/**
* @return array
*/
public static function castMessage(Message $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -86,6 +98,9 @@ class RdKafkaCaster
return $a;
}
/**
* @return array
*/
public static function castConf(Conf $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -97,6 +112,9 @@ class RdKafkaCaster
return $a;
}
/**
* @return array
*/
public static function castTopicConf(TopicConf $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -108,6 +126,9 @@ class RdKafkaCaster
return $a;
}
/**
* @return array
*/
public static function castRdKafka(\RdKafka $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -121,6 +142,9 @@ class RdKafkaCaster
return $a;
}
/**
* @return array
*/
public static function castCollectionMetadata(CollectionMetadata $c, array $a, Stub $stub, bool $isNested)
{
$a += iterator_to_array($c);
@@ -128,6 +152,9 @@ class RdKafkaCaster
return $a;
}
/**
* @return array
*/
public static function castTopicMetadata(TopicMetadata $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -140,6 +167,9 @@ class RdKafkaCaster
return $a;
}
/**
* @return array
*/
public static function castPartitionMetadata(PartitionMetadata $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -153,6 +183,9 @@ class RdKafkaCaster
return $a;
}
/**
* @return array
*/
public static function castBrokerMetadata(BrokerMetadata $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -166,13 +199,16 @@ class RdKafkaCaster
return $a;
}
/**
* @return array
*/
private static function extractMetadata(KafkaConsumer|\RdKafka $c)
{
$prefix = Caster::PREFIX_VIRTUAL;
try {
$m = $c->getMetadata(true, null, 500);
} catch (RdKafkaException $e) {
} catch (RdKafkaException) {
return [];
}

View File

@@ -11,6 +11,7 @@
namespace Symfony\Component\VarDumper\Caster;
use Relay\Relay;
use Symfony\Component\VarDumper\Cloner\Stub;
/**
@@ -23,15 +24,15 @@ use Symfony\Component\VarDumper\Cloner\Stub;
class RedisCaster
{
private const SERIALIZERS = [
\Redis::SERIALIZER_NONE => 'NONE',
\Redis::SERIALIZER_PHP => 'PHP',
0 => 'NONE', // Redis::SERIALIZER_NONE
1 => 'PHP', // Redis::SERIALIZER_PHP
2 => 'IGBINARY', // Optional Redis::SERIALIZER_IGBINARY
];
private const MODES = [
\Redis::ATOMIC => 'ATOMIC',
\Redis::MULTI => 'MULTI',
\Redis::PIPELINE => 'PIPELINE',
0 => 'ATOMIC', // Redis::ATOMIC
1 => 'MULTI', // Redis::MULTI
2 => 'PIPELINE', // Redis::PIPELINE
];
private const COMPRESSION_MODES = [
@@ -46,7 +47,10 @@ class RedisCaster
\RedisCluster::FAILOVER_DISTRIBUTE_SLAVES => 'DISTRIBUTE_SLAVES',
];
public static function castRedis(\Redis $c, array $a, Stub $stub, bool $isNested)
/**
* @return array
*/
public static function castRedis(\Redis|Relay $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -72,6 +76,9 @@ class RedisCaster
];
}
/**
* @return array
*/
public static function castRedisArray(\RedisArray $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -84,6 +91,9 @@ class RedisCaster
];
}
/**
* @return array
*/
public static function castRedisCluster(\RedisCluster $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -102,9 +112,9 @@ class RedisCaster
return $a;
}
private static function getRedisOptions(\Redis|\RedisArray|\RedisCluster $redis, array $options = []): EnumStub
private static function getRedisOptions(\Redis|Relay|\RedisArray|\RedisCluster $redis, array $options = []): EnumStub
{
$serializer = $redis->getOption(\Redis::OPT_SERIALIZER);
$serializer = $redis->getOption(\defined('Redis::OPT_SERIALIZER') ? \Redis::OPT_SERIALIZER : 1);
if (\is_array($serializer)) {
foreach ($serializer as &$v) {
if (isset(self::SERIALIZERS[$v])) {
@@ -136,11 +146,11 @@ class RedisCaster
}
$options += [
'TCP_KEEPALIVE' => \defined('Redis::OPT_TCP_KEEPALIVE') ? $redis->getOption(\Redis::OPT_TCP_KEEPALIVE) : 0,
'READ_TIMEOUT' => $redis->getOption(\Redis::OPT_READ_TIMEOUT),
'TCP_KEEPALIVE' => \defined('Redis::OPT_TCP_KEEPALIVE') ? $redis->getOption(\Redis::OPT_TCP_KEEPALIVE) : Relay::OPT_TCP_KEEPALIVE,
'READ_TIMEOUT' => $redis->getOption(\defined('Redis::OPT_READ_TIMEOUT') ? \Redis::OPT_READ_TIMEOUT : Relay::OPT_READ_TIMEOUT),
'COMPRESSION' => $compression,
'SERIALIZER' => $serializer,
'PREFIX' => $redis->getOption(\Redis::OPT_PREFIX),
'PREFIX' => $redis->getOption(\defined('Redis::OPT_PREFIX') ? \Redis::OPT_PREFIX : Relay::OPT_PREFIX),
'SCAN' => $retry,
];

View File

@@ -35,6 +35,9 @@ class ReflectionCaster
'isVariadic' => 'isVariadic',
];
/**
* @return array
*/
public static function castClosure(\Closure $c, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -71,6 +74,9 @@ class ReflectionCaster
return $a;
}
/**
* @return array
*/
public static function unsetClosureFileInfo(\Closure $c, array $a)
{
unset($a[Caster::PREFIX_VIRTUAL.'file'], $a[Caster::PREFIX_VIRTUAL.'line']);
@@ -78,12 +84,12 @@ class ReflectionCaster
return $a;
}
public static function castGenerator(\Generator $c, array $a, Stub $stub, bool $isNested)
public static function castGenerator(\Generator $c, array $a, Stub $stub, bool $isNested): array
{
// Cannot create ReflectionGenerator based on a terminated Generator
try {
$reflectionGenerator = new \ReflectionGenerator($c);
} catch (\Exception $e) {
} catch (\Exception) {
$a[Caster::PREFIX_VIRTUAL.'closed'] = true;
return $a;
@@ -92,6 +98,9 @@ class ReflectionCaster
return self::castReflectionGenerator($reflectionGenerator, $a, $stub, $isNested);
}
/**
* @return array
*/
public static function castType(\ReflectionType $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -114,6 +123,9 @@ class ReflectionCaster
return $a;
}
/**
* @return array
*/
public static function castAttribute(\ReflectionAttribute $c, array $a, Stub $stub, bool $isNested)
{
self::addMap($a, $c, [
@@ -124,6 +136,9 @@ class ReflectionCaster
return $a;
}
/**
* @return array
*/
public static function castReflectionGenerator(\ReflectionGenerator $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -144,7 +159,7 @@ class ReflectionCaster
array_unshift($trace, [
'function' => 'yield',
'file' => $function->getExecutingFile(),
'line' => $function->getExecutingLine() - (int) (\PHP_VERSION_ID < 80100),
'line' => $function->getExecutingLine(),
]);
$trace[] = $frame;
$a[$prefix.'trace'] = new TraceStub($trace, false, 0, -1, -1);
@@ -159,6 +174,9 @@ class ReflectionCaster
return $a;
}
/**
* @return array
*/
public static function castClass(\ReflectionClass $c, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -190,6 +208,9 @@ class ReflectionCaster
return $a;
}
/**
* @return array
*/
public static function castFunctionAbstract(\ReflectionFunctionAbstract $c, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -197,7 +218,7 @@ class ReflectionCaster
self::addMap($a, $c, [
'returnsReference' => 'returnsReference',
'returnType' => 'getReturnType',
'class' => 'getClosureScopeClass',
'class' => \PHP_VERSION_ID >= 80111 ? 'getClosureCalledClass' : 'getClosureScopeClass',
'this' => 'getClosureThis',
]);
@@ -248,6 +269,9 @@ class ReflectionCaster
return $a;
}
/**
* @return array
*/
public static function castClassConstant(\ReflectionClassConstant $c, array $a, Stub $stub, bool $isNested)
{
$a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers()));
@@ -258,6 +282,9 @@ class ReflectionCaster
return $a;
}
/**
* @return array
*/
public static function castMethod(\ReflectionMethod $c, array $a, Stub $stub, bool $isNested)
{
$a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers()));
@@ -265,6 +292,9 @@ class ReflectionCaster
return $a;
}
/**
* @return array
*/
public static function castParameter(\ReflectionParameter $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -292,19 +322,22 @@ class ReflectionCaster
if ($c->isOptional()) {
try {
$a[$prefix.'default'] = $v = $c->getDefaultValue();
if ($c->isDefaultValueConstant()) {
if ($c->isDefaultValueConstant() && !\is_object($v)) {
$a[$prefix.'default'] = new ConstStub($c->getDefaultValueConstantName(), $v);
}
if (null === $v) {
unset($a[$prefix.'allowsNull']);
}
} catch (\ReflectionException $e) {
} catch (\ReflectionException) {
}
}
return $a;
}
/**
* @return array
*/
public static function castProperty(\ReflectionProperty $c, array $a, Stub $stub, bool $isNested)
{
$a[Caster::PREFIX_VIRTUAL.'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers()));
@@ -315,6 +348,9 @@ class ReflectionCaster
return $a;
}
/**
* @return array
*/
public static function castReference(\ReflectionReference $c, array $a, Stub $stub, bool $isNested)
{
$a[Caster::PREFIX_VIRTUAL.'id'] = $c->getId();
@@ -322,6 +358,9 @@ class ReflectionCaster
return $a;
}
/**
* @return array
*/
public static function castExtension(\ReflectionExtension $c, array $a, Stub $stub, bool $isNested)
{
self::addMap($a, $c, [
@@ -338,6 +377,9 @@ class ReflectionCaster
return $a;
}
/**
* @return array
*/
public static function castZendExtension(\ReflectionZendExtension $c, array $a, Stub $stub, bool $isNested)
{
self::addMap($a, $c, [
@@ -350,6 +392,9 @@ class ReflectionCaster
return $a;
}
/**
* @return string
*/
public static function getSignature(array $a)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -402,7 +447,7 @@ class ReflectionCaster
return $signature;
}
private static function addExtra(array &$a, \Reflector $c)
private static function addExtra(array &$a, \Reflector $c): void
{
$x = isset($a[Caster::PREFIX_VIRTUAL.'extra']) ? $a[Caster::PREFIX_VIRTUAL.'extra']->value : [];
@@ -418,7 +463,7 @@ class ReflectionCaster
}
}
private static function addMap(array &$a, object $c, array $map, string $prefix = Caster::PREFIX_VIRTUAL)
private static function addMap(array &$a, object $c, array $map, string $prefix = Caster::PREFIX_VIRTUAL): void
{
foreach ($map as $k => $m) {
if ('isDisabled' === $k) {

View File

@@ -27,6 +27,9 @@ class ResourceCaster
return curl_getinfo($h);
}
/**
* @return array
*/
public static function castDba($dba, array $a, Stub $stub, bool $isNested)
{
$list = dba_list();
@@ -35,12 +38,15 @@ class ResourceCaster
return $a;
}
/**
* @return array
*/
public static function castProcess($process, array $a, Stub $stub, bool $isNested)
{
return proc_get_status($process);
}
public static function castStream($stream, array $a, Stub $stub, bool $isNested)
public static function castStream($stream, array $a, Stub $stub, bool $isNested): array
{
$a = stream_get_meta_data($stream) + static::castStreamContext($stream, $a, $stub, $isNested);
if ($a['uri'] ?? false) {
@@ -50,11 +56,17 @@ class ResourceCaster
return $a;
}
/**
* @return array
*/
public static function castStreamContext($stream, array $a, Stub $stub, bool $isNested)
{
return @stream_context_get_params($stream) ?: $a;
}
/**
* @return array
*/
public static function castGd($gd, array $a, Stub $stub, bool $isNested)
{
$a['size'] = imagesx($gd).'x'.imagesy($gd);
@@ -63,15 +75,9 @@ class ResourceCaster
return $a;
}
public static function castMysqlLink($h, array $a, Stub $stub, bool $isNested)
{
$a['host'] = mysql_get_host_info($h);
$a['protocol'] = mysql_get_proto_info($h);
$a['server'] = mysql_get_server_info($h);
return $a;
}
/**
* @return array
*/
public static function castOpensslX509($h, array $a, Stub $stub, bool $isNested)
{
$stub->cut = -1;
@@ -86,7 +92,7 @@ class ResourceCaster
$a += [
'subject' => new EnumStub(array_intersect_key($info['subject'], ['organizationName' => true, 'commonName' => true])),
'issuer' => new EnumStub(array_intersect_key($info['issuer'], ['organizationName' => true, 'commonName' => true])),
'expiry' => new ConstStub(date(\DateTime::ISO8601, $info['validTo_time_t']), $info['validTo_time_t']),
'expiry' => new ConstStub(date(\DateTimeInterface::ISO8601, $info['validTo_time_t']), $info['validTo_time_t']),
'fingerprint' => new EnumStub([
'md5' => new ConstStub(wordwrap(strtoupper(openssl_x509_fingerprint($h, 'md5')), 2, ':', true)),
'sha1' => new ConstStub(wordwrap(strtoupper(openssl_x509_fingerprint($h, 'sha1')), 2, ':', true)),

View File

@@ -0,0 +1,27 @@
<?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\Caster;
use Symfony\Component\VarDumper\Cloner\Stub;
/**
* Represents any arbitrary value.
*
* @author Alexandre Daubois <alex.daubois@gmail.com>
*/
class ScalarStub extends Stub
{
public function __construct(mixed $value)
{
$this->value = $value;
}
}

View File

@@ -29,16 +29,25 @@ class SplCaster
\SplFileObject::READ_CSV => 'READ_CSV',
];
/**
* @return array
*/
public static function castArrayObject(\ArrayObject $c, array $a, Stub $stub, bool $isNested)
{
return self::castSplArray($c, $a, $stub, $isNested);
}
/**
* @return array
*/
public static function castArrayIterator(\ArrayIterator $c, array $a, Stub $stub, bool $isNested)
{
return self::castSplArray($c, $a, $stub, $isNested);
}
/**
* @return array
*/
public static function castHeap(\Iterator $c, array $a, Stub $stub, bool $isNested)
{
$a += [
@@ -48,6 +57,9 @@ class SplCaster
return $a;
}
/**
* @return array
*/
public static function castDoublyLinkedList(\SplDoublyLinkedList $c, array $a, Stub $stub, bool $isNested)
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -63,6 +75,9 @@ class SplCaster
return $a;
}
/**
* @return array
*/
public static function castFileInfo(\SplFileInfo $c, array $a, Stub $stub, bool $isNested)
{
static $map = [
@@ -117,7 +132,7 @@ class SplCaster
foreach ($map as $key => $accessor) {
try {
$a[$prefix.$key] = $c->$accessor();
} catch (\Exception $e) {
} catch (\Exception) {
}
}
@@ -139,6 +154,9 @@ class SplCaster
return $a;
}
/**
* @return array
*/
public static function castFileObject(\SplFileObject $c, array $a, Stub $stub, bool $isNested)
{
static $map = [
@@ -155,7 +173,7 @@ class SplCaster
foreach ($map as $key => $accessor) {
try {
$a[$prefix.$key] = $c->$accessor();
} catch (\Exception $e) {
} catch (\Exception) {
}
}
@@ -176,6 +194,9 @@ class SplCaster
return $a;
}
/**
* @return array
*/
public static function castObjectStorage(\SplObjectStorage $c, array $a, Stub $stub, bool $isNested)
{
$storage = [];
@@ -184,10 +205,10 @@ class SplCaster
$clone = clone $c;
foreach ($clone as $obj) {
$storage[] = [
$storage[] = new EnumStub([
'object' => $obj,
'info' => $clone->getInfo(),
];
]);
}
$a += [
@@ -197,6 +218,9 @@ class SplCaster
return $a;
}
/**
* @return array
*/
public static function castOuterIterator(\OuterIterator $c, array $a, Stub $stub, bool $isNested)
{
$a[Caster::PREFIX_VIRTUAL.'innerIterator'] = $c->getInnerIterator();
@@ -204,6 +228,9 @@ class SplCaster
return $a;
}
/**
* @return array
*/
public static function castWeakReference(\WeakReference $c, array $a, Stub $stub, bool $isNested)
{
$a[Caster::PREFIX_VIRTUAL.'object'] = $c->get();
@@ -211,6 +238,27 @@ class SplCaster
return $a;
}
/**
* @return array
*/
public static function castWeakMap(\WeakMap $c, array $a, Stub $stub, bool $isNested)
{
$map = [];
foreach (clone $c as $obj => $data) {
$map[] = new EnumStub([
'object' => $obj,
'data' => $data,
]);
}
$a += [
Caster::PREFIX_VIRTUAL.'map' => $map,
];
return $a;
}
private static function castSplArray(\ArrayObject|\ArrayIterator $c, array $a, Stub $stub, bool $isNested): array
{
$prefix = Caster::PREFIX_VIRTUAL;
@@ -218,10 +266,14 @@ class SplCaster
if (!($flags & \ArrayObject::STD_PROP_LIST)) {
$c->setFlags(\ArrayObject::STD_PROP_LIST);
$a = Caster::castObject($c, \get_class($c), method_exists($c, '__debugInfo'), $stub->class);
$a = Caster::castObject($c, $c::class, method_exists($c, '__debugInfo'), $stub->class);
$c->setFlags($flags);
}
unset($a["\0ArrayObject\0storage"], $a["\0ArrayIterator\0storage"]);
$a += [
$prefix.'storage' => $c->getArrayCopy(),
$prefix.'flag::STD_PROP_LIST' => (bool) ($flags & \ArrayObject::STD_PROP_LIST),
$prefix.'flag::ARRAY_AS_PROPS' => (bool) ($flags & \ArrayObject::ARRAY_AS_PROPS),
];

View File

@@ -22,6 +22,9 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class StubCaster
{
/**
* @return array
*/
public static function castStub(Stub $c, array $a, Stub $stub, bool $isNested)
{
if ($isNested) {
@@ -43,11 +46,17 @@ class StubCaster
return $a;
}
/**
* @return array
*/
public static function castCutArray(CutArrayStub $c, array $a, Stub $stub, bool $isNested)
{
return $isNested ? $c->preservedSubset : $a;
}
/**
* @return array
*/
public static function cutInternals($obj, array $a, Stub $stub, bool $isNested)
{
if ($isNested) {
@@ -59,6 +68,9 @@ class StubCaster
return $a;
}
/**
* @return array
*/
public static function castEnum(EnumStub $c, array $a, Stub $stub, bool $isNested)
{
if ($isNested) {
@@ -81,4 +93,15 @@ class StubCaster
return $a;
}
/**
* @return array
*/
public static function castScalar(ScalarStub $scalarStub, array $a, Stub $stub)
{
$stub->type = Stub::TYPE_SCALAR;
$stub->attr['value'] = $scalarStub->value;
return $a;
}
}

View File

@@ -15,6 +15,7 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Uid\Ulid;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\VarDumper\Cloner\Stub;
use Symfony\Component\VarExporter\Internal\LazyObjectState;
/**
* @final
@@ -30,6 +31,9 @@ class SymfonyCaster
'format' => 'getRequestFormat',
];
/**
* @return array
*/
public static function castRequest(Request $request, array $a, Stub $stub, bool $isNested)
{
$clone = null;
@@ -37,9 +41,7 @@ class SymfonyCaster
foreach (self::REQUEST_GETTERS as $prop => $getter) {
$key = Caster::PREFIX_PROTECTED.$prop;
if (\array_key_exists($key, $a) && null === $a[$key]) {
if (null === $clone) {
$clone = clone $request;
}
$clone ??= clone $request;
$a[Caster::PREFIX_VIRTUAL.$prop] = $clone->{$getter}();
}
}
@@ -47,9 +49,12 @@ class SymfonyCaster
return $a;
}
/**
* @return array
*/
public static function castHttpClient($client, array $a, Stub $stub, bool $isNested)
{
$multiKey = sprintf("\0%s\0multi", \get_class($client));
$multiKey = sprintf("\0%s\0multi", $client::class);
if (isset($a[$multiKey])) {
$a[$multiKey] = new CutStub($a[$multiKey]);
}
@@ -57,6 +62,9 @@ class SymfonyCaster
return $a;
}
/**
* @return array
*/
public static function castHttpClientResponse($response, array $a, Stub $stub, bool $isNested)
{
$stub->cut += \count($a);
@@ -69,6 +77,37 @@ class SymfonyCaster
return $a;
}
/**
* @return array
*/
public static function castLazyObjectState($state, array $a, Stub $stub, bool $isNested)
{
if (!$isNested) {
return $a;
}
$stub->cut += \count($a) - 1;
$instance = $a['realInstance'] ?? null;
$a = ['status' => new ConstStub(match ($a['status']) {
LazyObjectState::STATUS_INITIALIZED_FULL => 'INITIALIZED_FULL',
LazyObjectState::STATUS_INITIALIZED_PARTIAL => 'INITIALIZED_PARTIAL',
LazyObjectState::STATUS_UNINITIALIZED_FULL => 'UNINITIALIZED_FULL',
LazyObjectState::STATUS_UNINITIALIZED_PARTIAL => 'UNINITIALIZED_PARTIAL',
}, $a['status'])];
if ($instance) {
$a['realInstance'] = $instance;
--$stub->cut;
}
return $a;
}
/**
* @return array
*/
public static function castUuid(Uuid $uuid, array $a, Stub $stub, bool $isNested)
{
$a[Caster::PREFIX_VIRTUAL.'toBase58'] = $uuid->toBase58();
@@ -82,6 +121,9 @@ class SymfonyCaster
return $a;
}
/**
* @return array
*/
public static function castUlid(Ulid $ulid, array $a, Stub $stub, bool $isNested)
{
$a[Caster::PREFIX_VIRTUAL.'toBase58'] = $ulid->toBase58();

View File

@@ -25,7 +25,7 @@ class TraceStub extends Stub
public $sliceLength;
public $numberingOffset;
public function __construct(array $trace, bool $keepArgs = true, int $sliceOffset = 0, int $sliceLength = null, int $numberingOffset = 0)
public function __construct(array $trace, bool $keepArgs = true, int $sliceOffset = 0, ?int $sliceLength = null, int $numberingOffset = 0)
{
$this->value = $trace;
$this->keepArgs = $keepArgs;

View File

@@ -0,0 +1,25 @@
<?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\Caster;
/**
* Represents an uninitialized property.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class UninitializedStub extends ConstStub
{
public function __construct(\ReflectionProperty $property)
{
parent::__construct('?'.($property->hasType() ? ' '.$property->getType() : ''), 'Uninitialized property');
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* This file is part of the Symfony package.
*
@@ -42,6 +43,9 @@ class XmlReaderCaster
\XMLReader::XML_DECLARATION => 'XML_DECLARATION',
];
/**
* @return array
*/
public static function castXmlReader(\XMLReader $reader, array $a, Stub $stub, bool $isNested)
{
try {
@@ -51,7 +55,7 @@ class XmlReaderCaster
'VALIDATE' => @$reader->getParserProperty(\XMLReader::VALIDATE),
'SUBST_ENTITIES' => @$reader->getParserProperty(\XMLReader::SUBST_ENTITIES),
];
} catch (\Error $e) {
} catch (\Error) {
$properties = [
'LOADDTD' => false,
'DEFAULTATTRS' => false,
@@ -81,6 +85,7 @@ class XmlReaderCaster
$info[$props]->cut = $count;
}
$a = Caster::filter($a, Caster::EXCLUDE_UNINITIALIZED, [], $count);
$info = Caster::filter($info, Caster::EXCLUDE_EMPTY, [], $count);
// +2 because hasValue and hasAttributes are always filtered
$stub->cut += $count + 2;

View File

@@ -47,6 +47,9 @@ class XmlResourceCaster
\XML_ERROR_EXTERNAL_ENTITY_HANDLING => 'XML_ERROR_EXTERNAL_ENTITY_HANDLING',
];
/**
* @return array
*/
public static function castXml($h, array $a, Stub $stub, bool $isNested)
{
$a['current_byte_index'] = xml_get_current_byte_index($h);

View File

@@ -28,6 +28,7 @@ abstract class AbstractCloner implements ClonerInterface
'Symfony\Component\VarDumper\Caster\CutArrayStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castCutArray'],
'Symfony\Component\VarDumper\Caster\ConstStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castStub'],
'Symfony\Component\VarDumper\Caster\EnumStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castEnum'],
'Symfony\Component\VarDumper\Caster\ScalarStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castScalar'],
'Fiber' => ['Symfony\Component\VarDumper\Caster\FiberCaster', 'castFiber'],
@@ -66,9 +67,6 @@ abstract class AbstractCloner implements ClonerInterface
'DOMAttr' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castAttr'],
'DOMElement' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castElement'],
'DOMText' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castText'],
'DOMTypeinfo' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castTypeinfo'],
'DOMDomError' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castDomError'],
'DOMLocator' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLocator'],
'DOMDocumentType' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castDocumentType'],
'DOMNotation' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castNotation'],
'DOMEntity' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castEntity'],
@@ -92,10 +90,12 @@ abstract class AbstractCloner implements ClonerInterface
'Symfony\Component\HttpFoundation\Request' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castRequest'],
'Symfony\Component\Uid\Ulid' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castUlid'],
'Symfony\Component\Uid\Uuid' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castUuid'],
'Symfony\Component\VarExporter\Internal\LazyObjectState' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castLazyObjectState'],
'Symfony\Component\VarDumper\Exception\ThrowingCasterException' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castThrowingCasterException'],
'Symfony\Component\VarDumper\Caster\TraceStub' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castTraceStub'],
'Symfony\Component\VarDumper\Caster\FrameStub' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castFrameStub'],
'Symfony\Component\VarDumper\Cloner\AbstractCloner' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'],
'Symfony\Component\ErrorHandler\Exception\FlattenException' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castFlattenException'],
'Symfony\Component\ErrorHandler\Exception\SilencedErrorContext' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castSilencedErrorContext'],
'Imagine\Image\ImageInterface' => ['Symfony\Component\VarDumper\Caster\ImagineCaster', 'castImage'],
@@ -127,9 +127,11 @@ abstract class AbstractCloner implements ClonerInterface
'SplObjectStorage' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castObjectStorage'],
'SplPriorityQueue' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castHeap'],
'OuterIterator' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castOuterIterator'],
'WeakMap' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castWeakMap'],
'WeakReference' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castWeakReference'],
'Redis' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedis'],
'Relay\Relay' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedis'],
'RedisArray' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedisArray'],
'RedisCluster' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedisCluster'],
@@ -163,7 +165,6 @@ abstract class AbstractCloner implements ClonerInterface
'GdImage' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castGd'],
':gd' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castGd'],
':mysql link' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castMysqlLink'],
':pgsql large object' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLargeObject'],
':pgsql link' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLink'],
':pgsql link persistent' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLink'],
@@ -191,6 +192,9 @@ abstract class AbstractCloner implements ClonerInterface
'RdKafka\Topic' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castTopic'],
'RdKafka\TopicPartition' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castTopicPartition'],
'RdKafka\TopicConf' => ['Symfony\Component\VarDumper\Caster\RdKafkaCaster', 'castTopicConf'],
'FFI\CData' => ['Symfony\Component\VarDumper\Caster\FFICaster', 'castCTypeOrCData'],
'FFI\CType' => ['Symfony\Component\VarDumper\Caster\FFICaster', 'castCTypeOrCData'],
];
protected $maxItems = 2500;
@@ -215,12 +219,9 @@ abstract class AbstractCloner implements ClonerInterface
*
* @see addCasters
*/
public function __construct(array $casters = null)
public function __construct(?array $casters = null)
{
if (null === $casters) {
$casters = static::$defaultCasters;
}
$this->addCasters($casters);
$this->addCasters($casters ?? static::$defaultCasters);
}
/**
@@ -232,6 +233,8 @@ abstract class AbstractCloner implements ClonerInterface
* see e.g. static::$defaultCasters.
*
* @param callable[] $casters A map of casters
*
* @return void
*/
public function addCasters(array $casters)
{
@@ -242,6 +245,8 @@ abstract class AbstractCloner implements ClonerInterface
/**
* Sets the maximum number of items to clone past the minimum depth in nested structures.
*
* @return void
*/
public function setMaxItems(int $maxItems)
{
@@ -250,6 +255,8 @@ abstract class AbstractCloner implements ClonerInterface
/**
* Sets the maximum cloned length for strings.
*
* @return void
*/
public function setMaxString(int $maxString)
{
@@ -259,6 +266,8 @@ abstract class AbstractCloner implements ClonerInterface
/**
* Sets the minimum tree depth where we are guaranteed to clone all the items. After this
* depth is reached, only setMaxItems items will be cloned.
*
* @return void
*/
public function setMinDepth(int $minDepth)
{

View File

@@ -17,7 +17,7 @@ use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider;
/**
* @author Nicolas Grekas <p@tchwork.com>
*/
class Data implements \ArrayAccess, \Countable, \IteratorAggregate
class Data implements \ArrayAccess, \Countable, \IteratorAggregate, \Stringable
{
private array $data;
private int $position = 0;
@@ -121,6 +121,9 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
yield from $value;
}
/**
* @return mixed
*/
public function __get(string $key)
{
if (null !== $data = $this->seek($key)) {
@@ -211,6 +214,11 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
return $data;
}
public function getContext(): array
{
return $this->context;
}
/**
* Seeks to a specific key in nested data structures.
*/
@@ -257,21 +265,21 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
/**
* Dumps data with a DumperInterface dumper.
*
* @return void
*/
public function dump(DumperInterface $dumper)
{
$refs = [0];
$cursor = new Cursor();
$cursor->hashType = -1;
$cursor->attr = $this->context[SourceContextProvider::class] ?? [];
$label = $this->context['label'] ?? '';
if ($cursor->attr = $this->context[SourceContextProvider::class] ?? []) {
$cursor->attr['if_links'] = true;
$cursor->hashType = -1;
$dumper->dumpScalar($cursor, 'default', '^');
$cursor->attr = ['if_links' => true];
$dumper->dumpScalar($cursor, 'default', ' ');
$cursor->hashType = 0;
if ($cursor->attr || '' !== $label) {
$dumper->dumpScalar($cursor, 'label', $label);
}
$cursor->hashType = 0;
$this->dumpItem($dumper, $cursor, $refs, $this->data[$this->position][$this->key]);
}
@@ -280,7 +288,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
*
* @param mixed $item A Stub object or the original value being dumped
*/
private function dumpItem(DumperInterface $dumper, Cursor $cursor, array &$refs, mixed $item)
private function dumpItem(DumperInterface $dumper, Cursor $cursor, array &$refs, mixed $item): void
{
$cursor->refIndex = 0;
$cursor->softRefTo = $cursor->softRefHandle = $cursor->softRefCount = 0;
@@ -362,6 +370,10 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
$dumper->leaveHash($cursor, $item->type, $item->class, $withChildren, $cut);
break;
case Stub::TYPE_SCALAR:
$dumper->dumpScalar($cursor, 'default', $item->attr['value']);
break;
default:
throw new \RuntimeException(sprintf('Unexpected Stub type: "%s".', $item->type));
}
@@ -402,7 +414,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
return $hashCut;
}
private function getStub(mixed $item)
private function getStub(mixed $item): mixed
{
if (!$item || !\is_array($item)) {
return $item;

View File

@@ -20,6 +20,8 @@ interface DumperInterface
{
/**
* Dumps a scalar value.
*
* @return void
*/
public function dumpScalar(Cursor $cursor, string $type, string|int|float|bool|null $value);
@@ -29,6 +31,8 @@ interface DumperInterface
* @param string $str The string being dumped
* @param bool $bin Whether $str is UTF-8 or binary encoded
* @param int $cut The number of characters $str has been cut by
*
* @return void
*/
public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut);
@@ -38,6 +42,8 @@ interface DumperInterface
* @param int $type A Cursor::HASH_* const for the type of hash
* @param string|int|null $class The object class, resource type or array count
* @param bool $hasChild When the dump of the hash has child item
*
* @return void
*/
public function enterHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild);
@@ -48,6 +54,8 @@ interface DumperInterface
* @param string|int|null $class The object class, resource type or array count
* @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
*
* @return void
*/
public function leaveHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild, int $cut);
}

View File

@@ -23,6 +23,7 @@ class Stub
public const TYPE_ARRAY = 3;
public const TYPE_OBJECT = 4;
public const TYPE_RESOURCE = 5;
public const TYPE_SCALAR = 6;
public const STRING_BINARY = 1;
public const STRING_UTF8 = 2;

View File

@@ -16,12 +16,8 @@ namespace Symfony\Component\VarDumper\Cloner;
*/
class VarCloner extends AbstractCloner
{
private static string $gid;
private static array $arrayCache = [];
/**
* {@inheritdoc}
*/
protected function doClone(mixed $var): array
{
$len = 1; // Length of $queue
@@ -44,7 +40,6 @@ class VarCloner extends AbstractCloner
$stub = null; // Stub capturing the main properties of an original item value
// or null if the original value is used directly
$gid = self::$gid ??= md5(random_bytes(6)); // Unique string used to detect the special $GLOBALS variable
$arrayStub = new Stub();
$arrayStub->type = Stub::TYPE_ARRAY;
$fromObjCast = false;
@@ -121,53 +116,15 @@ class VarCloner extends AbstractCloner
}
$stub = $arrayStub;
if (\PHP_VERSION_ID >= 80100) {
$stub->class = array_is_list($v) ? Stub::ARRAY_INDEXED : Stub::ARRAY_ASSOC;
$a = $v;
break;
}
$stub->class = Stub::ARRAY_INDEXED;
$j = -1;
foreach ($v as $gk => $gv) {
if ($gk !== ++$j) {
$stub->class = Stub::ARRAY_ASSOC;
$a = $v;
$a[$gid] = true;
break;
}
}
// Copies of $GLOBALS have very strange behavior,
// let's detect them with some black magic
if (isset($v[$gid])) {
unset($v[$gid]);
$a = [];
foreach ($v as $gk => &$gv) {
if ($v === $gv && !isset($hardRefs[\ReflectionReference::fromArrayElement($v, $gk)->getId()])) {
unset($v);
$v = new Stub();
$v->value = [$v->cut = \count($gv), Stub::TYPE_ARRAY => 0];
$v->handle = -1;
$gv = &$a[$gk];
$hardRefs[\ReflectionReference::fromArrayElement($a, $gk)->getId()] = &$gv;
$gv = $v;
}
$a[$gk] = &$gv;
}
unset($gv);
} else {
$a = $v;
}
$stub->class = array_is_list($v) ? Stub::ARRAY_INDEXED : Stub::ARRAY_ASSOC;
$a = $v;
break;
case \is_object($v):
if (empty($objRefs[$h = spl_object_id($v)])) {
$stub = new Stub();
$stub->type = Stub::TYPE_OBJECT;
$stub->class = \get_class($v);
$stub->class = $v::class;
$stub->value = $v;
$stub->handle = $h;
$a = $this->castObject($stub, 0 < $i);

View File

@@ -26,7 +26,7 @@ use Symfony\Component\VarDumper\Dumper\CliDumper;
*/
class CliDescriptor implements DumpDescriptorInterface
{
private $dumper;
private CliDumper $dumper;
private mixed $lastIdentifier = null;
public function __construct(CliDumper $dumper)

View File

@@ -24,7 +24,7 @@ use Symfony\Component\VarDumper\Dumper\HtmlDumper;
*/
class HtmlDescriptor implements DumpDescriptorInterface
{
private $dumper;
private HtmlDumper $dumper;
private bool $initialized = false;
public function __construct(HtmlDumper $dumper)

View File

@@ -38,7 +38,7 @@ use Symfony\Component\VarDumper\Server\DumpServer;
#[AsCommand(name: 'server:dump', description: 'Start a dump server that collects and displays dumps in a single place')]
class ServerDumpCommand extends Command
{
private $server;
private DumpServer $server;
/** @var DumpDescriptorInterface[] */
private array $descriptors;
@@ -54,7 +54,7 @@ class ServerDumpCommand extends Command
parent::__construct();
}
protected function configure()
protected function configure(): void
{
$this
->addOption('format', null, InputOption::VALUE_REQUIRED, sprintf('The output format (%s)', implode(', ', $this->getAvailableFormats())), 'cli')

View File

@@ -26,12 +26,15 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
public const DUMP_COMMA_SEPARATOR = 4;
public const DUMP_TRAILING_COMMA = 8;
/** @var callable|resource|string|null */
public static $defaultOutput = 'php://output';
protected $line = '';
/** @var callable|null */
protected $lineDumper;
/** @var resource|null */
protected $outputStream;
protected $decimalPoint; // This is locale dependent
protected $decimalPoint = '.';
protected $indentPad = ' ';
protected $flags;
@@ -42,12 +45,10 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
* @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, string $charset = null, int $flags = 0)
public function __construct($output = null, ?string $charset = null, int $flags = 0)
{
$this->flags = $flags;
$this->setCharset($charset ?: ini_get('php.output_encoding') ?: ini_get('default_charset') ?: 'UTF-8');
$this->decimalPoint = localeconv();
$this->decimalPoint = $this->decimalPoint['decimal_point'];
$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)) {
static::$defaultOutput = $this->outputStream;
@@ -57,9 +58,9 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
/**
* Sets the output destination of the dumps.
*
* @param callable|resource|string $output A line dumper callable, an opened stream or an output path
* @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path
*
* @return callable|resource|string The previous output destination
* @return callable|resource|string|null The previous output destination
*/
public function setOutput($output)
{
@@ -73,7 +74,7 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
$output = fopen($output, 'w');
}
$this->outputStream = $output;
$this->lineDumper = [$this, 'echoLine'];
$this->lineDumper = $this->echoLine(...);
}
return $prev;
@@ -120,9 +121,6 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
*/
public function dump(Data $data, $output = null): ?string
{
$this->decimalPoint = localeconv();
$this->decimalPoint = $this->decimalPoint['decimal_point'];
if ($locale = $this->flags & (self::DUMP_COMMA_SEPARATOR | self::DUMP_TRAILING_COMMA) ? setlocale(\LC_NUMERIC, 0) : null) {
setlocale(\LC_NUMERIC, 'C');
}
@@ -160,6 +158,8 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
*
* @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
*
* @return void
*/
protected function dumpLine(int $depth)
{
@@ -169,6 +169,8 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
/**
* Generic line dumper callback.
*
* @return void
*/
protected function echoLine(string $line, int $depth, string $indentPad)
{

View File

@@ -22,6 +22,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
class CliDumper extends AbstractDumper
{
public static $defaultColors;
/** @var callable|resource|string|null */
public static $defaultOutput = 'php://stdout';
protected $colors;
@@ -51,6 +52,7 @@ class CliDumper extends AbstractDumper
"\r" => '\r',
"\033" => '\e',
];
protected static $unicodeCharsRx = "/[\u{00A0}\u{00AD}\u{034F}\u{061C}\u{115F}\u{1160}\u{17B4}\u{17B5}\u{180E}\u{2000}-\u{200F}\u{202F}\u{205F}\u{2060}-\u{2064}\u{206A}-\u{206F}\u{3000}\u{2800}\u{3164}\u{FEFF}\u{FFA0}\u{1D159}\u{1D173}-\u{1D17A}]/u";
protected $collapseNextHash = false;
protected $expandNextHash = false;
@@ -61,10 +63,7 @@ class CliDumper extends AbstractDumper
private bool $handlesHrefGracefully;
/**
* {@inheritdoc}
*/
public function __construct($output = null, string $charset = null, int $flags = 0)
public function __construct($output = null, ?string $charset = null, int $flags = 0)
{
parent::__construct($output, $charset, $flags);
@@ -83,11 +82,13 @@ class CliDumper extends AbstractDumper
]);
}
$this->displayOptions['fileLinkFormat'] = ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format') ?: 'file://%f#L%l';
$this->displayOptions['fileLinkFormat'] = \ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format') ?: 'file://%f#L%l';
}
/**
* Enables/disables colored output.
*
* @return void
*/
public function setColors(bool $colors)
{
@@ -96,6 +97,8 @@ class CliDumper extends AbstractDumper
/**
* Sets the maximum number of characters per line for dumped strings.
*
* @return void
*/
public function setMaxStringWidth(int $maxStringWidth)
{
@@ -106,6 +109,8 @@ class CliDumper extends AbstractDumper
* Configures styles.
*
* @param array $styles A map of style names to style definitions
*
* @return void
*/
public function setStyles(array $styles)
{
@@ -116,6 +121,8 @@ class CliDumper extends AbstractDumper
* Configures display options.
*
* @param array $displayOptions A map of display options to customize the behavior
*
* @return void
*/
public function setDisplayOptions(array $displayOptions)
{
@@ -123,11 +130,12 @@ class CliDumper extends AbstractDumper
}
/**
* {@inheritdoc}
* @return void
*/
public function dumpScalar(Cursor $cursor, string $type, string|int|float|bool|null $value)
{
$this->dumpKey($cursor);
$this->collapseNextHash = $this->expandNextHash = false;
$style = 'const';
$attr = $cursor->attr;
@@ -137,6 +145,11 @@ class CliDumper extends AbstractDumper
$style = 'default';
break;
case 'label':
$this->styles += ['label' => $this->styles['default']];
$style = 'label';
break;
case 'integer':
$style = 'num';
@@ -153,17 +166,12 @@ class CliDumper extends AbstractDumper
$style = 'float';
}
switch (true) {
case \INF === $value: $value = 'INF'; break;
case -\INF === $value: $value = '-INF'; break;
case is_nan($value): $value = 'NAN'; break;
default:
$value = (string) $value;
if (!str_contains($value, $this->decimalPoint)) {
$value .= $this->decimalPoint.'0';
}
break;
}
$value = match (true) {
\INF === $value => 'INF',
-\INF === $value => '-INF',
is_nan($value) => 'NAN',
default => !str_contains($value = (string) $value, $this->decimalPoint) ? $value .= $this->decimalPoint.'0' : $value,
};
break;
case 'NULL':
@@ -186,11 +194,12 @@ class CliDumper extends AbstractDumper
}
/**
* {@inheritdoc}
* @return void
*/
public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut)
{
$this->dumpKey($cursor);
$this->collapseNextHash = $this->expandNextHash = false;
$attr = $cursor->attr;
if ($bin) {
@@ -198,13 +207,16 @@ class CliDumper extends AbstractDumper
}
if ('' === $str) {
$this->line .= '""';
if ($cut) {
$this->line .= '…'.$cut;
}
$this->endValue($cursor);
} else {
$attr += [
'length' => 0 <= $cut ? mb_strlen($str, 'UTF-8') + $cut : 0,
'binary' => $bin,
];
$str = $bin && false !== strpos($str, "\0") ? [$str] : explode("\n", $str);
$str = $bin && str_contains($str, "\0") ? [$str] : explode("\n", $str);
if (isset($str[1]) && !isset($str[2]) && !isset($str[1][0])) {
unset($str[1]);
$str[0] .= "\n";
@@ -274,15 +286,14 @@ class CliDumper extends AbstractDumper
}
/**
* {@inheritdoc}
* @return void
*/
public function enterHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild)
{
if (null === $this->colors) {
$this->colors = $this->supportsColors();
}
$this->colors ??= $this->supportsColors();
$this->dumpKey($cursor);
$this->expandNextHash = false;
$attr = $cursor->attr;
if ($this->collapseNextHash) {
@@ -315,7 +326,7 @@ class CliDumper extends AbstractDumper
}
/**
* {@inheritdoc}
* @return void
*/
public function leaveHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild, int $cut)
{
@@ -332,6 +343,8 @@ class CliDumper extends AbstractDumper
*
* @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
*
* @return void
*/
protected function dumpEllipsis(Cursor $cursor, bool $hasChild, int $cut)
{
@@ -348,6 +361,8 @@ class CliDumper extends AbstractDumper
/**
* Dumps a key in a hash structure.
*
* @return void
*/
protected function dumpKey(Cursor $cursor)
{
@@ -437,12 +452,11 @@ class CliDumper extends AbstractDumper
*/
protected function style(string $style, string $value, array $attr = []): string
{
if (null === $this->colors) {
$this->colors = $this->supportsColors();
}
$this->colors ??= $this->supportsColors();
$this->handlesHrefGracefully ??= 'JetBrains-JediTerm' !== getenv('TERMINAL_EMULATOR')
&& (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100);
&& (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100)
&& !isset($_SERVER['IDEA_INITIAL_DIRECTORY']);
if (isset($attr['ellipsis'], $attr['ellipsis-type'])) {
$prefix = substr($value, 0, -$attr['ellipsis']);
@@ -474,7 +488,15 @@ class CliDumper extends AbstractDumper
return $s.$endCchr;
}, $value, -1, $cchrCount);
if ($this->colors) {
if (!($attr['binary'] ?? false)) {
$value = preg_replace_callback(static::$unicodeCharsRx, function ($c) use (&$cchrCount, $startCchr, $endCchr) {
++$cchrCount;
return $startCchr.'\u{'.strtoupper(dechex(mb_ord($c[0]))).'}'.$endCchr;
}, $value);
}
if ($this->colors && '' !== $value) {
if ($cchrCount && "\033" === $value[0]) {
$value = substr($value, \strlen($startCchr));
} else {
@@ -497,10 +519,15 @@ class CliDumper extends AbstractDumper
}
}
if (isset($attr['href'])) {
if ('label' === $style) {
$value .= '^';
}
$value = "\033]8;;{$attr['href']}\033\\{$value}\033]8;;\033\\";
}
} elseif ($attr['if_links'] ?? false) {
return '';
}
if ('label' === $style && '' !== $value) {
$value .= ' ';
}
return $value;
@@ -511,7 +538,7 @@ class CliDumper extends AbstractDumper
if ($this->outputStream !== static::$defaultOutput) {
return $this->hasColorSupport($this->outputStream);
}
if (null !== static::$defaultColors) {
if (isset(static::$defaultColors)) {
return static::$defaultColors;
}
if (isset($_SERVER['argv'][1])) {
@@ -546,16 +573,23 @@ class CliDumper extends AbstractDumper
}
/**
* {@inheritdoc}
* @return void
*/
protected function dumpLine(int $depth, bool $endOfValue = false)
{
if (null === $this->colors) {
$this->colors = $this->supportsColors();
}
if ($this->colors) {
$this->line = sprintf("\033[%sm%s\033[m", $this->styles['default'], $this->line);
}
parent::dumpLine($depth);
}
/**
* @return void
*/
protected function endValue(Cursor $cursor)
{
if (-1 === $cursor->hashType) {
@@ -632,7 +666,7 @@ class CliDumper extends AbstractDumper
return $result;
}
private function getSourceLink(string $file, int $line)
private function getSourceLink(string $file, int $line): string|false
{
if ($fmt = $this->displayOptions['fileLinkFormat']) {
return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : ($fmt->format($file, $line) ?: 'file://'.$file.'#L'.$line);

View File

@@ -22,8 +22,8 @@ use Symfony\Component\VarDumper\Cloner\VarCloner;
*/
final class RequestContextProvider implements ContextProviderInterface
{
private $requestStack;
private $cloner;
private RequestStack $requestStack;
private VarCloner $cloner;
public function __construct(RequestStack $requestStack)
{

View File

@@ -11,7 +11,8 @@
namespace Symfony\Component\VarDumper\Dumper\ContextProvider;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\ErrorHandler\ErrorRenderer\FileLinkFormatter;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter as LegacyFileLinkFormatter;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
use Symfony\Component\VarDumper\VarDumper;
@@ -28,9 +29,9 @@ final class SourceContextProvider implements ContextProviderInterface
private int $limit;
private ?string $charset;
private ?string $projectDir;
private $fileLinkFormatter;
private FileLinkFormatter|LegacyFileLinkFormatter|null $fileLinkFormatter;
public function __construct(string $charset = null, string $projectDir = null, FileLinkFormatter $fileLinkFormatter = null, int $limit = 9)
public function __construct(?string $charset = null, ?string $projectDir = null, FileLinkFormatter|LegacyFileLinkFormatter|null $fileLinkFormatter = null, int $limit = 9)
{
$this->charset = $charset;
$this->projectDir = $projectDir;
@@ -44,7 +45,7 @@ final class SourceContextProvider implements ContextProviderInterface
$file = $trace[1]['file'];
$line = $trace[1]['line'];
$name = false;
$name = '-' === $file || 'Standard input code' === $file ? 'Standard input code' : false;
$fileExcerpt = false;
for ($i = 2; $i < $this->limit; ++$i) {

View File

@@ -19,7 +19,7 @@ use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface;
*/
class ContextualizedDumper implements DataDumperInterface
{
private $wrappedDumper;
private DataDumperInterface $wrappedDumper;
private array $contextProviders;
/**
@@ -31,13 +31,16 @@ class ContextualizedDumper implements DataDumperInterface
$this->contextProviders = $contextProviders;
}
/**
* @return string|null
*/
public function dump(Data $data)
{
$context = [];
$context = $data->getContext();
foreach ($this->contextProviders as $contextProvider) {
$context[\get_class($contextProvider)] = $contextProvider->getContext();
$context[$contextProvider::class] = $contextProvider->getContext();
}
$this->wrappedDumper->dump($data->withContext($context));
return $this->wrappedDumper->dump($data->withContext($context));
}
}

View File

@@ -20,5 +20,8 @@ use Symfony\Component\VarDumper\Cloner\Data;
*/
interface DataDumperInterface
{
/**
* @return string|null
*/
public function dump(Data $data);
}

View File

@@ -21,6 +21,7 @@ use Symfony\Component\VarDumper\Cloner\Data;
*/
class HtmlDumper extends CliDumper
{
/** @var callable|resource|string|null */
public static $defaultOutput = 'php://output';
protected static $themes = [
@@ -74,19 +75,16 @@ class HtmlDumper extends CliDumper
];
private array $extraDisplayOptions = [];
/**
* {@inheritdoc}
*/
public function __construct($output = null, string $charset = null, int $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'];
}
/**
* {@inheritdoc}
* @return void
*/
public function setStyles(array $styles)
{
@@ -94,6 +92,9 @@ class HtmlDumper extends CliDumper
$this->styles = $styles + $this->styles;
}
/**
* @return void
*/
public function setTheme(string $themeName)
{
if (!isset(static::$themes[$themeName])) {
@@ -107,6 +108,8 @@ class HtmlDumper extends CliDumper
* Configures display options.
*
* @param array $displayOptions A map of display options to customize the behavior
*
* @return void
*/
public function setDisplayOptions(array $displayOptions)
{
@@ -116,6 +119,8 @@ class HtmlDumper extends CliDumper
/**
* Sets an HTML header that will be dumped once in the output stream.
*
* @return void
*/
public function setDumpHeader(?string $header)
{
@@ -124,6 +129,8 @@ class HtmlDumper extends CliDumper
/**
* Sets an HTML prefix and suffix that will encapse every single dump.
*
* @return void
*/
public function setDumpBoundaries(string $prefix, string $suffix)
{
@@ -131,9 +138,6 @@ class HtmlDumper extends CliDumper
$this->dumpSuffix = $suffix;
}
/**
* {@inheritdoc}
*/
public function dump(Data $data, $output = null, array $extraDisplayOptions = []): ?string
{
$this->extraDisplayOptions = $extraDisplayOptions;
@@ -145,6 +149,8 @@ class HtmlDumper extends CliDumper
/**
* Dumps the HTML header.
*
* @return string
*/
protected function getDumpHeader()
{
@@ -158,19 +164,15 @@ class HtmlDumper extends CliDumper
<script>
Sfdump = window.Sfdump || (function (doc) {
var refStyle = doc.createElement('style'),
rxEsc = /([.*+?^${}()|\[\]\/\\])/g,
doc.documentElement.classList.add('sf-js-enabled');
var rxEsc = /([.*+?^${}()|\[\]\/\\])/g,
idRx = /\bsf-dump-\d+-ref[012]\w+\b/,
keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl',
addEventListener = function (e, n, cb) {
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) {
addEventListener = function (element, eventName, callback) {
element.attachEvent('on' + eventName, function (e) {
@@ -350,26 +352,16 @@ return function (root, x) {
function xpathHasClass(className) {
return "contains(concat(' ', normalize-space(@class), ' '), ' " + className +" ')";
}
addEventListener(root, 'mouseover', function (e) {
if ('' != refStyle.innerHTML) {
refStyle.innerHTML = '';
}
});
a('mouseover', function (a, e, c) {
if (c) {
e.target.style.cursor = "pointer";
} else if (a = idRx.exec(a.className)) {
try {
refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}';
} catch (e) {
}
}
});
a('click', function (a, e, c) {
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;
@@ -430,7 +422,8 @@ return function (root, x) {
x += elt.parentNode.getAttribute('data-depth')/1;
}
} else if (/\bsf-dump-ref\b/.test(elt.className) && (a = elt.getAttribute('href'))) {
a = a.substr(1);
a = a.slice(1);
elt.className += ' sf-dump-hover';
elt.className += ' '+a;
if (/[\[{]$/.test(elt.previousSibling.nodeValue)) {
@@ -647,6 +640,16 @@ return function (root, x) {
})(document);
</script><style>
.sf-js-enabled pre.sf-dump .sf-dump-compact,
.sf-js-enabled .sf-dump-str-collapse .sf-dump-str-collapse,
.sf-js-enabled .sf-dump-str-expand .sf-dump-str-expand {
display: none;
}
.sf-dump-hover:hover {
background-color: #B729D9;
color: #FFF !important;
border-radius: 2px;
}
pre.sf-dump {
display: block;
white-space: pre;
@@ -661,7 +664,7 @@ pre.sf-dump:after {
clear: both;
}
pre.sf-dump span {
display: inline;
display: inline-flex;
}
pre.sf-dump a {
text-decoration: none;
@@ -783,7 +786,7 @@ EOHTML
}
/**
* {@inheritdoc}
* @return void
*/
public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut)
{
@@ -801,7 +804,7 @@ EOHTML
}
/**
* {@inheritdoc}
* @return void
*/
public function enterHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild)
{
@@ -832,7 +835,7 @@ EOHTML
}
/**
* {@inheritdoc}
* @return void
*/
public function leaveHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild, int $cut)
{
@@ -843,12 +846,9 @@ EOHTML
parent::leaveHash($cursor, $type, $class, $hasChild, 0);
}
/**
* {@inheritdoc}
*/
protected function style(string $style, string $value, array $attr = []): string
{
if ('' === $value) {
if ('' === $value && ('label' !== $style || !isset($attr['file']) && !isset($attr['href']))) {
return '';
}
@@ -864,7 +864,7 @@ 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']) {
@@ -883,7 +883,6 @@ EOHTML
} elseif ('private' === $style) {
$style .= sprintf(' title="Private property defined in class:&#10;`%s`"', esc($this->utf8Encode($attr['class'])));
}
$map = static::$controlCharsMap;
if (isset($attr['ellipsis'])) {
$class = 'sf-dump-ellipsis';
@@ -902,6 +901,7 @@ EOHTML
}
}
$map = static::$controlCharsMap;
$v = "<span class=sf-dump-{$style}>".preg_replace_callback(static::$controlCharsRx, function ($c) use ($map) {
$s = $b = '<span class="sf-dump-default';
$c = $c[$i = 0];
@@ -924,22 +924,34 @@ EOHTML
return $s.'</span>';
}, $v).'</span>';
if (!($attr['binary'] ?? false)) {
$v = preg_replace_callback(static::$unicodeCharsRx, function ($c) {
return '<span class=sf-dump-default>\u{'.strtoupper(dechex(mb_ord($c[0]))).'}</span>';
}, $v);
}
if (isset($attr['file']) && $href = $this->getSourceLink($attr['file'], $attr['line'] ?? 0)) {
$attr['href'] = $href;
}
if (isset($attr['href'])) {
if ('label' === $style) {
$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);
}
if ('label' === $style) {
$v .= ' ';
}
return $v;
}
/**
* {@inheritdoc}
* @return void
*/
protected function dumpLine(int $depth, bool $endOfValue = false)
{
@@ -960,7 +972,7 @@ EOHTML
}
$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);
@@ -968,7 +980,7 @@ EOHTML
AbstractDumper::dumpLine($depth);
}
private function getSourceLink(string $file, int $line)
private function getSourceLink(string $file, int $line): string|false
{
$options = $this->extraDisplayOptions + $this->displayOptions;
@@ -980,7 +992,7 @@ EOHTML
}
}
function esc(string $str)
function esc(string $str): string
{
return htmlspecialchars($str, \ENT_QUOTES, 'UTF-8');
}

View File

@@ -22,15 +22,15 @@ use Symfony\Component\VarDumper\Server\Connection;
*/
class ServerDumper implements DataDumperInterface
{
private $connection;
private $wrappedDumper;
private Connection $connection;
private ?DataDumperInterface $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 = [])
public function __construct(string $host, ?DataDumperInterface $wrappedDumper = null, array $contextProviders = [])
{
$this->connection = new Connection($host, $contextProviders);
$this->wrappedDumper = $wrappedDumper;
@@ -42,12 +42,14 @@ class ServerDumper implements DataDumperInterface
}
/**
* {@inheritdoc}
* @return string|null
*/
public function dump(Data $data)
{
if (!$this->connection->write($data) && $this->wrappedDumper) {
$this->wrappedDumper->dump($data);
return $this->wrappedDumper->dump($data);
}
return null;
}
}

View File

@@ -21,6 +21,6 @@ class ThrowingCasterException extends \Exception
*/
public function __construct(\Throwable $prev)
{
parent::__construct('Unexpected '.\get_class($prev).' thrown from a caster: '.$prev->getMessage(), 0, $prev);
parent::__construct('Unexpected '.$prev::class.' thrown from a caster: '.$prev->getMessage(), 0, $prev);
}
}

View File

@@ -1,4 +1,4 @@
Copyright (c) 2014-2022 Fabien Potencier
Copyright (c) 2014-present Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -10,6 +10,10 @@
* file that was distributed with this source code.
*/
if ('cli' !== PHP_SAPI) {
throw new Exception('This script must be run from the command line.');
}
/**
* Starts a dump server to collect and output dumps on a single place with multiple formats support.
*

View File

@@ -9,40 +9,52 @@
* file that was distributed with this source code.
*/
use Symfony\Component\VarDumper\Caster\ScalarStub;
use Symfony\Component\VarDumper\VarDumper;
if (!function_exists('dump')) {
/**
* @author Nicolas Grekas <p@tchwork.com>
* @author Alexandre Daubois <alex.daubois@gmail.com>
*/
function dump(mixed $var, mixed ...$moreVars): mixed
function dump(mixed ...$vars): mixed
{
VarDumper::dump($var);
if (!$vars) {
VarDumper::dump(new ScalarStub('🐛'));
foreach ($moreVars as $v) {
VarDumper::dump($v);
return null;
}
if (1 < func_num_args()) {
return func_get_args();
if (array_key_exists(0, $vars) && 1 === count($vars)) {
VarDumper::dump($vars[0]);
$k = 0;
} else {
foreach ($vars as $k => $v) {
VarDumper::dump($v, is_int($k) ? 1 + $k : $k);
}
}
return $var;
if (1 < count($vars)) {
return $vars;
}
return $vars[$k];
}
}
if (!function_exists('dd')) {
/**
* @return never
*/
function dd(...$vars): void
function dd(mixed ...$vars): never
{
if (!in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && !headers_sent()) {
if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true) && !headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
foreach ($vars as $v) {
VarDumper::dump($v);
if (array_key_exists(0, $vars) && 1 === count($vars)) {
VarDumper::dump($vars[0]);
} else {
foreach ($vars as $k => $v) {
VarDumper::dump($v, is_int($k) ? 1 + $k : $k);
}
}
exit(1);

View File

@@ -62,7 +62,7 @@ class Connection
$context = array_filter($context);
$encodedPayload = base64_encode(serialize([$data, $context]))."\n";
set_error_handler([self::class, 'nullErrorHandler']);
set_error_handler(static fn () => null);
try {
if (-1 !== stream_socket_sendto($this->socket, $encodedPayload)) {
return true;
@@ -82,16 +82,14 @@ class Connection
return false;
}
private static function nullErrorHandler(int $t, string $m)
{
// no-op
}
/**
* @return resource|null
*/
private function createSocket()
{
set_error_handler([self::class, 'nullErrorHandler']);
set_error_handler(static fn () => null);
try {
return stream_socket_client($this->host, $errno, $errstr, 3, \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT);
return stream_socket_client($this->host, $errno, $errstr, 3) ?: null;
} finally {
restore_error_handler();
}

View File

@@ -25,14 +25,14 @@ use Symfony\Component\VarDumper\Cloner\Stub;
class DumpServer
{
private string $host;
private $logger;
private ?LoggerInterface $logger;
/**
* @var resource|null
*/
private $socket;
public function __construct(string $host, LoggerInterface $logger = null)
public function __construct(string $host, ?LoggerInterface $logger = null)
{
if (!str_contains($host, '://')) {
$host = 'tcp://'.$host;
@@ -56,25 +56,19 @@ class DumpServer
}
foreach ($this->getMessages() as $clientId => $message) {
if ($this->logger) {
$this->logger->info('Received a payload from client {clientId}', ['clientId' => $clientId]);
}
$this->logger?->info('Received a payload from client {clientId}', ['clientId' => $clientId]);
$payload = @unserialize(base64_decode($message), ['allowed_classes' => [Data::class, Stub::class]]);
// Impossible to decode the message, give up.
if (false === $payload) {
if ($this->logger) {
$this->logger->warning('Unable to decode a message from {clientId} client.', ['clientId' => $clientId]);
}
$this->logger?->warning('Unable to decode a message from {clientId} client.', ['clientId' => $clientId]);
continue;
}
if (!\is_array($payload) || \count($payload) < 2 || !$payload[0] instanceof Data || !\is_array($payload[1])) {
if ($this->logger) {
$this->logger->warning('Invalid payload from {clientId} client. Expected an array of two elements (Data $data, array $context)', ['clientId' => $clientId]);
}
$this->logger?->warning('Invalid payload from {clientId} client. Expected an array of two elements (Data $data, array $context)', ['clientId' => $clientId]);
continue;
}

View File

@@ -27,7 +27,7 @@ trait VarDumperTestTrait
'flags' => null,
];
protected function setUpVarDumper(array $casters, int $flags = null): void
protected function setUpVarDumper(array $casters, ?int $flags = null): void
{
$this->varDumperConfig['casters'] = $casters;
$this->varDumperConfig['flags'] = $flags;
@@ -52,7 +52,7 @@ trait VarDumperTestTrait
$this->assertStringMatchesFormat($this->prepareExpectation($expected, $filter), $this->getDump($data, null, $filter), $message);
}
protected function getDump(mixed $data, string|int $key = null, int $filter = 0): ?string
protected function getDump(mixed $data, string|int|null $key = null, int $filter = 0): ?string
{
if (null === $flags = $this->varDumperConfig['flags']) {
$flags = getenv('DUMP_LIGHT_ARRAY') ? CliDumper::DUMP_LIGHT_ARRAY : 0;

View File

@@ -11,9 +11,9 @@
namespace Symfony\Component\VarDumper;
use Symfony\Component\ErrorHandler\ErrorRenderer\FileLinkFormatter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Symfony\Component\VarDumper\Caster\ReflectionCaster;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
@@ -37,17 +37,26 @@ class VarDumper
*/
private static $handler;
public static function dump(mixed $var)
/**
* @param string|null $label
*
* @return mixed
*/
public static function dump(mixed $var/* , string $label = null */)
{
$label = 2 <= \func_num_args() ? func_get_arg(1) : null;
if (null === self::$handler) {
self::register();
}
return (self::$handler)($var);
return (self::$handler)($var, $label);
}
public static function setHandler(callable $callable = null): ?callable
public static function setHandler(?callable $callable = null): ?callable
{
if (1 > \func_num_args()) {
trigger_deprecation('symfony/var-dumper', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
}
$prevHandler = self::$handler;
// Prevent replacing the handler with expected format as soon as the env var was set:
@@ -76,19 +85,25 @@ class VarDumper
case 'server' === $format:
case $format && 'tcp' === parse_url($format, \PHP_URL_SCHEME):
$host = 'server' === $format ? $_SERVER['VAR_DUMPER_SERVER'] ?? '127.0.0.1:9912' : $format;
$dumper = \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? new CliDumper() : new HtmlDumper();
$dumper = \in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true) ? new CliDumper() : new HtmlDumper();
$dumper = new ServerDumper($host, $dumper, self::getDefaultContextProviders());
break;
default:
$dumper = \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? new CliDumper() : new HtmlDumper();
$dumper = \in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true) ? new CliDumper() : new HtmlDumper();
}
if (!$dumper instanceof ServerDumper) {
$dumper = new ContextualizedDumper($dumper, [new SourceContextProvider()]);
}
self::$handler = function ($var) use ($cloner, $dumper) {
$dumper->dump($cloner->cloneVar($var));
self::$handler = function ($var, ?string $label = null) use ($cloner, $dumper) {
$var = $cloner->cloneVar($var);
if (null !== $label) {
$var = $var->withContext(['label' => $label]);
}
$dumper->dump($var);
};
}
@@ -96,7 +111,7 @@ class VarDumper
{
$contextProviders = [];
if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && (class_exists(Request::class))) {
if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true) && class_exists(Request::class)) {
$requestStack = new RequestStack();
$requestStack->push(Request::createFromGlobals());
$contextProviders['request'] = new RequestContextProvider($requestStack);

View File

@@ -16,25 +16,22 @@
}
],
"require": {
"php": ">=8.0.2",
"php": ">=8.1",
"symfony/deprecation-contracts": "^2.5|^3",
"symfony/polyfill-mbstring": "~1.0"
},
"require-dev": {
"ext-iconv": "*",
"symfony/console": "^5.4|^6.0",
"symfony/process": "^5.4|^6.0",
"symfony/uid": "^5.4|^6.0",
"symfony/console": "^5.4|^6.0|^7.0",
"symfony/error-handler": "^6.3|^7.0",
"symfony/http-kernel": "^5.4|^6.0|^7.0",
"symfony/process": "^5.4|^6.0|^7.0",
"symfony/uid": "^5.4|^6.0|^7.0",
"twig/twig": "^2.13|^3.0.4"
},
"conflict": {
"phpunit/phpunit": "<5.4.3",
"symfony/console": "<5.4"
},
"suggest": {
"ext-iconv": "To convert non-UTF-8 strings to UTF-8 (or symfony/polyfill-iconv in case ext-iconv cannot be used).",
"ext-intl": "To show region name in time zone dump",
"symfony/console": "To use the ServerDumpCommand and/or the bin/var-dump-server script"
},
"autoload": {
"files": [ "Resources/functions/dump.php" ],
"psr-4": { "Symfony\\Component\\VarDumper\\": "" },