N°8910 - Upgrade Symfony packages

This commit is contained in:
Benjamin Dalsass
2026-02-19 09:18:56 +01:00
committed by GitHub
parent d5706fcbef
commit d2f67dcb3c
126 changed files with 1107 additions and 2067 deletions

View File

@@ -13,8 +13,8 @@ namespace Symfony\Component\VarExporter\Exception;
class ClassNotFoundException extends \Exception implements ExceptionInterface
{
public function __construct(string $class, \Throwable $previous = null)
public function __construct(string $class, ?\Throwable $previous = null)
{
parent::__construct(sprintf('Class "%s" not found.', $class), 0, $previous);
parent::__construct(\sprintf('Class "%s" not found.', $class), 0, $previous);
}
}

View File

@@ -13,8 +13,8 @@ namespace Symfony\Component\VarExporter\Exception;
class NotInstantiableTypeException extends \Exception implements ExceptionInterface
{
public function __construct(string $type, \Throwable $previous = null)
public function __construct(string $type, ?\Throwable $previous = null)
{
parent::__construct(sprintf('Type "%s" is not instantiable.', $type), 0, $previous);
parent::__construct(\sprintf('Type "%s" is not instantiable.', $type), 0, $previous);
}
}

View File

@@ -61,8 +61,8 @@ final class Hydrator
$propertyScopes = InternalHydrator::$propertyScopes[$class] ??= InternalHydrator::getPropertyScopes($class);
foreach ($properties as $name => &$value) {
[$scope, $name, $readonlyScope] = $propertyScopes[$name] ?? [$class, $name, $class];
$scopedProperties[$readonlyScope ?? $scope][$name] = &$value;
[$scope, $name, $writeScope] = $propertyScopes[$name] ?? [$class, $name, $class];
$scopedProperties[$writeScope ?? $scope][$name] = &$value;
}
unset($value);
}

View File

