Skip to content
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

add check for uninitialized property, and force reflection if type is… #1375

Closed
wants to merge 2 commits into from
Closed
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: 5 additions & 1 deletion src/Accessor/DefaultAccessorStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,18 @@ public function getValue(object $object, PropertyMetadata $metadata, Serializati
return $object->{$metadata->getter}();
}

if ($metadata->forceReflectionAccess) {
if ($metadata->forceReflectionAccess || ($context->getShouldSerializeUnitializedAsNull() && $metadata->hasType)) {
$ref = $this->propertyReflectionCache[$metadata->class][$metadata->name] ?? null;
if (null === $ref) {
$ref = new \ReflectionProperty($metadata->class, $metadata->name);
$ref->setAccessible(true);
$this->propertyReflectionCache[$metadata->class][$metadata->name] = $ref;
}

if (PHP_VERSION_ID >= 70400 && !$ref->isInitialized($object)) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Should it be executed also for the cases when $metadata->forceReflectionAccess is set to true, but $context->getShouldSerializeUnitializedAsNull() will return false?

return null;
}

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

Expand Down
16 changes: 15 additions & 1 deletion src/Metadata/PropertyMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,25 @@ class PropertyMetadata extends BasePropertyMetadata
*/
public $forceReflectionAccess = false;

/**
* @internal
*
* @var bool
*/
public $hasType = false;

public function __construct(string $class, string $name)
{
parent::__construct($class, $name);

try {
$class = $this->getReflection()->getDeclaringClass();
$this->forceReflectionAccess = $class->isInternal() || $class->getProperty($name)->isStatic();
$reflectionProperty = $class->getProperty($name);
$this->forceReflectionAccess = $class->isInternal()
|| $reflectionProperty->isStatic();
$this->hasType = PHP_VERSION_ID >= 70400
&& method_exists($reflectionProperty, 'hasType')
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do we need additional check if method exists? according to docs it should be available since PHP 7.4 - so I would remove additional checks.

&& $reflectionProperty->hasType();
} catch (\ReflectionException $e) {
}
}
Expand Down Expand Up @@ -231,6 +243,7 @@ protected function serializeToArray(): array
$this->excludeIf,
$this->skipWhenEmpty,
$this->forceReflectionAccess,
$this->hasType,
parent::serializeToArray(),
];
}
Expand Down Expand Up @@ -263,6 +276,7 @@ protected function unserializeFromArray(array $data): void
$this->excludeIf,
$this->skipWhenEmpty,
$this->forceReflectionAccess,
$this->hasType,
$parentData,
] = $data;

Expand Down
19 changes: 19 additions & 0 deletions src/SerializationContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ class SerializationContext extends Context
*/
private $serializeNull = false;

/**
* @return bool
*/
private $serializeUnitializedNull = false;

public static function create(): self
{
return new self();
Expand All @@ -50,6 +55,20 @@ public function setSerializeNull(bool $bool): self
return $this;
}

public function getShouldSerializeUnitializedAsNull(): bool
{
return $this->serializeUnitializedNull;
}

public function setShouldSerializeUnitializedAsNull(bool $bool): self
{
$this->assertMutable();

$this->serializeUnitializedNull = $bool;

return $this;
}

/**
* Returns TRUE when NULLs should be serialized
* Returns FALSE when NULLs should not be serialized
Expand Down
32 changes: 32 additions & 0 deletions tests/Serializer/BaseSerializationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1392,6 +1392,38 @@ public function testTypedProperties()
}
}

public function testSerializeWithUninitializedProperty()
{
if (PHP_VERSION_ID < 70400) {
$this->markTestSkipped(sprintf('%s requires PHP 7.4', __METHOD__));
}

$user = new TypedProperties\User();
$user->id = 1;

$context = new SerializationContext();
$context->setShouldSerializeUnitializedAsNull(true);

self::assertEquals(
'{"id":1,"tags":[]}',
$this->serializer->serialize($user, 'json', $context)
);
}

public function testSerializeWithUninitializedPropertyError()
{
if (PHP_VERSION_ID < 70400) {
$this->markTestSkipped(sprintf('%s requires PHP 7.4', __METHOD__));
}

$this->expectException(\Error::class);
$this->expectExceptionMessage('Typed property JMS\Serializer\Tests\Fixtures\TypedProperties\User::$role must not be accessed before initialization');
$user = new TypedProperties\User();
$user->id = 1;

$this->serializer->serialize($user, 'json');
}

/**
* @doesNotPerformAssertions
*/
Expand Down