package and depencies

This commit is contained in:
RafficMohammed
2023-01-08 02:57:24 +05:30
parent d5332eb421
commit 1d54b8bc7f
4309 changed files with 193331 additions and 172289 deletions

View File

@@ -1,6 +1,12 @@
CHANGELOG
=========
6.2
---
* Add support for `FFI\CData` and `FFI\CType`
* Deprecate calling `VarDumper::setHandler()` without arguments
5.4
---

View File

@@ -20,7 +20,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class ArgsStub extends EnumStub
{
private static $parameters = [];
private static array $parameters = [];
public function __construct(array $args, string $function, ?string $class)
{
@@ -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

@@ -47,7 +47,7 @@ class Caster
if ($hasDebugInfo) {
try {
$debugInfo = $obj->__debugInfo();
} catch (\Throwable $e) {
} catch (\Throwable) {
// ignore failing __debugInfo()
$hasDebugInfo = false;
}
@@ -61,7 +61,7 @@ class Caster
if ($a) {
static $publicProperties = [];
$debugClass = $debugClass ?? get_debug_type($obj);
$debugClass ??= get_debug_type($obj);
$i = 0;
$prefixedKeys = [];

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 = null)
public function __construct(string $identifier, callable|array|string $callable = null)
{
$this->value = $identifier;
@@ -50,7 +50,7 @@ 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]);
}
}
@@ -71,7 +71,7 @@ class ClassStub extends ConstStub
$this->value .= $s;
}
}
} catch (\ReflectionException $e) {
} catch (\ReflectionException) {
return;
} finally {
if (0 < $i = strrpos($this->value, '\\')) {
@@ -87,7 +87,7 @@ class ClassStub extends ConstStub
}
}
public static function wrapCallable($callable)
public static function wrapCallable(mixed $callable)
{
if (\is_object($callable) || !\is_callable($callable)) {
return $callable;

View File

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

View File

@@ -20,14 +20,14 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class CutStub extends Stub
{
public function __construct($value)
public function __construct(mixed $value)
{
$this->value = $value;
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

@@ -208,43 +208,6 @@ 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;
}
public static function castDocumentType(\DOMDocumentType $dom, array $a, Stub $stub, bool $isNested)
{
$a += [

View File

@@ -28,7 +28,7 @@ class DateCaster
{
$prefix = Caster::PREFIX_VIRTUAL;
$location = $d->getTimezone()->getLocation();
$fromNow = (new \DateTime())->diff($d);
$fromNow = (new \DateTimeImmutable())->diff($d);
$title = $d->format('l, F j, Y')
."\n".self::formatInterval($fromNow).' from now'
@@ -79,7 +79,7 @@ class DateCaster
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)];

View File

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

View File

@@ -24,9 +24,9 @@ use Symfony\Component\VarDumper\Exception\ThrowingCasterException;
*/
class ExceptionCaster
{
public static $srcContext = 1;
public static $traceArgs = true;
public static $errorTypes = [
public static int $srcContext = 1;
public static bool $traceArgs = true;
public static array $errorTypes = [
\E_DEPRECATED => 'E_DEPRECATED',
\E_USER_DEPRECATED => 'E_USER_DEPRECATED',
\E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR',
@@ -44,7 +44,7 @@ class ExceptionCaster
\E_STRICT => 'E_STRICT',
];
private static $framesCache = [];
private static array $framesCache = [];
public static function castError(\Error $e, array $a, Stub $stub, bool $isNested, int $filter = 0)
{
@@ -337,7 +337,7 @@ class ExceptionCaster
$stub->attr['file'] = $f;
$stub->attr['line'] = $caller->getStartLine();
}
} catch (\ReflectionException $e) {
} catch (\ReflectionException) {
// ignore fake class/function
}
@@ -352,9 +352,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,17 +20,14 @@ class LinkStub extends ConstStub
{
public $inVendor = false;
private static $vendorRoots;
private static $composerRoots;
private static array $vendorRoots;
private static array $composerRoots = [];
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://')) {
@@ -65,7 +62,7 @@ class LinkStub extends ConstStub
private function getComposerRoot(string $file, bool &$inVendor)
{
if (null === self::$vendorRoots) {
if (!isset(self::$vendorRoots)) {
self::$vendorRoots = [];
foreach (get_declared_classes() as $class) {

View File

@@ -20,8 +20,8 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class MemcachedCaster
{
private static $optionConstants;
private static $defaultOptions;
private static array $optionConstants;
private static array $defaultOptions;
public static function castMemcached(\Memcached $c, array $a, Stub $stub, bool $isNested)
{
@@ -37,8 +37,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 +56,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

@@ -76,7 +76,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])) {

View File

@@ -37,7 +37,7 @@ class RdKafkaCaster
try {
$assignment = $c->getAssignment();
} catch (RdKafkaException $e) {
} catch (RdKafkaException) {
$assignment = [];
}
@@ -166,13 +166,13 @@ class RdKafkaCaster
return $a;
}
private static function extractMetadata($c)
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

@@ -102,10 +102,7 @@ class RedisCaster
return $a;
}
/**
* @param \Redis|\RedisArray|\RedisCluster $redis
*/
private static function getRedisOptions($redis, array $options = []): EnumStub
private static function getRedisOptions(\Redis|\RedisArray|\RedisCluster $redis, array $options = []): EnumStub
{
$serializer = $redis->getOption(\Redis::OPT_SERIALIZER);
if (\is_array($serializer)) {

View File

@@ -83,7 +83,7 @@ class ReflectionCaster
// 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;
@@ -96,7 +96,7 @@ class ReflectionCaster
{
$prefix = Caster::PREFIX_VIRTUAL;
if ($c instanceof \ReflectionNamedType || \PHP_VERSION_ID < 80000) {
if ($c instanceof \ReflectionNamedType) {
$a += [
$prefix.'name' => $c instanceof \ReflectionNamedType ? $c->getName() : (string) $c,
$prefix.'allowsNull' => $c->allowsNull(),
@@ -144,7 +144,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);
@@ -298,7 +298,7 @@ class ReflectionCaster
if (null === $v) {
unset($a[$prefix.'allowsNull']);
}
} catch (\ReflectionException $e) {
} catch (\ReflectionException) {
}
}
@@ -421,7 +421,7 @@ class ReflectionCaster
private static function addMap(array &$a, object $c, array $map, string $prefix = Caster::PREFIX_VIRTUAL)
{
foreach ($map as $k => $m) {
if (\PHP_VERSION_ID >= 80000 && 'isDisabled' === $k) {
if ('isDisabled' === $k) {
continue;
}
@@ -433,10 +433,8 @@ class ReflectionCaster
private static function addAttributes(array &$a, \Reflector $c, string $prefix = Caster::PREFIX_VIRTUAL): void
{
if (\PHP_VERSION_ID >= 80000) {
foreach ($c->getAttributes() as $n) {
$a[$prefix.'attributes'][] = $n;
}
foreach ($c->getAttributes() as $n) {
$a[$prefix.'attributes'][] = $n;
}
}
}

View File

@@ -22,10 +22,7 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class ResourceCaster
{
/**
* @param \CurlHandle|resource $h
*/
public static function castCurl($h, array $a, Stub $stub, bool $isNested): array
public static function castCurl(\CurlHandle $h, array $a, Stub $stub, bool $isNested): array
{
return curl_getinfo($h);
}
@@ -66,15 +63,6 @@ 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;
}
public static function castOpensslX509($h, array $a, Stub $stub, bool $isNested)
{
$stub->cut = -1;
@@ -89,7 +77,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

@@ -94,38 +94,30 @@ class SplCaster
unset($a["\0SplFileInfo\0fileName"]);
unset($a["\0SplFileInfo\0pathName"]);
if (\PHP_VERSION_ID < 80000) {
if (false === $c->getPathname()) {
$a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state';
return $a;
try {
$c->isReadable();
} catch (\RuntimeException $e) {
if ('Object not initialized' !== $e->getMessage()) {
throw $e;
}
} else {
try {
$c->isReadable();
} catch (\RuntimeException $e) {
if ('Object not initialized' !== $e->getMessage()) {
throw $e;
}
$a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state';
$a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state';
return $a;
} catch (\Error $e) {
if ('Object not initialized' !== $e->getMessage()) {
throw $e;
}
$a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state';
return $a;
return $a;
} catch (\Error $e) {
if ('Object not initialized' !== $e->getMessage()) {
throw $e;
}
$a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state';
return $a;
}
foreach ($map as $key => $accessor) {
try {
$a[$prefix.$key] = $c->$accessor();
} catch (\Exception $e) {
} catch (\Exception) {
}
}
@@ -163,7 +155,7 @@ class SplCaster
foreach ($map as $key => $accessor) {
try {
$a[$prefix.$key] = $c->$accessor();
} catch (\Exception $e) {
} catch (\Exception) {
}
}
@@ -219,19 +211,16 @@ class SplCaster
return $a;
}
private static function castSplArray($c, array $a, Stub $stub, bool $isNested): array
private static function castSplArray(\ArrayObject|\ArrayIterator $c, array $a, Stub $stub, bool $isNested): array
{
$prefix = Caster::PREFIX_VIRTUAL;
$flags = $c->getFlags();
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);
}
if (\PHP_VERSION_ID < 70400) {
$a[$prefix.'storage'] = $c->getArrayCopy();
}
$a += [
$prefix.'flag::STD_PROP_LIST' => (bool) ($flags & \ArrayObject::STD_PROP_LIST),
$prefix.'flag::ARRAY_AS_PROPS' => (bool) ($flags & \ArrayObject::ARRAY_AS_PROPS),

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
@@ -37,9 +38,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}();
}
}
@@ -49,7 +48,7 @@ class SymfonyCaster
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]);
}
@@ -69,6 +68,22 @@ class SymfonyCaster
return $a;
}
public static function castLazyObjectState($state, array $a, Stub $stub, bool $isNested)
{
if (!$isNested) {
return $a;
}
$stub->cut += \count($a) - 1;
return ['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'])];
}
public static function castUuid(Uuid $uuid, array $a, Stub $stub, bool $isNested)
{
$a[Caster::PREFIX_VIRTUAL.'toBase58'] = $uuid->toBase58();

View File

@@ -52,7 +52,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,

View File

@@ -66,9 +66,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,6 +89,7 @@ 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'],
@@ -156,7 +154,6 @@ abstract class AbstractCloner implements ClonerInterface
'mysqli_driver' => ['Symfony\Component\VarDumper\Caster\MysqliCaster', 'castMysqliDriver'],
'CurlHandle' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castCurl'],
':curl' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castCurl'],
':dba' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castDba'],
':dba persistent' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castDba'],
@@ -164,7 +161,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'],
@@ -192,6 +188,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;
@@ -201,15 +200,15 @@ abstract class AbstractCloner implements ClonerInterface
/**
* @var array<string, list<callable>>
*/
private $casters = [];
private array $casters = [];
/**
* @var callable|null
*/
private $prevErrorHandler;
private $classInfo = [];
private $filter = 0;
private array $classInfo = [];
private int $filter = 0;
/**
* @param callable[]|null $casters A map of casters
@@ -218,10 +217,7 @@ abstract class AbstractCloner implements ClonerInterface
*/
public function __construct(array $casters = null)
{
if (null === $casters) {
$casters = static::$defaultCasters;
}
$this->addCasters($casters);
$this->addCasters($casters ?? static::$defaultCasters);
}
/**
@@ -269,12 +265,9 @@ abstract class AbstractCloner implements ClonerInterface
/**
* Clones a PHP variable.
*
* @param mixed $var Any PHP variable
* @param int $filter A bit field of Caster::EXCLUDE_* constants
*
* @return Data
* @param int $filter A bit field of Caster::EXCLUDE_* constants
*/
public function cloneVar($var, int $filter = 0)
public function cloneVar(mixed $var, int $filter = 0): Data
{
$this->prevErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) {
if (\E_RECOVERABLE_ERROR === $type || \E_USER_ERROR === $type) {
@@ -306,26 +299,20 @@ abstract class AbstractCloner implements ClonerInterface
/**
* Effectively clones the PHP variable.
*
* @param mixed $var Any PHP variable
*
* @return array
*/
abstract protected function doClone($var);
abstract protected function doClone(mixed $var): array;
/**
* Casts an object to an array representation.
*
* @param bool $isNested True if the object is nested in the dumped structure
*
* @return array
*/
protected function castObject(Stub $stub, bool $isNested)
protected function castObject(Stub $stub, bool $isNested): array
{
$obj = $stub->value;
$class = $stub->class;
if (\PHP_VERSION_ID < 80000 ? "\0" === ($class[15] ?? null) : str_contains($class, "@anonymous\0")) {
if (str_contains($class, "@anonymous\0")) {
$stub->class = get_debug_type($obj);
}
if (isset($this->classInfo[$class])) {
@@ -376,10 +363,8 @@ abstract class AbstractCloner implements ClonerInterface
* Casts a resource to an array representation.
*
* @param bool $isNested True if the object is nested in the dumped structure
*
* @return array
*/
protected function castResource(Stub $stub, bool $isNested)
protected function castResource(Stub $stub, bool $isNested): array
{
$a = [];
$res = $stub->value;

View File

@@ -18,10 +18,6 @@ interface ClonerInterface
{
/**
* Clones a PHP variable.
*
* @param mixed $var Any PHP variable
*
* @return Data
*/
public function cloneVar($var);
public function cloneVar(mixed $var): Data;
}

View File

@@ -19,13 +19,13 @@ use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider;
*/
class Data implements \ArrayAccess, \Countable, \IteratorAggregate
{
private $data;
private $position = 0;
private $key = 0;
private $maxDepth = 20;
private $maxItemsPerDepth = -1;
private $useRefHandles = -1;
private $context = [];
private array $data;
private int $position = 0;
private int|string $key = 0;
private int $maxDepth = 20;
private int $maxItemsPerDepth = -1;
private int $useRefHandles = -1;
private array $context = [];
/**
* @param array $data An array as returned by ClonerInterface::cloneVar()
@@ -35,10 +35,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
$this->data = $data;
}
/**
* @return string|null
*/
public function getType()
public function getType(): ?string
{
$item = $this->data[$this->position][$this->key];
@@ -71,7 +68,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
*
* @return string|int|float|bool|array|Data[]|null
*/
public function getValue($recursive = false)
public function getValue(array|bool $recursive = false): string|int|float|bool|array|null
{
$item = $this->data[$this->position][$this->key];
@@ -110,20 +107,12 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
return $children;
}
/**
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
public function count(): int
{
return \count($this->getValue());
}
/**
* @return \Traversable
*/
#[\ReturnTypeWillChange]
public function getIterator()
public function getIterator(): \Traversable
{
if (!\is_array($value = $this->getValue())) {
throw new \LogicException(sprintf('"%s" object holds non-iterable type "%s".', self::class, get_debug_type($value)));
@@ -143,54 +132,32 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
return null;
}
/**
* @return bool
*/
public function __isset(string $key)
public function __isset(string $key): bool
{
return null !== $this->seek($key);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($key)
public function offsetExists(mixed $key): bool
{
return $this->__isset($key);
}
/**
* @return mixed
*/
#[\ReturnTypeWillChange]
public function offsetGet($key)
public function offsetGet(mixed $key): mixed
{
return $this->__get($key);
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function offsetSet($key, $value)
public function offsetSet(mixed $key, mixed $value): void
{
throw new \BadMethodCallException(self::class.' objects are immutable.');
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function offsetUnset($key)
public function offsetUnset(mixed $key): void
{
throw new \BadMethodCallException(self::class.' objects are immutable.');
}
/**
* @return string
*/
public function __toString()
public function __toString(): string
{
$value = $this->getValue();
@@ -203,10 +170,8 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
/**
* Returns a depth limited clone of $this.
*
* @return static
*/
public function withMaxDepth(int $maxDepth)
public function withMaxDepth(int $maxDepth): static
{
$data = clone $this;
$data->maxDepth = $maxDepth;
@@ -216,10 +181,8 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
/**
* Limits the number of elements per depth level.
*
* @return static
*/
public function withMaxItemsPerDepth(int $maxItemsPerDepth)
public function withMaxItemsPerDepth(int $maxItemsPerDepth): static
{
$data = clone $this;
$data->maxItemsPerDepth = $maxItemsPerDepth;
@@ -231,10 +194,8 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
* Enables/disables objects' identifiers tracking.
*
* @param bool $useRefHandles False to hide global ref. handles
*
* @return static
*/
public function withRefHandles(bool $useRefHandles)
public function withRefHandles(bool $useRefHandles): static
{
$data = clone $this;
$data->useRefHandles = $useRefHandles ? -1 : 0;
@@ -242,10 +203,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
return $data;
}
/**
* @return static
*/
public function withContext(array $context)
public function withContext(array $context): static
{
$data = clone $this;
$data->context = $context;
@@ -255,12 +213,8 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
/**
* Seeks to a specific key in nested data structures.
*
* @param string|int $key The key to seek to
*
* @return static|null
*/
public function seek($key)
public function seek(string|int $key): ?static
{
$item = $this->data[$this->position][$this->key];
@@ -326,7 +280,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, $item)
private function dumpItem(DumperInterface $dumper, Cursor $cursor, array &$refs, mixed $item)
{
$cursor->refIndex = 0;
$cursor->softRefTo = $cursor->softRefHandle = $cursor->softRefCount = 0;
@@ -448,7 +402,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate
return $hashCut;
}
private function getStub($item)
private function getStub(mixed $item)
{
if (!$item || !\is_array($item)) {
return $item;

View File

@@ -20,11 +20,8 @@ interface DumperInterface
{
/**
* Dumps a scalar value.
*
* @param string $type The PHP type of the value being dumped
* @param string|int|float|bool $value The scalar value being dumped
*/
public function dumpScalar(Cursor $cursor, string $type, $value);
public function dumpScalar(Cursor $cursor, string $type, string|int|float|bool|null $value);
/**
* Dumps a string.
@@ -38,19 +35,19 @@ interface DumperInterface
/**
* Dumps while entering an hash.
*
* @param int $type A Cursor::HASH_* const for the type of hash
* @param string|int $class The object class, resource type or array count
* @param bool $hasChild When the dump of the hash has child item
* @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
*/
public function enterHash(Cursor $cursor, int $type, $class, bool $hasChild);
public function enterHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild);
/**
* Dumps while leaving an hash.
*
* @param int $type A Cursor::HASH_* const for the type of hash
* @param string|int $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
* @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
* @param int $cut The number of items the hash has been cut by
*/
public function leaveHash(Cursor $cursor, int $type, $class, bool $hasChild, int $cut);
public function leaveHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild, int $cut);
}

View File

@@ -39,7 +39,7 @@ class Stub
public $position = 0;
public $attr = [];
private static $defaultProperties = [];
private static array $defaultProperties = [];
/**
* @internal

View File

@@ -16,13 +16,10 @@ namespace Symfony\Component\VarDumper\Cloner;
*/
class VarCloner extends AbstractCloner
{
private static $gid;
private static $arrayCache = [];
private static string $gid;
private static array $arrayCache = [];
/**
* {@inheritdoc}
*/
protected function doClone($var)
protected function doClone(mixed $var): array
{
$len = 1; // Length of $queue
$pos = 0; // Number of cloned items past the minimum depth
@@ -44,9 +41,7 @@ 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
if (!$gid = self::$gid) {
$gid = self::$gid = md5(random_bytes(6)); // Unique string used to detect the special $GLOBALS variable
}
$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;
@@ -65,22 +60,13 @@ class VarCloner extends AbstractCloner
foreach ($vals as $k => $v) {
// $v is the original value or a stub object in case of hard references
if (\PHP_VERSION_ID >= 70400) {
$zvalRef = ($r = \ReflectionReference::fromArrayElement($vals, $k)) ? $r->getId() : null;
} else {
$refs[$k] = $cookie;
$zvalRef = $vals[$k] === $cookie;
}
$zvalRef = ($r = \ReflectionReference::fromArrayElement($vals, $k)) ? $r->getId() : null;
if ($zvalRef) {
$vals[$k] = &$stub; // Break hard references to make $queue completely
unset($stub); // independent from the original structure
if (\PHP_VERSION_ID >= 70400 ? null !== $vals[$k] = $hardRefs[$zvalRef] ?? null : $v instanceof Stub && isset($hardRefs[spl_object_id($v)])) {
if (\PHP_VERSION_ID >= 70400) {
$v = $vals[$k];
} else {
$refs[$k] = $vals[$k] = $v;
}
if (null !== $vals[$k] = $hardRefs[$zvalRef] ?? null) {
$v = $vals[$k];
if ($v->value instanceof Stub && (Stub::TYPE_OBJECT === $v->value->type || Stub::TYPE_RESOURCE === $v->value->type)) {
++$v->value->refCount;
}
@@ -90,15 +76,7 @@ class VarCloner extends AbstractCloner
$vals[$k] = new Stub();
$vals[$k]->value = $v;
$vals[$k]->handle = ++$refsCounter;
if (\PHP_VERSION_ID >= 70400) {
$hardRefs[$zvalRef] = $vals[$k];
} else {
$refs[$k] = $vals[$k];
$h = spl_object_id($refs[$k]);
$hardRefs[$h] = &$refs[$k];
$values[$h] = $v;
}
$hardRefs[$zvalRef] = $vals[$k];
}
// Create $stub when the original value $v cannot be used directly
// If $v is a nested structure, put that structure in array $a
@@ -140,57 +118,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 && (\PHP_VERSION_ID < 70400 || !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;
if (\PHP_VERSION_ID >= 70400) {
$gv = &$a[$gk];
$hardRefs[\ReflectionReference::fromArrayElement($a, $gk)->getId()] = &$gv;
} else {
$gv = &$hardRefs[spl_object_id($v)];
}
$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);
@@ -274,10 +210,8 @@ class VarCloner extends AbstractCloner
if (!$zvalRef) {
$vals[$k] = $stub;
} elseif (\PHP_VERSION_ID >= 70400) {
$hardRefs[$zvalRef]->value = $stub;
} else {
$refs[$k]->value = $stub;
$hardRefs[$zvalRef]->value = $stub;
}
}

View File

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

View File

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

View File

@@ -11,6 +11,7 @@
namespace Symfony\Component\VarDumper\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Completion\CompletionInput;
use Symfony\Component\Console\Completion\CompletionSuggestions;
@@ -34,15 +35,13 @@ use Symfony\Component\VarDumper\Server\DumpServer;
*
* @final
*/
#[AsCommand(name: 'server:dump', description: 'Start a dump server that collects and displays dumps in a single place')]
class ServerDumpCommand extends Command
{
protected static $defaultName = 'server:dump';
protected static $defaultDescription = 'Start a dump server that collects and displays dumps in a single place';
private $server;
private DumpServer $server;
/** @var DumpDescriptorInterface[] */
private $descriptors;
private array $descriptors;
public function __construct(DumpServer $server, array $descriptors = [])
{
@@ -59,7 +58,6 @@ class ServerDumpCommand extends Command
{
$this
->addOption('format', null, InputOption::VALUE_REQUIRED, sprintf('The output format (%s)', implode(', ', $this->getAvailableFormats())), 'cli')
->setDescription(self::$defaultDescription)
->setHelp(<<<'EOF'
<info>%command.name%</info> starts a dump server that collects and displays
dumps in a single place for debugging you application:

View File

@@ -31,11 +31,11 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
protected $line = '';
protected $lineDumper;
protected $outputStream;
protected $decimalPoint; // This is locale dependent
protected $decimalPoint = '.';
protected $indentPad = ' ';
protected $flags;
private $charset = '';
private string $charset = '';
/**
* @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path, defaults to static::$defaultOutput
@@ -46,7 +46,6 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
{
$this->flags = $flags;
$this->setCharset($charset ?: \ini_get('php.output_encoding') ?: \ini_get('default_charset') ?: 'UTF-8');
$this->decimalPoint = \PHP_VERSION_ID >= 80000 ? '.' : localeconv()['decimal_point'];
$this->setOutput($output ?: static::$defaultOutput);
if (!$output && \is_string(static::$defaultOutput)) {
static::$defaultOutput = $this->outputStream;
@@ -72,7 +71,7 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
$output = fopen($output, 'w');
}
$this->outputStream = $output;
$this->lineDumper = [$this, 'echoLine'];
$this->lineDumper = $this->echoLine(...);
}
return $prev;
@@ -83,7 +82,7 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
*
* @return string The previous charset
*/
public function setCharset(string $charset)
public function setCharset(string $charset): string
{
$prev = $this->charset;
@@ -102,7 +101,7 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
*
* @return string The previous indent pad
*/
public function setIndentPad(string $pad)
public function setIndentPad(string $pad): string
{
$prev = $this->indentPad;
$this->indentPad = $pad;
@@ -117,10 +116,8 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
*
* @return string|null The dump as string when $output is true
*/
public function dump(Data $data, $output = null)
public function dump(Data $data, $output = null): ?string
{
$this->decimalPoint = \PHP_VERSION_ID >= 80000 ? '.' : localeconv()['decimal_point'];
if ($locale = $this->flags & (self::DUMP_COMMA_SEPARATOR | self::DUMP_TRAILING_COMMA) ? setlocale(\LC_NUMERIC, 0) : null) {
setlocale(\LC_NUMERIC, 'C');
}
@@ -177,10 +174,8 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface
/**
* Converts a non-UTF-8 string to UTF-8.
*
* @return string|null
*/
protected function utf8Encode(?string $s)
protected function utf8Encode(?string $s): ?string
{
if (null === $s || preg_match('//u', $s)) {
return $s;

View File

@@ -55,15 +55,12 @@ class CliDumper extends AbstractDumper
protected $collapseNextHash = false;
protected $expandNextHash = false;
private $displayOptions = [
private array $displayOptions = [
'fileLinkFormat' => null,
];
private $handlesHrefGracefully;
private bool $handlesHrefGracefully;
/**
* {@inheritdoc}
*/
public function __construct($output = null, string $charset = null, int $flags = 0)
{
parent::__construct($output, $charset, $flags);
@@ -122,10 +119,7 @@ class CliDumper extends AbstractDumper
$this->displayOptions = $displayOptions + $this->displayOptions;
}
/**
* {@inheritdoc}
*/
public function dumpScalar(Cursor $cursor, string $type, $value)
public function dumpScalar(Cursor $cursor, string $type, string|int|float|bool|null $value)
{
$this->dumpKey($cursor);
@@ -153,17 +147,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':
@@ -185,9 +174,6 @@ class CliDumper extends AbstractDumper
$this->endValue($cursor);
}
/**
* {@inheritdoc}
*/
public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut)
{
$this->dumpKey($cursor);
@@ -204,7 +190,7 @@ class CliDumper extends AbstractDumper
'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";
@@ -273,14 +259,9 @@ class CliDumper extends AbstractDumper
}
}
/**
* {@inheritdoc}
*/
public function enterHash(Cursor $cursor, int $type, $class, bool $hasChild)
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);
$attr = $cursor->attr;
@@ -314,10 +295,7 @@ class CliDumper extends AbstractDumper
}
}
/**
* {@inheritdoc}
*/
public function leaveHash(Cursor $cursor, int $type, $class, bool $hasChild, int $cut)
public function leaveHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild, int $cut)
{
if (empty($cursor->attr['cut_hash'])) {
$this->dumpEllipsis($cursor, $hasChild, $cut);
@@ -434,19 +412,13 @@ class CliDumper extends AbstractDumper
* @param string $style The type of style being applied
* @param string $value The value being styled
* @param array $attr Optional context information
*
* @return string
*/
protected function style(string $style, string $value, array $attr = [])
protected function style(string $style, string $value, array $attr = []): string
{
if (null === $this->colors) {
$this->colors = $this->supportsColors();
}
$this->colors ??= $this->supportsColors();
if (null === $this->handlesHrefGracefully) {
$this->handlesHrefGracefully = 'JetBrains-JediTerm' !== getenv('TERMINAL_EMULATOR')
&& (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100);
}
$this->handlesHrefGracefully ??= 'JetBrains-JediTerm' !== getenv('TERMINAL_EMULATOR')
&& (!getenv('KONSOLE_VERSION') || (int) getenv('KONSOLE_VERSION') > 201100);
if (isset($attr['ellipsis'], $attr['ellipsis-type'])) {
$prefix = substr($value, 0, -$attr['ellipsis']);
@@ -510,10 +482,7 @@ class CliDumper extends AbstractDumper
return $value;
}
/**
* @return bool
*/
protected function supportsColors()
protected function supportsColors(): bool
{
if ($this->outputStream !== static::$defaultOutput) {
return $this->hasColorSupport($this->outputStream);
@@ -552,9 +521,6 @@ class CliDumper extends AbstractDumper
return static::$defaultColors = $this->hasColorSupport($h);
}
/**
* {@inheritdoc}
*/
protected function dumpLine(int $depth, bool $endOfValue = false)
{
if ($this->colors) {
@@ -585,10 +551,8 @@ class CliDumper extends AbstractDumper
*
* Reference: Composer\XdebugHandler\Process::supportsColor
* https://github.com/composer/xdebug-handler
*
* @param mixed $stream A CLI output stream
*/
private function hasColorSupport($stream): bool
private function hasColorSupport(mixed $stream): bool
{
if (!\is_resource($stream) || 'stream' !== get_resource_type($stream)) {
return false;

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

@@ -25,10 +25,10 @@ use Twig\Template;
*/
final class SourceContextProvider implements ContextProviderInterface
{
private $limit;
private $charset;
private $projectDir;
private $fileLinkFormatter;
private int $limit;
private ?string $charset;
private ?string $projectDir;
private ?FileLinkFormatter $fileLinkFormatter;
public function __construct(string $charset = null, string $projectDir = null, FileLinkFormatter $fileLinkFormatter = null, int $limit = 9)
{

View File

@@ -19,8 +19,8 @@ use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface;
*/
class ContextualizedDumper implements DataDumperInterface
{
private $wrappedDumper;
private $contextProviders;
private DataDumperInterface $wrappedDumper;
private array $contextProviders;
/**
* @param ContextProviderInterface[] $contextProviders
@@ -35,7 +35,7 @@ class ContextualizedDumper implements DataDumperInterface
{
$context = [];
foreach ($this->contextProviders as $contextProvider) {
$context[\get_class($contextProvider)] = $contextProvider->getContext();
$context[$contextProvider::class] = $contextProvider->getContext();
}
$this->wrappedDumper->dump($data->withContext($context));

View File

@@ -67,16 +67,13 @@ class HtmlDumper extends CliDumper
protected $lastDepth = -1;
protected $styles;
private $displayOptions = [
private array $displayOptions = [
'maxDepth' => 1,
'maxStringLength' => 160,
'fileLinkFormat' => null,
];
private $extraDisplayOptions = [];
private array $extraDisplayOptions = [];
/**
* {@inheritdoc}
*/
public function __construct($output = null, string $charset = null, int $flags = 0)
{
AbstractDumper::__construct($output, $charset, $flags);
@@ -85,9 +82,6 @@ class HtmlDumper extends CliDumper
$this->styles = static::$themes['dark'] ?? self::$themes['dark'];
}
/**
* {@inheritdoc}
*/
public function setStyles(array $styles)
{
$this->headerIsDumped = false;
@@ -131,10 +125,7 @@ class HtmlDumper extends CliDumper
$this->dumpSuffix = $suffix;
}
/**
* {@inheritdoc}
*/
public function dump(Data $data, $output = null, array $extraDisplayOptions = [])
public function dump(Data $data, $output = null, array $extraDisplayOptions = []): ?string
{
$this->extraDisplayOptions = $extraDisplayOptions;
$result = parent::dump($data, $output);
@@ -782,9 +773,6 @@ EOHTML
return $this->dumpHeader = preg_replace('/\s+/', ' ', $line).'</style>'.$this->dumpHeader;
}
/**
* {@inheritdoc}
*/
public function dumpString(Cursor $cursor, string $str, bool $bin, int $cut)
{
if ('' === $str && isset($cursor->attr['img-data'], $cursor->attr['content-type'])) {
@@ -800,10 +788,7 @@ EOHTML
}
}
/**
* {@inheritdoc}
*/
public function enterHash(Cursor $cursor, int $type, $class, bool $hasChild)
public function enterHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild)
{
if (Cursor::HASH_OBJECT === $type) {
$cursor->attr['depth'] = $cursor->depth;
@@ -831,10 +816,7 @@ EOHTML
}
}
/**
* {@inheritdoc}
*/
public function leaveHash(Cursor $cursor, int $type, $class, bool $hasChild, int $cut)
public function leaveHash(Cursor $cursor, int $type, string|int|null $class, bool $hasChild, int $cut)
{
$this->dumpEllipsis($cursor, $hasChild, $cut);
if ($hasChild) {
@@ -843,10 +825,7 @@ EOHTML
parent::leaveHash($cursor, $type, $class, $hasChild, 0);
}
/**
* {@inheritdoc}
*/
protected function style(string $style, string $value, array $attr = [])
protected function style(string $style, string $value, array $attr = []): string
{
if ('' === $value) {
return '';
@@ -938,9 +917,6 @@ EOHTML
return $v;
}
/**
* {@inheritdoc}
*/
protected function dumpLine(int $depth, bool $endOfValue = false)
{
if (-1 === $this->lastDepth) {

View File

@@ -22,8 +22,8 @@ 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
@@ -41,9 +41,6 @@ class ServerDumper implements DataDumperInterface
return $this->connection->getContextProviders();
}
/**
* {@inheritdoc}
*/
public function dump(Data $data)
{
if (!$this->connection->write($data) && $this->wrappedDumper) {

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

@@ -15,7 +15,7 @@ if (!function_exists('dump')) {
/**
* @author Nicolas Grekas <p@tchwork.com>
*/
function dump($var, ...$moreVars)
function dump(mixed $var, mixed ...$moreVars): mixed
{
VarDumper::dump($var);
@@ -35,7 +35,7 @@ if (!function_exists('dd')) {
/**
* @return never
*/
function dd(...$vars)
function dd(...$vars): void
{
if (!in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && !headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');

View File

@@ -21,8 +21,8 @@ use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface;
*/
class Connection
{
private $host;
private $contextProviders;
private string $host;
private array $contextProviders;
/**
* @var resource|null

View File

@@ -24,8 +24,8 @@ use Symfony\Component\VarDumper\Cloner\Stub;
*/
class DumpServer
{
private $host;
private $logger;
private string $host;
private ?LoggerInterface $logger;
/**
* @var resource|null
@@ -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

@@ -22,7 +22,7 @@ trait VarDumperTestTrait
/**
* @internal
*/
private $varDumperConfig = [
private array $varDumperConfig = [
'casters' => [],
'flags' => null,
];
@@ -42,17 +42,17 @@ trait VarDumperTestTrait
$this->varDumperConfig['flags'] = null;
}
public function assertDumpEquals($expected, $data, int $filter = 0, string $message = '')
public function assertDumpEquals(mixed $expected, mixed $data, int $filter = 0, string $message = '')
{
$this->assertSame($this->prepareExpectation($expected, $filter), $this->getDump($data, null, $filter), $message);
}
public function assertDumpMatchesFormat($expected, $data, int $filter = 0, string $message = '')
public function assertDumpMatchesFormat(mixed $expected, mixed $data, int $filter = 0, string $message = '')
{
$this->assertStringMatchesFormat($this->prepareExpectation($expected, $filter), $this->getDump($data, null, $filter), $message);
}
protected function getDump($data, $key = null, int $filter = 0): ?string
protected function getDump(mixed $data, string|int $key = null, int $filter = 0): ?string
{
if (null === $flags = $this->varDumperConfig['flags']) {
$flags = getenv('DUMP_LIGHT_ARRAY') ? CliDumper::DUMP_LIGHT_ARRAY : 0;
@@ -73,7 +73,7 @@ trait VarDumperTestTrait
return rtrim($dumper->dump($data, true));
}
private function prepareExpectation($expected, int $filter): string
private function prepareExpectation(mixed $expected, int $filter): string
{
if (!\is_string($expected)) {
$expected = $this->getDump($expected, null, $filter);

View File

@@ -37,7 +37,7 @@ class VarDumper
*/
private static $handler;
public static function dump($var)
public static function dump(mixed $var)
{
if (null === self::$handler) {
self::register();
@@ -46,11 +46,11 @@ class VarDumper
return (self::$handler)($var);
}
/**
* @return callable|null
*/
public static function setHandler(callable $callable = null)
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:

View File

@@ -16,20 +16,19 @@
}
],
"require": {
"php": ">=7.2.5",
"symfony/polyfill-mbstring": "~1.0",
"symfony/polyfill-php80": "^1.16"
"php": ">=8.1",
"symfony/polyfill-mbstring": "~1.0"
},
"require-dev": {
"ext-iconv": "*",
"symfony/console": "^4.4|^5.0|^6.0",
"symfony/process": "^4.4|^5.0|^6.0",
"symfony/uid": "^5.1|^6.0",
"symfony/console": "^5.4|^6.0",
"symfony/process": "^5.4|^6.0",
"symfony/uid": "^5.4|^6.0",
"twig/twig": "^2.13|^3.0.4"
},
"conflict": {
"phpunit/phpunit": "<5.4.3",
"symfony/console": "<4.4"
"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).",