Skip to content

[Serializer] fix support for lazy/unset properties #44295

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/Symfony/Component/PropertyAccess/PropertyAccessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ private function readProperty(array $zval, string $property, bool $ignoreInvalid

$result = self::RESULT_PROTO;
$object = $zval[self::VALUE];
$class = \get_class($object);
$access = $this->getReadAccessInfo(\get_class($object), $property);

try {
Expand All @@ -406,6 +407,11 @@ private function readProperty(array $zval, string $property, bool $ignoreInvalid
throw $e;
}
} elseif (self::ACCESS_TYPE_PROPERTY === $access[self::ACCESS_TYPE]) {
$name = $access[self::ACCESS_NAME];
if (!method_exists($object, '__get') && !isset($object->$name) && !\array_key_exists($name, (array) $object) && (\PHP_VERSION_ID < 70400 || !(new \ReflectionProperty($class, $name))->hasType())) {
throw new AccessException(sprintf('The property "%s::$%s" is not initialized.', $class, $name));
}

$result[self::VALUE] = $object->{$access[self::ACCESS_NAME]};

if ($access[self::ACCESS_REF] && isset($zval[self::REF])) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\Serializer\Normalizer;

use Symfony\Component\PropertyAccess\Exception\AccessException;
use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException;
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
Expand Down Expand Up @@ -181,7 +182,23 @@ public function normalize($object, $format = null, array $context = [])
continue;
}

$attributeValue = $this->getAttributeValue($object, $attribute, $format, $context);
try {
$attributeValue = $this->getAttributeValue($object, $attribute, $format, $context);
} catch (AccessException $e) {
if (sprintf('The property "%s::$%s" is not initialized.', \get_class($object), $attribute) === $e->getMessage()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rather than detecting the error message (which could easily be broken if we reword the message, especially as there is no tests covering this), shouldn't we use a subclass of the AccessException instead ?
The rule until now is that the exception messages are not covered by any BC rules and should not be relied upon to catch exceptions.
And this is a cross-component dependency, which would require actually changing the BC rules to allow the current pattern

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes I agree, that's what we've done on 5.3 already, but introducing a new class in 4.4 doesn't look like a good idea to me...

continue;
}
if (($p = $e->getPrevious()) && 'Error' === \get_class($p) && $this->isUninitializedValueError($p)) {
continue;
}
throw $e;
} catch (\Error $e) {
if ($this->isUninitializedValueError($e)) {
continue;
}
throw $e;
}

if ($maxDepthReached) {
$attributeValue = $maxDepthHandler($attributeValue, $object, $attribute, $format, $context);
}
Expand Down Expand Up @@ -637,4 +654,15 @@ private function getCacheKey(?string $format, array $context)
return false;
}
}

/**
* This error may occur when specific object normalizer implementation gets attribute value
* by accessing a public uninitialized property or by calling a method accessing such property.
*/
private function isUninitializedValueError(\Error $e): bool
{
return \PHP_VERSION_ID >= 70400
&& str_starts_with($e->getMessage(), 'Typed property')
&& str_ends_with($e->getMessage(), 'must not be accessed before initialization');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,16 +104,8 @@ protected function extractAttributes($object, $format = null, array $context = [
}

// properties
$propertyValues = !method_exists($object, '__get') ? (array) $object : null;
foreach ($reflClass->getProperties() as $reflProperty) {
if (null !== $propertyValues && !\array_key_exists($reflProperty->name, $propertyValues)) {
if ($reflProperty->isPublic()
|| ($reflProperty->isProtected() && !\array_key_exists("\0*\0{$reflProperty->name}", $propertyValues))
|| ($reflProperty->isPrivate() && !\array_key_exists("\0{$reflProperty->class}\0{$reflProperty->name}", $propertyValues))
) {
unset($attributes[$reflProperty->name]);
}

if (!$reflProperty->isPublic()) {
continue;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\Component\Serializer\Normalizer;

use Symfony\Component\PropertyAccess\Exception\AccessException;

/**
* Converts between objects and arrays by mapping properties.
*
Expand Down Expand Up @@ -101,17 +103,10 @@ protected function extractAttributes($object, $format = null, array $context = [
{
$reflectionObject = new \ReflectionObject($object);
$attributes = [];
$propertyValues = !method_exists($object, '__get') ? (array) $object : null;

do {
foreach ($reflectionObject->getProperties() as $property) {
if ((null !== $propertyValues && (
($property->isPublic() && !\array_key_exists($property->name, $propertyValues))
|| ($property->isProtected() && !\array_key_exists("\0*\0{$property->name}", $propertyValues))
|| ($property->isPrivate() && !\array_key_exists("\0{$property->class}\0{$property->name}", $propertyValues))
))
|| !$this->isAllowedAttribute($reflectionObject->getName(), $property->name, $format, $context)
) {
if (!$this->isAllowedAttribute($reflectionObject->getName(), $property->name, $format, $context)) {
continue;
}

Expand All @@ -138,6 +133,21 @@ protected function getAttributeValue($object, $attribute, $format = null, array
$reflectionProperty->setAccessible(true);
}

if (\PHP_VERSION_ID >= 70400 && $reflectionProperty->hasType()) {
return $reflectionProperty->getValue($object);
}

if (!method_exists($object, '__get') && !isset($object->$attribute)) {
$propertyValues = (array) $object;

if (($reflectionProperty->isPublic() && !\array_key_exists($reflectionProperty->name, $propertyValues))
|| ($reflectionProperty->isProtected() && !\array_key_exists("\0*\0{$reflectionProperty->name}", $propertyValues))
|| ($reflectionProperty->isPrivate() && !\array_key_exists("\0{$reflectionProperty->class}\0{$reflectionProperty->name}", $propertyValues))
) {
throw new AccessException(sprintf('The property "%s::$%s" is not initialized.', \get_class($object), $reflectionProperty->name));
}
}

return $reflectionProperty->getValue($object);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Serializer/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"symfony/error-handler": "^4.4|^5.0",
"symfony/http-foundation": "^3.4|^4.0|^5.0",
"symfony/mime": "^4.4|^5.0",
"symfony/property-access": "^3.4.41|^4.4.9|^5.0.9",
"symfony/property-access": "^4.4.36|^5.3.13",
"symfony/property-info": "^3.4.13|~4.0|^5.0",
"symfony/validator": "^3.4|^4.0|^5.0",
"symfony/yaml": "^3.4|^4.0|^5.0"
Expand Down