@@ -76,32 +76,23 @@ class Exporter
$class = $value::class;
$reflector = Registry::$reflectors[$class] ??= Registry::getClassReflector($class);
$properties = [];
$sleep = null;
$proto = Registry::$prototypes[$class];
if ($reflector->hasMethod('__serialize')) {
if (!$reflector->getMethod('__serialize')->isPublic()) {
throw new \Error(sprintf('Call to %s method "%s::__serialize()".', $reflector->getMethod('__serialize')->isProtected() ? 'protected' : 'private', $class));
throw new \Error(\sprintf('Call to %s method "%s::__serialize()".', $reflector->getMethod('__serialize')->isProtected() ? 'protected' : 'private', $class));
}
if (!\is_array($serializeProperties = $value->__serialize())) {
if (!\is_array($arrayValue = $value->__serialize())) {
throw new \TypeError($class.'::__serialize() must return an array');
}
if ($reflector->hasMethod('__unserialize')) {
$properties = $serializeProperties;
} else {
foreach ($serializeProperties as $n => $v) {
$c = $reflector->hasProperty($n) && ($p = $reflector->getProperty($n))->isReadOnly() ? $p->class : 'stdClass';
$properties[$c][$n] = $v;
}
$properties = $arrayValue;
goto prepare_value;
}
goto prepare_value;
}
$sleep = null;
$proto = Registry::$prototypes[$class];
if (($value instanceof \ArrayIterator || $value instanceof \ArrayObject) && null !== $proto) {
} elseif (($value instanceof \ArrayIterator || $value instanceof \ArrayObject) && null !== $proto) {
// ArrayIterator and ArrayObject need special care because their "flags"
// option changes the behavior of the (array) casting operator.
[$arrayValue, $properties] = self::getArrayObjectProperties($value, $proto);
@@ -117,10 +108,7 @@ class Exporter
}
$properties = ['SplObjectStorage' => ["\0" => $properties]];
$arrayValue = (array) $value;
} elseif ($value instanceof \Serializable
|| $value instanceof \__PHP_Incomplete_Class
|| \PHP_VERSION_ID < 80200 && $value instanceof \DatePeriod
) {
} elseif ($value instanceof \Serializable || $value instanceof \__PHP_Incomplete_Class || \PHP_VERSION_ID < 80200 && $value instanceof \DatePeriod) {
++$objectsCount;
$objectsPool[$value] = [$id = \count($objectsPool), serialize($value), [], 0];
$value = new Reference($id);
@@ -144,15 +132,15 @@ class Exporter
$i = 0;
$n = (string) $name;
if ('' === $n || "\0" !== $n[0]) {
$c = $reflector->hasProperty($n) && ($p = $reflector->getProperty($n))->isReadOnly() ? $p->class : 'stdClass';
$parent = $reflector;
do {
$p = $parent->hasProperty($n) ? $parent->getProperty($n) : null;
} while (!$p && $parent = $parent->getParentClass());
$c = $p && (!$p->isPublic() || (\PHP_VERSION_ID >= 80400 ? $p->isProtectedSet() || $p->isPrivateSet() : $p->isReadOnly())) ? $p->class : 'stdClass';
} elseif ('*' === $n[1]) {
$n = substr($n, 3);
$c = $reflector->getProperty($n)->class;
if ('Error' === $c) {
$c = 'TypeError';
} elseif ('Exception' === $c) {
$c = 'ErrorException';
}
} else {
$i = strpos($n, "\0", 2);
$c = substr($n, 1, $i - 1);
@@ -165,13 +153,19 @@ class Exporter
}
unset($sleep[$name], $sleep[$n]);
}
if (!\array_key_exists($name, $proto) || $proto[$name] !== $v || "\x00Error\x00trace" === $name || "\x00Exception\x00trace" === $name) {
if ("\x00Error\x00trace" === $name || "\x00Exception\x00trace" === $name) {
$properties[$c][$n] = $v;
} elseif (!\array_key_exists($name, $proto) || $proto[$name] !== $v) {
$properties[match ($c) {
'Error' => 'TypeError',
'Exception' => 'ErrorException',
default => $c,
}][$n] = $v;
}
}
if ($sleep) {
foreach ($sleep as $n => $v) {
trigger_error(sprintf('serialize(): "%s" returned as member variable from __sleep() but does not exist', $n), \E_USER_NOTICE);
trigger_error(\sprintf('serialize(): "%s" returned as member variable from __sleep() but does not exist', $n), \E_USER_NOTICE);
}
}
if (method_exists($class, '__unserialize')) {
@@ -224,10 +218,10 @@ class Exporter
$subIndent = $indent.' ';
if (\is_string($value)) {
$code = sprintf("'%s'", addcslashes($value, "'\\"));
$code = \sprintf("'%s'", addcslashes($value, "'\\"));
$code = preg_replace_callback("/((?:[\\0\\r\\n]|\u{202A}|\u{202B}|\u{202D}|\u{202E}|\u{2066}|\u{2067}|\u{2068}|\u{202C}|\u{2069})++)(.)/", function ($m) use ($subIndent) {
$m[1] = sprintf('\'."%s".\'', str_replace(
$m[1] = \sprintf('\'."%s".\'', str_replace(
["\0", "\r", "\n", "\u{202A}", "\u{202B}", "\u{202D}", "\u{202E}", "\u{2066}", "\u{2067}", "\u{2068}", "\u{202C}", "\u{2069}", '\n\\'],
['\0', '\r', '\n', '\u{202A}', '\u{202B}', '\u{202D}', '\u{202E}', '\u{2066}', '\u{2067}', '\u{2068}', '\u{202C}', '\u{2069}', '\n"'."\n".$subIndent.'."\\'],
$m[1]
@@ -285,7 +279,7 @@ class Exporter
return self::exportHydrator($value, $indent, $subIndent);
}
throw new \UnexpectedValueException(sprintf('Cannot export value of type "%s".', get_debug_type($value)));
throw new \UnexpectedValueException(\sprintf('Cannot export value of type "%s".', get_debug_type($value)));
}
private static function exportRegistry(Registry $value, string $indent, string $subIndent): string

View File

@@ -20,6 +20,9 @@ use Symfony\Component\VarExporter\Exception\ClassNotFoundException;
*/
class Hydrator
{
public const PROPERTY_HAS_HOOKS = 1;
public const PROPERTY_NOT_BY_REF = 2;
public static array $hydrators = [];
public static array $simpleHydrators = [];
public static array $propertyScopes = [];
@@ -70,11 +73,11 @@ class Hydrator
return $baseHydrator;
case 'ErrorException':
return $baseHydrator->bindTo(null, new class() extends \ErrorException {
return $baseHydrator->bindTo(null, new class extends \ErrorException {
});
case 'TypeError':
return $baseHydrator->bindTo(null, new class() extends \Error {
return $baseHydrator->bindTo(null, new class extends \Error {
});
case 'SplObjectStorage':
@@ -83,7 +86,7 @@ class Hydrator
if ("\0" === $name) {
foreach ($values as $i => $v) {
for ($j = 0; $j < \count($v); ++$j) {
$objects[$i]->attach($v[$j], $v[++$j]);
$objects[$i][$v[$j]] = $v[++$j];
}
}
continue;
@@ -156,13 +159,16 @@ class Hydrator
public static function getSimpleHydrator($class)
{
$baseHydrator = self::$simpleHydrators['stdClass'] ??= (function ($properties, $object) {
$readonly = (array) $this;
$notByRef = (array) $this;
foreach ($properties as $name => &$value) {
$object->$name = $value;
if (!($readonly[$name] ?? false)) {
if (!$noRef = $notByRef[$name] ?? false) {
$object->$name = $value;
$object->$name = &$value;
} elseif (true !== $noRef) {
$noRef($object, $value);
} else {
$object->$name = $value;
}
}
})->bindTo(new \stdClass());
@@ -172,11 +178,11 @@ class Hydrator
return $baseHydrator;
case 'ErrorException':
return $baseHydrator->bindTo(new \stdClass(), new class() extends \ErrorException {
return $baseHydrator->bindTo(new \stdClass(), new class extends \ErrorException {
});
case 'TypeError':
return $baseHydrator->bindTo(new \stdClass(), new class() extends \Error {
return $baseHydrator->bindTo(new \stdClass(), new class extends \Error {
});
case 'SplObjectStorage':
@@ -188,7 +194,7 @@ class Hydrator
continue;
}
for ($i = 0; $i < \count($value); ++$i) {
$object->attach($value[$i], $value[++$i]);
$object[$value[$i]] = $value[++$i];
}
}
};
@@ -217,14 +223,19 @@ class Hydrator
}
if (!$classReflector->isInternal()) {
$readonly = new \stdClass();
foreach ($classReflector->getProperties(\ReflectionProperty::IS_READONLY) as $propertyReflector) {
if ($class === $propertyReflector->class) {
$readonly->{$propertyReflector->name} = true;
$notByRef = new \stdClass();
foreach ($classReflector->getProperties() as $propertyReflector) {
if ($propertyReflector->isStatic()) {
continue;
}
if (\PHP_VERSION_ID >= 80400 && !$propertyReflector->isAbstract() && $propertyReflector->getHooks()) {
$notByRef->{$propertyReflector->name} = $propertyReflector->setRawValue(...);
} elseif ($propertyReflector->isReadOnly()) {
$notByRef->{$propertyReflector->name} = true;
}
}
return $baseHydrator->bindTo($readonly, $class);
return $baseHydrator->bindTo($notByRef, $class);
}
if ($classReflector->name !== $class) {
@@ -269,12 +280,23 @@ class Hydrator
continue;
}
$name = $property->name;
$access = ($flags << 2) | ($flags & \ReflectionProperty::IS_READONLY ? self::PROPERTY_NOT_BY_REF : 0);
if (\PHP_VERSION_ID >= 80400 && !$property->isAbstract() && $h = $property->getHooks()) {
$access |= self::PROPERTY_HAS_HOOKS | (isset($h['get']) && !$h['get']->returnsReference() ? self::PROPERTY_NOT_BY_REF : 0);
}
if (\ReflectionProperty::IS_PRIVATE & $flags) {
$propertyScopes["\0$class\0$name"] = $propertyScopes[$name] = [$class, $name, $flags & \ReflectionProperty::IS_READONLY ? $class : null, $property];
$propertyScopes["\0$class\0$name"] = $propertyScopes[$name] = [$class, $name, null, $access, $property];
continue;
}
$propertyScopes[$name] = [$class, $name, $flags & \ReflectionProperty::IS_READONLY ? $property->class : null, $property];
$propertyScopes[$name] = [$class, $name, null, $access, $property];
if ($flags & (\PHP_VERSION_ID >= 80400 ? \ReflectionProperty::IS_PRIVATE_SET : \ReflectionProperty::IS_READONLY)) {
$propertyScopes[$name][2] = $property->class;
}
if (\ReflectionProperty::IS_PROTECTED & $flags) {
$propertyScopes["\0*\0$name"] = $propertyScopes[$name];
@@ -285,12 +307,20 @@ class Hydrator
$class = $r->name;
foreach ($r->getProperties(\ReflectionProperty::IS_PRIVATE) as $property) {
if (!$property->isStatic()) {
$name = $property->name;
$readonlyScope = $property->isReadOnly() ? $class : null;
$propertyScopes["\0$class\0$name"] = [$class, $name, $readonlyScope, $property];
$propertyScopes[$name] ??= [$class, $name, $readonlyScope, $property];
$flags = $property->getModifiers();
if (\ReflectionProperty::IS_STATIC & $flags) {
continue;
}
$name = $property->name;
$access = ($flags << 2) | ($flags & \ReflectionProperty::IS_READONLY ? self::PROPERTY_NOT_BY_REF : 0);
if (\PHP_VERSION_ID >= 80400 && $h = $property->getHooks()) {
$access |= self::PROPERTY_HAS_HOOKS | (isset($h['get']) && !$h['get']->returnsReference() ? self::PROPERTY_NOT_BY_REF : 0);
}
$propertyScopes["\0$class\0$name"] = [$class, $name, null, $access, $property];
$propertyScopes[$name] ??= $propertyScopes["\0$class\0$name"];
}
}

View File

@@ -50,6 +50,7 @@ class LazyObjectRegistry
public static function getClassResetters($class)
{
$classProperties = [];
$hookedProperties = [];
if ((self::$classReflectors[$class] ??= new \ReflectionClass($class))->isInternal()) {
$propertyScopes = [];
@@ -57,11 +58,17 @@ class LazyObjectRegistry
$propertyScopes = Hydrator::$propertyScopes[$class] ??= Hydrator::getPropertyScopes($class);
}
foreach ($propertyScopes as $key => [$scope, $name, $readonlyScope]) {
foreach ($propertyScopes as $key => [$scope, $name, $writeScope, $access]) {
$propertyScopes[$k = "\0$scope\0$name"] ?? $propertyScopes[$k = "\0*\0$name"] ?? $k = $name;
if ($k === $key && "\0$class\0lazyObjectState" !== $k) {
$classProperties[$readonlyScope ?? $scope][$name] = $key;
if ($k !== $key || "\0$class\0lazyObjectState" === $k) {
continue;
}
if ($access & Hydrator::PROPERTY_HAS_HOOKS) {
$hookedProperties[$k] = true;
} else {
$classProperties[$writeScope ?? $scope][$name] = $key;
}
}
@@ -76,9 +83,13 @@ class LazyObjectRegistry
}, null, $scope);
}
$resetters[] = static function ($instance, $skippedProperties, $onlyProperties = null) {
$resetters[] = static function ($instance, $skippedProperties, $onlyProperties = null) use ($hookedProperties) {
foreach ((array) $instance as $name => $value) {
if ("\0" !== ($name[0] ?? '') && !\array_key_exists($name, $skippedProperties) && (null === $onlyProperties || \array_key_exists($name, $onlyProperties))) {
if ("\0" !== ($name[0] ?? '')
&& !\array_key_exists($name, $skippedProperties)
&& (null === $onlyProperties || \array_key_exists($name, $onlyProperties))
&& !isset($hookedProperties[$name])
) {
unset($instance->$name);
}
}
@@ -90,8 +101,8 @@ class LazyObjectRegistry
public static function getClassAccessors($class)
{
return \Closure::bind(static fn () => [
'get' => static function &($instance, $name, $readonly) {
if (!$readonly) {
'get' => static function &($instance, $name, $notByRef) {
if (!$notByRef) {
return $instance->$name;
}
$value = $instance->$name;
@@ -127,9 +138,9 @@ class LazyObjectRegistry
return $methods;
}
public static function getScope($propertyScopes, $class, $property, $readonlyScope = null)
public static function getScopeForRead($propertyScopes, $class, $property)
{
if (null === $readonlyScope && !isset($propertyScopes[$k = "\0$class\0$property"]) && !isset($propertyScopes[$k = "\0*\0$property"])) {
if (!isset($propertyScopes[$k = "\0$class\0$property"]) && !isset($propertyScopes[$k = "\0*\0$property"])) {
return null;
}
$frame = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2];
@@ -137,7 +148,27 @@ class LazyObjectRegistry
if (\ReflectionProperty::class === $scope = $frame['class'] ?? \Closure::class) {
$scope = $frame['object']->class;
}
if (null === $readonlyScope && '*' === $k[1] && ($class === $scope || (is_subclass_of($class, $scope) && !isset($propertyScopes["\0$scope\0$property"])))) {
if ('*' === $k[1] && ($class === $scope || (is_subclass_of($class, $scope) && !isset($propertyScopes["\0$scope\0$property"])))) {
return null;
}
return $scope;
}
public static function getScopeForWrite($propertyScopes, $class, $property, $flags)
{
if (!($flags & (\ReflectionProperty::IS_PRIVATE | \ReflectionProperty::IS_PROTECTED | \ReflectionProperty::IS_READONLY | (\PHP_VERSION_ID >= 80400 ? \ReflectionProperty::IS_PRIVATE_SET | \ReflectionProperty::IS_PROTECTED_SET : 0)))) {
return null;
}
$frame = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2];
if (\ReflectionProperty::class === $scope = $frame['class'] ?? \Closure::class) {
$scope = $frame['object']->class;
}
if ($flags & (\ReflectionProperty::IS_PRIVATE | (\PHP_VERSION_ID >= 80400 ? \ReflectionProperty::IS_PRIVATE_SET : \ReflectionProperty::IS_READONLY))) {
return $scope;
}
if ($flags & (\ReflectionProperty::IS_PROTECTED | (\PHP_VERSION_ID >= 80400 ? \ReflectionProperty::IS_PROTECTED_SET : 0)) && ($class === $scope || (is_subclass_of($class, $scope) && !isset($propertyScopes["\0$scope\0$property"])))) {
return null;
}

View File

@@ -45,7 +45,7 @@ class LazyObjectState
$this->status = \is_array($initializer) ? self::STATUS_UNINITIALIZED_PARTIAL : self::STATUS_UNINITIALIZED_FULL;
}
public function initialize($instance, $propertyName, $propertyScope)
public function initialize($instance, $propertyName, $writeScope)
{
if (self::STATUS_INITIALIZED_FULL === $this->status) {
return self::STATUS_INITIALIZED_FULL;
@@ -53,13 +53,13 @@ class LazyObjectState
if (\is_array($this->initializer)) {
$class = $instance::class;
$propertyScope ??= $class;
$writeScope ??= $class;
$propertyScopes = Hydrator::$propertyScopes[$class];
$propertyScopes[$k = "\0$propertyScope\0$propertyName"] ?? $propertyScopes[$k = "\0*\0$propertyName"] ?? $k = $propertyName;
$propertyScopes[$k = "\0$writeScope\0$propertyName"] ?? $propertyScopes[$k = "\0*\0$propertyName"] ?? $k = $propertyName;
if ($initializer = $this->initializer[$k] ?? null) {
$value = $initializer(...[$instance, $propertyName, $propertyScope, LazyObjectRegistry::$defaultProperties[$class][$k] ?? null]);
$accessor = LazyObjectRegistry::$classAccessors[$propertyScope] ??= LazyObjectRegistry::getClassAccessors($propertyScope);
$value = $initializer(...[$instance, $propertyName, $writeScope, LazyObjectRegistry::$defaultProperties[$class][$k] ?? null]);
$accessor = LazyObjectRegistry::$classAccessors[$writeScope] ??= LazyObjectRegistry::getClassAccessors($writeScope);
$accessor['set']($instance, $propertyName, $value);
return $this->status = self::STATUS_INITIALIZED_PARTIAL;
@@ -67,12 +67,12 @@ class LazyObjectState
if ($initializer = $this->initializer["\0"] ?? null) {
if (!\is_array($values = $initializer($instance, LazyObjectRegistry::$defaultProperties[$class]))) {
throw new \TypeError(sprintf('The lazy-initializer defined for instance of "%s" must return an array, got "%s".', $class, get_debug_type($values)));
throw new \TypeError(\sprintf('The lazy-initializer defined for instance of "%s" must return an array, got "%s".', $class, get_debug_type($values)));
}
$properties = (array) $instance;
foreach ($values as $key => $value) {
if (!\array_key_exists($key, $properties) && [$scope, $name, $readonlyScope] = $propertyScopes[$key] ?? null) {
$scope = $readonlyScope ?? ('*' !== $scope ? $scope : $class);
if (!\array_key_exists($key, $properties) && [$scope, $name, $writeScope] = $propertyScopes[$key] ?? null) {
$scope = $writeScope ?? $scope;
$accessor = LazyObjectRegistry::$classAccessors[$scope] ??= LazyObjectRegistry::getClassAccessors($scope);
$accessor['set']($instance, $name, $value);
@@ -116,10 +116,10 @@ class LazyObjectState
$properties = (array) $instance;
$onlyProperties = \is_array($this->initializer) ? $this->initializer : null;
foreach ($propertyScopes as $key => [$scope, $name, $readonlyScope]) {
foreach ($propertyScopes as $key => [$scope, $name, , $access]) {
$propertyScopes[$k = "\0$scope\0$name"] ?? $propertyScopes[$k = "\0*\0$name"] ?? $k = $name;
if ($k === $key && (null !== $readonlyScope || !\array_key_exists($k, $properties))) {
if ($k === $key && ($access & Hydrator::PROPERTY_HAS_HOOKS || ($access >> 2) & \ReflectionProperty::IS_READONLY || !\array_key_exists($k, $properties))) {
$skippedProperties[$k] = true;
}
}

View File

@@ -11,12 +11,15 @@
namespace Symfony\Component\VarExporter\Internal;
use Symfony\Component\Serializer\Attribute\Ignore;
if (\PHP_VERSION_ID >= 80300) {
/**
* @internal
*/
trait LazyObjectTrait
{
#[Ignore]
private readonly LazyObjectState $lazyObjectState;
}
} else {
@@ -25,6 +28,7 @@ if (\PHP_VERSION_ID >= 80300) {
*/
trait LazyObjectTrait
{
#[Ignore]
private LazyObjectState $lazyObjectState;
}
}

View File

@@ -11,6 +11,7 @@
namespace Symfony\Component\VarExporter;
use Symfony\Component\Serializer\Attribute\Ignore;
use Symfony\Component\VarExporter\Internal\Hydrator;
use Symfony\Component\VarExporter\Internal\LazyObjectRegistry as Registry;
use Symfony\Component\VarExporter\Internal\LazyObjectState;
@@ -31,7 +32,7 @@ trait LazyGhostTrait
* that the initializer doesn't initialize, if any
* @param static|null $instance
*/
public static function createLazyGhost(\Closure|array $initializer, array $skippedProperties = null, object $instance = null): static
public static function createLazyGhost(\Closure|array $initializer, ?array $skippedProperties = null, ?object $instance = null): static
{
if (\is_array($initializer)) {
trigger_deprecation('symfony/var-exporter', '6.4', 'Per-property lazy-initializers are deprecated and won\'t be supported anymore in 7.0, use an object initializer instead.');
@@ -61,6 +62,7 @@ trait LazyGhostTrait
*
* @param $partial Whether partially initialized objects should be considered as initialized
*/
#[Ignore]
public function isLazyObjectInitialized(bool $partial = false): bool
{
if (!$state = $this->lazyObjectState ?? null) {
@@ -111,14 +113,14 @@ trait LazyGhostTrait
$properties = (array) $this;
$propertyScopes = Hydrator::$propertyScopes[$class] ??= Hydrator::getPropertyScopes($class);
foreach ($state->initializer as $key => $initializer) {
if (\array_key_exists($key, $properties) || ![$scope, $name, $readonlyScope] = $propertyScopes[$key] ?? null) {
if (\array_key_exists($key, $properties) || ![$scope, $name, $writeScope] = $propertyScopes[$key] ?? null) {
continue;
}
$scope = $readonlyScope ?? ('*' !== $scope ? $scope : $class);
$scope = $writeScope ?? $scope;
if (null === $values) {
if (!\is_array($values = ($state->initializer["\0"])($this, Registry::$defaultProperties[$class]))) {
throw new \TypeError(sprintf('The lazy-initializer defined for instance of "%s" must return an array, got "%s".', $class, get_debug_type($values)));
throw new \TypeError(\sprintf('The lazy-initializer defined for instance of "%s" must return an array, got "%s".', $class, get_debug_type($values)));
}
if (\array_key_exists($key, $properties = (array) $this)) {
@@ -158,22 +160,28 @@ trait LazyGhostTrait
{
$propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
$scope = null;
$notByRef = 0;
if ([$class, , $readonlyScope] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScope($propertyScopes, $class, $name);
if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScopeForRead($propertyScopes, $class, $name);
$state = $this->lazyObjectState ?? null;
if ($state && (null === $scope || isset($propertyScopes["\0$scope\0$name"]))) {
$notByRef = $access & Hydrator::PROPERTY_NOT_BY_REF;
if (LazyObjectState::STATUS_INITIALIZED_FULL === $state->status) {
// Work around php/php-src#12695
$property = null === $scope ? $name : "\0$scope\0$name";
$property = $propertyScopes[$property][3]
?? Hydrator::$propertyScopes[$this::class][$property][3] = new \ReflectionProperty($scope ?? $class, $name);
$property = $propertyScopes[$property][4]
?? Hydrator::$propertyScopes[$this::class][$property][4] = new \ReflectionProperty($scope ?? $class, $name);
} else {
$property = null;
}
if (\PHP_VERSION_ID >= 80400 && !$notByRef && ($access >> 2) & \ReflectionProperty::IS_PRIVATE_SET) {
$scope ??= $writeScope;
}
if ($property?->isInitialized($this) ?? LazyObjectState::STATUS_UNINITIALIZED_PARTIAL !== $state->initialize($this, $name, $readonlyScope ?? $scope)) {
if ($property?->isInitialized($this) ?? LazyObjectState::STATUS_UNINITIALIZED_PARTIAL !== $state->initialize($this, $name, $writeScope ?? $scope)) {
goto get_in_scope;
}
}
@@ -190,14 +198,14 @@ trait LazyGhostTrait
if (null === $class) {
$frame = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
trigger_error(sprintf('Undefined property: %s::$%s in %s on line %s', $this::class, $name, $frame['file'], $frame['line']), \E_USER_NOTICE);
trigger_error(\sprintf('Undefined property: %s::$%s in %s on line %s', $this::class, $name, $frame['file'], $frame['line']), \E_USER_NOTICE);
}
get_in_scope:
try {
if (null === $scope) {
if (null === $readonlyScope) {
if (!$notByRef) {
return $this->$name;
}
$value = $this->$name;
@@ -206,7 +214,7 @@ trait LazyGhostTrait
}
$accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope);
return $accessor['get']($this, $name, null !== $readonlyScope);
return $accessor['get']($this, $name, $notByRef);
} catch (\Error $e) {
if (\Error::class !== $e::class || !str_starts_with($e->getMessage(), 'Cannot access uninitialized non-nullable property')) {
throw $e;
@@ -221,8 +229,12 @@ trait LazyGhostTrait
$accessor['set']($this, $name, []);
return $accessor['get']($this, $name, null !== $readonlyScope);
return $accessor['get']($this, $name, $notByRef);
} catch (\Error) {
if (preg_match('/^Cannot access uninitialized non-nullable property ([^ ]++) by reference$/', $e->getMessage(), $matches)) {
throw new \Error('Typed property '.$matches[1].' must not be accessed before initialization', $e->getCode(), $e->getPrevious());
}
throw $e;
}
}
@@ -233,15 +245,15 @@ trait LazyGhostTrait
$propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
$scope = null;
if ([$class, , $readonlyScope] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScope($propertyScopes, $class, $name, $readonlyScope);
if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScopeForWrite($propertyScopes, $class, $name, $access >> 2);
$state = $this->lazyObjectState ?? null;
if ($state && ($readonlyScope === $scope || isset($propertyScopes["\0$scope\0$name"]))
if ($state && ($writeScope === $scope || isset($propertyScopes["\0$scope\0$name"]))
&& LazyObjectState::STATUS_INITIALIZED_FULL !== $state->status
) {
if (LazyObjectState::STATUS_UNINITIALIZED_FULL === $state->status) {
$state->initialize($this, $name, $readonlyScope ?? $scope);
$state->initialize($this, $name, $writeScope ?? $scope);
}
goto set_in_scope;
}
@@ -268,13 +280,13 @@ trait LazyGhostTrait
$propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
$scope = null;
if ([$class, , $readonlyScope] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScope($propertyScopes, $class, $name);
if ([$class, , $writeScope] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScopeForRead($propertyScopes, $class, $name);
$state = $this->lazyObjectState ?? null;
if ($state && (null === $scope || isset($propertyScopes["\0$scope\0$name"]))
&& LazyObjectState::STATUS_INITIALIZED_FULL !== $state->status
&& LazyObjectState::STATUS_UNINITIALIZED_PARTIAL !== $state->initialize($this, $name, $readonlyScope ?? $scope)
&& LazyObjectState::STATUS_UNINITIALIZED_PARTIAL !== $state->initialize($this, $name, $writeScope ?? $scope)
) {
goto isset_in_scope;
}
@@ -299,15 +311,15 @@ trait LazyGhostTrait
$propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
$scope = null;
if ([$class, , $readonlyScope] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScope($propertyScopes, $class, $name, $readonlyScope);
if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScopeForWrite($propertyScopes, $class, $name, $access >> 2);
$state = $this->lazyObjectState ?? null;
if ($state && ($readonlyScope === $scope || isset($propertyScopes["\0$scope\0$name"]))
if ($state && ($writeScope === $scope || isset($propertyScopes["\0$scope\0$name"]))
&& LazyObjectState::STATUS_INITIALIZED_FULL !== $state->status
) {
if (LazyObjectState::STATUS_UNINITIALIZED_FULL === $state->status) {
$state->initialize($this, $name, $readonlyScope ?? $scope);
$state->initialize($this, $name, $writeScope ?? $scope);
}
goto unset_in_scope;
}
@@ -363,7 +375,7 @@ trait LazyGhostTrait
$value = $properties[$k = $name] ?? $properties[$k = "\0*\0$name"] ?? $properties[$k = "\0$class\0$name"] ?? $properties[$k = "\0$scope\0$name"] ?? $k = null;
if (null === $k) {
trigger_error(sprintf('serialize(): "%s" returned as member variable from __sleep() but does not exist', $name), \E_USER_NOTICE);
trigger_error(\sprintf('serialize(): "%s" returned as member variable from __sleep() but does not exist', $name), \E_USER_NOTICE);
} else {
$data[$k] = $value;
}
@@ -385,6 +397,7 @@ trait LazyGhostTrait
}
}
#[Ignore]
private function setLazyObjectAsInitialized(bool $initialized): void
{
$state = $this->lazyObjectState ?? null;

View File

@@ -11,6 +11,7 @@
namespace Symfony\Component\VarExporter;
use Symfony\Component\Serializer\Attribute\Ignore;
use Symfony\Component\VarExporter\Hydrator as PublicHydrator;
use Symfony\Component\VarExporter\Internal\Hydrator;
use Symfony\Component\VarExporter\Internal\LazyObjectRegistry as Registry;
@@ -27,7 +28,7 @@ trait LazyProxyTrait
* @param \Closure():object $initializer Returns the proxied object
* @param static|null $instance
*/
public static function createLazyProxy(\Closure $initializer, object $instance = null): static
public static function createLazyProxy(\Closure $initializer, ?object $instance = null): static
{
if (self::class !== $class = $instance ? $instance::class : static::class) {
$skippedProperties = ["\0".self::class."\0lazyObjectState" => true];
@@ -50,6 +51,7 @@ trait LazyProxyTrait
*
* @param $partial Whether partially initialized objects should be considered as initialized
*/
#[Ignore]
public function isLazyObjectInitialized(bool $partial = false): bool
{
return !isset($this->lazyObjectState) || isset($this->lazyObjectState->realInstance) || Registry::$noInitializerState === $this->lazyObjectState->initializer;
@@ -86,14 +88,19 @@ trait LazyProxyTrait
$propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
$scope = null;
$instance = $this;
$notByRef = 0;
if ([$class, , $readonlyScope] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScope($propertyScopes, $class, $name);
if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
$notByRef = $access & Hydrator::PROPERTY_NOT_BY_REF;
$scope = Registry::getScopeForRead($propertyScopes, $class, $name);
if (null === $scope || isset($propertyScopes["\0$scope\0$name"])) {
if ($state = $this->lazyObjectState ?? null) {
$instance = $state->realInstance ??= ($state->initializer)();
}
if (\PHP_VERSION_ID >= 80400 && !$notByRef && ($access >> 2) & \ReflectionProperty::IS_PRIVATE_SET) {
$scope ??= $writeScope;
}
$parent = 2;
goto get_in_scope;
}
@@ -113,14 +120,15 @@ trait LazyProxyTrait
if (!$parent && null === $class && !\array_key_exists($name, (array) $instance)) {
$frame = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
trigger_error(sprintf('Undefined property: %s::$%s in %s on line %s', $instance::class, $name, $frame['file'], $frame['line']), \E_USER_NOTICE);
trigger_error(\sprintf('Undefined property: %s::$%s in %s on line %s', $instance::class, $name, $frame['file'], $frame['line']), \E_USER_NOTICE);
}
get_in_scope:
$notByRef = $notByRef || 1 === $parent;
try {
if (null === $scope) {
if (null === $readonlyScope && 1 !== $parent) {
if (!$notByRef) {
return $instance->$name;
}
$value = $instance->$name;
@@ -129,7 +137,7 @@ trait LazyProxyTrait
}
$accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope);
return $accessor['get']($instance, $name, null !== $readonlyScope || 1 === $parent);
return $accessor['get']($instance, $name, $notByRef);
} catch (\Error $e) {
if (\Error::class !== $e::class || !str_starts_with($e->getMessage(), 'Cannot access uninitialized non-nullable property')) {
throw $e;
@@ -144,7 +152,7 @@ trait LazyProxyTrait
$accessor['set']($instance, $name, []);
return $accessor['get']($instance, $name, null !== $readonlyScope || 1 === $parent);
return $accessor['get']($instance, $name, $notByRef);
} catch (\Error) {
throw $e;
}
@@ -157,10 +165,10 @@ trait LazyProxyTrait
$scope = null;
$instance = $this;
if ([$class, , $readonlyScope] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScope($propertyScopes, $class, $name, $readonlyScope);
if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScopeForWrite($propertyScopes, $class, $name, $access >> 2);
if ($readonlyScope === $scope || isset($propertyScopes["\0$scope\0$name"])) {
if ($writeScope === $scope || isset($propertyScopes["\0$scope\0$name"])) {
if ($state = $this->lazyObjectState ?? null) {
$instance = $state->realInstance ??= ($state->initializer)();
}
@@ -193,7 +201,7 @@ trait LazyProxyTrait
$instance = $this;
if ([$class] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScope($propertyScopes, $class, $name);
$scope = Registry::getScopeForRead($propertyScopes, $class, $name);
if (null === $scope || isset($propertyScopes["\0$scope\0$name"])) {
if ($state = $this->lazyObjectState ?? null) {
@@ -225,10 +233,10 @@ trait LazyProxyTrait
$scope = null;
$instance = $this;
if ([$class, , $readonlyScope] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScope($propertyScopes, $class, $name, $readonlyScope);
if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
$scope = Registry::getScopeForWrite($propertyScopes, $class, $name, $access >> 2);
if ($readonlyScope === $scope || isset($propertyScopes["\0$scope\0$name"])) {
if ($writeScope === $scope || isset($propertyScopes["\0$scope\0$name"])) {
if ($state = $this->lazyObjectState ?? null) {
$instance = $state->realInstance ??= ($state->initializer)();
}
@@ -298,7 +306,7 @@ trait LazyProxyTrait
$value = $properties[$k = $name] ?? $properties[$k = "\0*\0$name"] ?? $properties[$k = "\0$class\0$name"] ?? $properties[$k = "\0$scope\0$name"] ?? $k = null;
if (null === $k) {
trigger_error(sprintf('serialize(): "%s" returned as member variable from __sleep() but does not exist', $name), \E_USER_NOTICE);
trigger_error(\sprintf('serialize(): "%s" returned as member variable from __sleep() but does not exist', $name), \E_USER_NOTICE);
} else {
$data[$k] = $value;
}

View File

@@ -28,19 +28,19 @@ final class ProxyHelper
public static function generateLazyGhost(\ReflectionClass $class): string
{
if (\PHP_VERSION_ID >= 80200 && \PHP_VERSION_ID < 80300 && $class->isReadOnly()) {
throw new LogicException(sprintf('Cannot generate lazy ghost: class "%s" is readonly.', $class->name));
throw new LogicException(\sprintf('Cannot generate lazy ghost with PHP < 8.3: class "%s" is readonly.', $class->name));
}
if ($class->isFinal()) {
throw new LogicException(sprintf('Cannot generate lazy ghost: class "%s" is final.', $class->name));
throw new LogicException(\sprintf('Cannot generate lazy ghost: class "%s" is final.', $class->name));
}
if ($class->isInterface() || $class->isAbstract()) {
throw new LogicException(sprintf('Cannot generate lazy ghost: "%s" is not a concrete class.', $class->name));
if ($class->isInterface() || $class->isAbstract() || $class->isTrait()) {
throw new LogicException(\sprintf('Cannot generate lazy ghost: "%s" is not a concrete class.', $class->name));
}
if (\stdClass::class !== $class->name && $class->isInternal()) {
throw new LogicException(sprintf('Cannot generate lazy ghost: class "%s" is internal.', $class->name));
throw new LogicException(\sprintf('Cannot generate lazy ghost: class "%s" is internal.', $class->name));
}
if ($class->hasMethod('__get') && 'mixed' !== (self::exportType($class->getMethod('__get')) ?? 'mixed')) {
throw new LogicException(sprintf('Cannot generate lazy ghost: return type of method "%s::__get()" should be "mixed".', $class->name));
throw new LogicException(\sprintf('Cannot generate lazy ghost: return type of method "%s::__get()" should be "mixed".', $class->name));
}
static $traitMethods;
@@ -48,17 +48,58 @@ final class ProxyHelper
foreach ($traitMethods as $method) {
if ($class->hasMethod($method->name) && $class->getMethod($method->name)->isFinal()) {
throw new LogicException(sprintf('Cannot generate lazy ghost: method "%s::%s()" is final.', $class->name, $method->name));
throw new LogicException(\sprintf('Cannot generate lazy ghost: method "%s::%s()" is final.', $class->name, $method->name));
}
}
$parent = $class;
while ($parent = $parent->getParentClass()) {
if (\stdClass::class !== $parent->name && $parent->isInternal()) {
throw new LogicException(sprintf('Cannot generate lazy ghost: class "%s" extends "%s" which is internal.', $class->name, $parent->name));
throw new LogicException(\sprintf('Cannot generate lazy ghost: class "%s" extends "%s" which is internal.', $class->name, $parent->name));
}
}
$propertyScopes = self::exportPropertyScopes($class->name);
$hooks = '';
$propertyScopes = Hydrator::$propertyScopes[$class->name] ??= Hydrator::getPropertyScopes($class->name);
foreach ($propertyScopes as $key => [$scope, $name, , $access]) {
$propertyScopes[$k = "\0$scope\0$name"] ?? $propertyScopes[$k = "\0*\0$name"] ?? $k = $name;
$flags = $access >> 2;
if ($k !== $key || !($access & Hydrator::PROPERTY_HAS_HOOKS) || $flags & \ReflectionProperty::IS_VIRTUAL) {
continue;
}
if ($flags & (\ReflectionProperty::IS_FINAL | \ReflectionProperty::IS_PRIVATE)) {
throw new LogicException(\sprintf('Cannot generate lazy ghost: property "%s::$%s" is final or private(set).', $class->name, $name));
}
$p = $propertyScopes[$k][4] ?? Hydrator::$propertyScopes[$class->name][$k][4] = new \ReflectionProperty($scope, $name);
$type = self::exportType($p);
$hooks .= "\n "
.($p->isProtected() ? 'protected' : 'public')
.($p->isProtectedSet() ? ' protected(set)' : '')
." {$type} \${$name}"
.($p->hasDefaultValue() ? ' = '.VarExporter::export($p->getDefaultValue()) : '')
." {\n";
foreach ($p->getHooks() as $hook => $method) {
if ('get' === $hook) {
$ref = ($method->returnsReference() ? '&' : '');
$hooks .= " {$ref}get { \$this->initializeLazyObject(); return parent::\${$name}::get(); }\n";
} elseif ('set' === $hook) {
$parameters = self::exportParameters($method, true);
$arg = '$'.$method->getParameters()[0]->name;
$hooks .= " set({$parameters}) { \$this->initializeLazyObject(); parent::\${$name}::set({$arg}); }\n";
} else {
throw new LogicException(\sprintf('Cannot generate lazy ghost: hook "%s::%s()" is not supported.', $class->name, $method->name));
}
}
$hooks .= " }\n";
}
$propertyScopes = self::exportPropertyScopes($class->name, $propertyScopes);
return <<<EOPHP
extends \\{$class->name} implements \Symfony\Component\VarExporter\LazyObjectInterface
@@ -66,7 +107,7 @@ final class ProxyHelper
use \Symfony\Component\VarExporter\LazyGhostTrait;
private const LAZY_OBJECT_PROPERTY_SCOPES = {$propertyScopes};
}
{$hooks}}
// Help opcache.preload discover always-needed symbols
class_exists(\Symfony\Component\VarExporter\Internal\Hydrator::class);
@@ -86,23 +127,113 @@ final class ProxyHelper
public static function generateLazyProxy(?\ReflectionClass $class, array $interfaces = []): string
{
if (!class_exists($class?->name ?? \stdClass::class, false)) {
throw new LogicException(sprintf('Cannot generate lazy proxy: "%s" is not a class.', $class->name));
throw new LogicException(\sprintf('Cannot generate lazy proxy: "%s" is not a class.', $class->name));
}
if ($class?->isFinal()) {
throw new LogicException(sprintf('Cannot generate lazy proxy: class "%s" is final.', $class->name));
throw new LogicException(\sprintf('Cannot generate lazy proxy: class "%s" is final.', $class->name));
}
if (\PHP_VERSION_ID >= 80200 && \PHP_VERSION_ID < 80300 && $class?->isReadOnly()) {
throw new LogicException(sprintf('Cannot generate lazy proxy: class "%s" is readonly.', $class->name));
throw new LogicException(\sprintf('Cannot generate lazy proxy with PHP < 8.3: class "%s" is readonly.', $class->name));
}
$propertyScopes = $class ? Hydrator::$propertyScopes[$class->name] ??= Hydrator::getPropertyScopes($class->name) : [];
$abstractProperties = [];
$hookedProperties = [];
if (\PHP_VERSION_ID >= 80400 && $class) {
foreach ($propertyScopes as $key => [$scope, $name, , $access]) {
$propertyScopes[$k = "\0$scope\0$name"] ?? $propertyScopes[$k = "\0*\0$name"] ?? $k = $name;
$flags = $access >> 2;
if ($k !== $key) {
continue;
}
if ($flags & \ReflectionProperty::IS_ABSTRACT) {
$abstractProperties[$name] = $propertyScopes[$k][4] ?? Hydrator::$propertyScopes[$class->name][$k][4] = new \ReflectionProperty($scope, $name);
continue;
}
$abstractProperties[$name] = false;
if (!($access & Hydrator::PROPERTY_HAS_HOOKS) || $flags & \ReflectionProperty::IS_VIRTUAL) {
continue;
}
if ($flags & (\ReflectionProperty::IS_FINAL | \ReflectionProperty::IS_PRIVATE)) {
throw new LogicException(\sprintf('Cannot generate lazy proxy: property "%s::$%s" is final or private(set).', $class->name, $name));
}
$p = $propertyScopes[$k][4] ?? Hydrator::$propertyScopes[$class->name][$k][4] = new \ReflectionProperty($scope, $name);
$hookedProperties[$name] = [$p, $p->getHooks()];
}
}
$methodReflectors = [$class?->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) ?? []];
foreach ($interfaces as $interface) {
if (!$interface->isInterface()) {
throw new LogicException(sprintf('Cannot generate lazy proxy: "%s" is not an interface.', $interface->name));
throw new LogicException(\sprintf('Cannot generate lazy proxy: "%s" is not an interface.', $interface->name));
}
$methodReflectors[] = $interface->getMethods();
if (\PHP_VERSION_ID >= 80400) {
foreach ($interface->getProperties() as $p) {
$abstractProperties[$p->name] ??= $p;
$hookedProperties[$p->name] ??= [$p, []];
$hookedProperties[$p->name][1] += $p->getHooks();
}
}
}
$hooks = '';
foreach (array_filter($abstractProperties) as $name => $p) {
$type = self::exportType($p);
$hooks .= "\n "
.($p->isProtected() ? 'protected' : 'public')
.($p->isProtectedSet() ? ' protected(set)' : '')
." {$type} \${$name};\n";
}
foreach ($hookedProperties as $name => [$p, $methods]) {
$type = self::exportType($p);
$hooks .= "\n "
.($p->isProtected() ? 'protected' : 'public')
.($p->isProtectedSet() ? ' protected(set)' : '')
." {$type} \${$name} {\n";
foreach ($methods as $hook => $method) {
if ('get' === $hook) {
$ref = ($method->returnsReference() ? '&' : '');
$hooks .= <<<EOPHP
{$ref}get {
if (isset(\$this->lazyObjectState)) {
return (\$this->lazyObjectState->realInstance ??= (\$this->lazyObjectState->initializer)())->{$p->name};
}
return parent::\${$p->name}::get();
}
EOPHP;
} elseif ('set' === $hook) {
$parameters = self::exportParameters($method, true);
$arg = '$'.$method->getParameters()[0]->name;
$hooks .= <<<EOPHP
set({$parameters}) {
if (isset(\$this->lazyObjectState)) {
\$this->lazyObjectState->realInstance ??= (\$this->lazyObjectState->initializer)();
\$this->lazyObjectState->realInstance->{$p->name} = {$arg};
}
parent::\${$p->name}::set({$arg});
}
EOPHP;
} else {
throw new LogicException(\sprintf('Cannot generate lazy proxy: hook "%s::%s()" is not supported.', $class->name, $method->name));
}
}
$hooks .= " }\n";
}
$methodReflectors = array_merge(...$methodReflectors);
$extendsInternalClass = false;
if ($parent = $class) {
@@ -112,6 +243,7 @@ final class ProxyHelper
}
$methodsHaveToBeProxied = $extendsInternalClass;
$methods = [];
$methodReflectors = array_merge(...$methodReflectors);
foreach ($methodReflectors as $method) {
if ('__get' !== strtolower($method->name) || 'mixed' === ($type = self::exportType($method) ?? 'mixed')) {
@@ -134,7 +266,7 @@ final class ProxyHelper
}
if ($method->isFinal()) {
if ($extendsInternalClass || $methodsHaveToBeProxied || method_exists(LazyProxyTrait::class, $method->name)) {
throw new LogicException(sprintf('Cannot generate lazy proxy: method "%s::%s()" is final.', $class->name, $method->name));
throw new LogicException(\sprintf('Cannot generate lazy proxy: method "%s::%s()" is final.', $class->name, $method->name));
}
continue;
}
@@ -195,15 +327,40 @@ final class ProxyHelper
$methods = ['initializeLazyObject' => implode('', $body).' }'] + $methods;
}
$body = $methods ? "\n".implode("\n\n", $methods)."\n" : '';
$propertyScopes = $class ? self::exportPropertyScopes($class->name) : '[]';
$propertyScopes = $class ? self::exportPropertyScopes($class->name, $propertyScopes) : '[]';
if (
$class?->hasMethod('__unserialize')
&& !$class->getMethod('__unserialize')->getParameters()[0]->getType()
) {
// fix contravariance type problem when $class declares a `__unserialize()` method without typehint.
$lazyProxyTraitStatement = <<<EOPHP
use \Symfony\Component\VarExporter\LazyProxyTrait {
__unserialize as private __doUnserialize;
}
EOPHP;
$body .= <<<EOPHP
public function __unserialize(\$data): void
{
\$this->__doUnserialize(\$data);
}
EOPHP;
} else {
$lazyProxyTraitStatement = <<<EOPHP
use \Symfony\Component\VarExporter\LazyProxyTrait;
EOPHP;
}
return <<<EOPHP
{$parent} implements \\{$interfaces}
{
use \Symfony\Component\VarExporter\LazyProxyTrait;
{$lazyProxyTraitStatement}
private const LAZY_OBJECT_PROPERTY_SCOPES = {$propertyScopes};
{$body}}
{$hooks}{$body}}
// Help opcache.preload discover always-needed symbols
class_exists(\Symfony\Component\VarExporter\Internal\Hydrator::class);
@@ -213,18 +370,20 @@ final class ProxyHelper
EOPHP;
}
public static function exportSignature(\ReflectionFunctionAbstract $function, bool $withParameterTypes = true, string &$args = null): string
public static function exportParameters(\ReflectionFunctionAbstract $function, bool $withParameterTypes = true, ?string &$args = null): string
{
$byRefIndex = 0;
$args = '';
$param = null;
$parameters = [];
$namespace = $function instanceof \ReflectionMethod ? $function->class : $function->getNamespaceName().'\\';
$namespace = substr($namespace, 0, strrpos($namespace, '\\') ?: 0);
foreach ($function->getParameters() as $param) {
$parameters[] = ($param->getAttributes(\SensitiveParameter::class) ? '#[\SensitiveParameter] ' : '')
.($withParameterTypes && $param->hasType() ? self::exportType($param).' ' : '')
.($param->isPassedByReference() ? '&' : '')
.($param->isVariadic() ? '...' : '').'$'.$param->name
.($param->isOptional() && !$param->isVariadic() ? ' = '.self::exportDefault($param) : '');
.($param->isOptional() && !$param->isVariadic() ? ' = '.self::exportDefault($param, $namespace) : '');
if ($param->isPassedByReference()) {
$byRefIndex = 1 + $param->getPosition();
}
@@ -237,12 +396,19 @@ final class ProxyHelper
$args = substr($args, 0, -2);
} else {
$args = explode(', ', $args, 1 + $byRefIndex);
$args[$byRefIndex] = sprintf('...\array_slice(\func_get_args(), %d)', $byRefIndex);
$args[$byRefIndex] = \sprintf('...\array_slice(\func_get_args(), %d)', $byRefIndex);
$args = implode(', ', $args);
}
return implode(', ', $parameters);
}
public static function exportSignature(\ReflectionFunctionAbstract $function, bool $withParameterTypes = true, ?string &$args = null): string
{
$parameters = self::exportParameters($function, $withParameterTypes, $args);
$signature = 'function '.($function->returnsReference() ? '&' : '')
.($function->isClosure() ? '' : $function->name).'('.implode(', ', $parameters).')';
.($function->isClosure() ? '' : $function->name).'('.$parameters.')';
if ($function instanceof \ReflectionMethod) {
$signature = ($function->isPublic() ? 'public ' : ($function->isProtected() ? 'protected ' : 'private '))
@@ -270,7 +436,7 @@ final class ProxyHelper
return $signature;
}
public static function exportType(\ReflectionFunctionAbstract|\ReflectionProperty|\ReflectionParameter $owner, bool $noBuiltin = false, \ReflectionType $type = null): ?string
public static function exportType(\ReflectionFunctionAbstract|\ReflectionProperty|\ReflectionParameter $owner, bool $noBuiltin = false, ?\ReflectionType $type = null): ?string
{
if (!$type ??= $owner instanceof \ReflectionFunctionAbstract ? $owner->getReturnType() : $owner->getType()) {
return null;
@@ -311,19 +477,20 @@ final class ProxyHelper
return '';
}
if (null === $glue) {
return (!$noBuiltin && $type->allowsNull() && 'mixed' !== $name ? '?' : '').$types[0];
$defaultNull = $owner instanceof \ReflectionParameter && 'NULL' === rtrim(substr(explode('$'.$owner->name.' = ', (string) $owner, 2)[1] ?? '', 0, -2));
return (!$noBuiltin && ($type->allowsNull() || $defaultNull) && !\in_array($name, ['mixed', 'null'], true) ? '?' : '').$types[0];
}
sort($types);
return implode($glue, $types);
}
private static function exportPropertyScopes(string $parent): string
private static function exportPropertyScopes(string $parent, array $propertyScopes): string
{
$propertyScopes = Hydrator::$propertyScopes[$parent] ??= Hydrator::getPropertyScopes($parent);
uksort($propertyScopes, 'strnatcmp');
foreach ($propertyScopes as $k => $v) {
unset($propertyScopes[$k][3]);
unset($propertyScopes[$k][4]);
}
$propertyScopes = VarExporter::export($propertyScopes);
$propertyScopes = str_replace(VarExporter::export($parent), 'parent::class', $propertyScopes);
@@ -333,7 +500,7 @@ final class ProxyHelper
return $propertyScopes;
}
private static function exportDefault(\ReflectionParameter $param): string
private static function exportDefault(\ReflectionParameter $param, $namespace): string
{
$default = rtrim(substr(explode('$'.$param->name.' = ', (string) $param, 2)[1] ?? '', 0, -2));
@@ -347,7 +514,7 @@ final class ProxyHelper
$regexp = "/(\"(?:[^\"\\\\]*+(?:\\\\.)*+)*+\"|'(?:[^'\\\\]*+(?:\\\\.)*+)*+')/";
$parts = preg_split($regexp, $default, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY);
$regexp = '/([\[\( ]|^)([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z0-9_\x7f-\xff]++)*+)(?!: )/';
$regexp = '/([\[\( ]|^)([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z0-9_\x7f-\xff]++)*+)(\(?)(?!: )/';
$callback = (false !== strpbrk($default, "\\:('") && $class = $param->getDeclaringClass())
? fn ($m) => $m[1].match ($m[2]) {
'new', 'false', 'true', 'null' => $m[2],
@@ -355,13 +522,13 @@ final class ProxyHelper
'self' => '\\'.$class->name,
'namespace\\parent',
'parent' => ($parent = $class->getParentClass()) ? '\\'.$parent->name : 'parent',
default => '\\'.$m[2],
}
default => self::exportSymbol($m[2], '(' !== $m[3], $namespace),
}.$m[3]
: fn ($m) => $m[1].match ($m[2]) {
'new', 'false', 'true', 'null', 'self', 'parent' => $m[2],
'NULL' => 'null',
default => '\\'.$m[2],
};
default => self::exportSymbol($m[2], '(' !== $m[3], $namespace),
}.$m[3];
return implode('', array_map(fn ($part) => match ($part[0]) {
'"' => $part, // for internal classes only
@@ -369,4 +536,18 @@ final class ProxyHelper
default => preg_replace_callback($regexp, $callback, $part),
}, $parts));
}
private static function exportSymbol(string $symbol, bool $mightBeRootConst, string $namespace): string
{
if (!$mightBeRootConst
|| false === ($ns = strrpos($symbol, '\\'))
|| substr($symbol, 0, $ns) !== $namespace
|| \defined($symbol)
|| !\defined(substr($symbol, $ns + 1))
) {
return '\\'.$symbol;
}
return '\\'.substr($symbol, $ns + 1);
}
}

View File

@@ -37,7 +37,7 @@ final class VarExporter
*
* @throws ExceptionInterface When the provided value cannot be serialized
*/
public static function export(mixed $value, bool &$isStaticValue = null, array &$foundClasses = []): string
public static function export(mixed $value, ?bool &$isStaticValue = null, array &$foundClasses = []): string
{
$isStaticValue = true;

View File

@@ -20,6 +20,8 @@
"symfony/deprecation-contracts": "^2.5|^3"
},
"require-dev": {
"symfony/property-access": "^6.4|^7.0",
"symfony/serializer": "^6.4|^7.0",
"symfony/var-dumper": "^5.4|^6.0|^7.0"
},
"autoload": {