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

Fix deserialization not initializing properties when they have a default value and the field is not found in the payload #1417

Merged
merged 4 commits into from
Aug 6, 2022
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
1 change: 1 addition & 0 deletions .github/workflows/benchmark.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ jobs:
php-version:
- "7.2"
- "8.0"
- "8.1"

steps:
- name: Checkout code
Expand Down
29 changes: 28 additions & 1 deletion .github/workflows/static-analysis.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,41 @@ jobs:

- name: "Run a static analysis with phpstan/phpstan"
run: "vendor/bin/phpstan analyse -c phpstan-7-4.neon.dist --error-format=checkstyle | cs2pr"
static-analysis-phpstan:

static-analysis-phpstan-8-0:
name: "Static Analysis with PHPStan"
runs-on: "ubuntu-20.04"

strategy:
matrix:
php-version:
- "8.0"

steps:
- name: "Checkout code"
uses: "actions/checkout@v2"

- name: "Install PHP"
uses: "shivammathur/setup-php@v2"
with:
coverage: "none"
php-version: "${{ matrix.php-version }}"
tools: "cs2pr"
extensions: pdo_sqlite

- name: "Install dependencies with Composer"
uses: "ramsey/composer-install@v1"

- name: "Run a static analysis with phpstan/phpstan"
run: "vendor/bin/phpstan analyse -c phpstan-8-0.neon.dist --error-format=checkstyle | cs2pr"

static-analysis-phpstan-8-1:
name: "Static Analysis with PHPStan"
runs-on: "ubuntu-20.04"

strategy:
matrix:
php-version:
- "8.1"
include:
- { php-version: '8.2', composer-options: '--ignore-platform-req=php' }
Expand Down
1 change: 1 addition & 0 deletions phpstan-7-4.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ parameters:
- %currentWorkingDirectory%/tests
excludePaths:
- %currentWorkingDirectory%/tests/Fixtures/TypedProperties/UnionTypedProperties.php
- %currentWorkingDirectory%/tests/Fixtures/TypedProperties/ConstructorPromotion/Vase.php
- %currentWorkingDirectory%/tests/Fixtures/TypedProperties/UnionTypedProperties.php
- %currentWorkingDirectory%/tests/Metadata/Driver/UnionTypedPropertiesDriverTest.php
- %currentWorkingDirectory%/tests/Serializer/BaseSerializationTest.php
Expand Down
14 changes: 14 additions & 0 deletions phpstan-8-0.neon.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
parameters:
level: 1

ignoreErrors:
- '~Class Doctrine\\Common\\Persistence\\Proxy not found~'
- '~Class Doctrine\\ODM\\MongoDB\\PersistentCollection not found~'
- '~Class Symfony\\(Contracts|Component)\\Translation\\TranslatorInterface not found~'
- '#Constructor of class JMS\\Serializer\\Annotation\\.*? has an unused parameter#'
- '#Class JMS\\Serializer\\Annotation\\DeprecatedReadOnly extends @final class JMS\\Serializer\\Annotation\\ReadOnlyProperty.#'

paths:
- %currentWorkingDirectory%/src
- %currentWorkingDirectory%/tests
- %currentWorkingDirectory%/tests/Fixtures/TypedProperties/ConstructorPromotion/Vase.php
5 changes: 5 additions & 0 deletions src/Builder/DefaultDriverFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use JMS\Serializer\Expression\CompilableExpressionEvaluatorInterface;
use JMS\Serializer\Metadata\Driver\AnnotationDriver;
use JMS\Serializer\Metadata\Driver\AttributeDriver;
use JMS\Serializer\Metadata\Driver\DefaultValuePropertyDriver;
use JMS\Serializer\Metadata\Driver\TypedPropertiesDriver;
use JMS\Serializer\Metadata\Driver\XmlDriver;
use JMS\Serializer\Metadata\Driver\YamlDriver;
Expand Down Expand Up @@ -63,6 +64,10 @@ public function createDriver(array $metadataDirs, Reader $annotationReader): Dri
$driver = new TypedPropertiesDriver($driver, $this->typeParser);
}

if (PHP_VERSION_ID >= 80000) {
$driver = new DefaultValuePropertyDriver($driver);
}

return $driver;
}
}
3 changes: 3 additions & 0 deletions src/GraphNavigator/DeserializationGraphNavigator.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,9 @@ public function accept($data, ?array $type = null)
$v = $this->visitor->visitProperty($propertyMetadata, $data);
$this->accessor->setValue($object, $v, $propertyMetadata, $this->context);
} catch (NotAcceptableException $e) {
if (true === $propertyMetadata->hasDefault) {
$this->accessor->setValue($object, $propertyMetadata->defaultValue, $propertyMetadata, $this->context);
}
}

$this->context->popPropertyMetadata();
Expand Down
80 changes: 80 additions & 0 deletions src/Metadata/Driver/DefaultValuePropertyDriver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

declare(strict_types=1);

namespace JMS\Serializer\Metadata\Driver;

use JMS\Serializer\Metadata\ClassMetadata as SerializerClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;
use Metadata\ClassMetadata;
use Metadata\Driver\DriverInterface;
use ReflectionClass;
use ReflectionException;
use ReflectionProperty;

class DefaultValuePropertyDriver implements DriverInterface
{
/**
* @var DriverInterface
*/
protected $delegate;

public function __construct(DriverInterface $delegate)
{
$this->delegate = $delegate;
}

public function loadMetadataForClass(ReflectionClass $class): ?ClassMetadata
{
$classMetadata = $this->delegate->loadMetadataForClass($class);
\assert($classMetadata instanceof SerializerClassMetadata);

if (null === $classMetadata) {
return null;
}

foreach ($classMetadata->propertyMetadata as $key => $propertyMetadata) {
\assert($propertyMetadata instanceof PropertyMetadata);
if (null !== $propertyMetadata->hasDefault) {
continue;
}

try {
$propertyReflection = $this->getPropertyReflection($propertyMetadata);
$propertyMetadata->hasDefault = false;
if ($propertyReflection->hasDefaultValue() && $propertyReflection->hasType()) {
$propertyMetadata->hasDefault = true;
$propertyMetadata->defaultValue = $propertyReflection->getDefaultValue();
} elseif ($propertyReflection->isPromoted()) {
// need to get the parameter in the constructor to check for default values
$classReflection = $this->getClassReflection($propertyMetadata);
$params = $classReflection->getConstructor()->getParameters();
foreach ($params as $parameter) {
if ($parameter->getName() === $propertyMetadata->name) {
if ($parameter->isDefaultValueAvailable()) {
$propertyMetadata->hasDefault = true;
$propertyMetadata->defaultValue = $parameter->getDefaultValue();
}

break;
}
}
}
} catch (ReflectionException $e) {
continue;
}
}

return $classMetadata;
}

private function getPropertyReflection(PropertyMetadata $propertyMetadata): ReflectionProperty
{
return new ReflectionProperty($propertyMetadata->class, $propertyMetadata->name);
}

private function getClassReflection(PropertyMetadata $propertyMetadata): ReflectionClass
{
return new ReflectionClass($propertyMetadata->class);
}
}
14 changes: 14 additions & 0 deletions src/Metadata/PropertyMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,16 @@ class PropertyMetadata extends BasePropertyMetadata
*/
public $excludeIf = null;

/**
* @var bool|null
*/
public $hasDefault;

/**
* @var mixed|null
*/
public $defaultValue;

/**
* @internal
*
Expand Down Expand Up @@ -235,6 +245,8 @@ protected function serializeToArray(): array
$this->excludeIf,
$this->skipWhenEmpty,
$this->forceReflectionAccess,
$this->hasDefault,
$this->defaultValue,
parent::serializeToArray(),
];
}
Expand Down Expand Up @@ -267,6 +279,8 @@ protected function unserializeFromArray(array $data): void
$this->excludeIf,
$this->skipWhenEmpty,
$this->forceReflectionAccess,
$this->hasDefault,
$this->defaultValue,
$parentData,
] = $data;

Expand Down
16 changes: 16 additions & 0 deletions tests/Fixtures/TypedProperties/ConstructorPromotion/Vase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace JMS\Serializer\Tests\Fixtures\TypedProperties\ConstructorPromotion;

class Vase
{
public function __construct(
public string $color,
public ?string $plant = null,
public string $typeOfSoil = 'potting mix',
public int $daysSincePotting = -1,
) {
}
}
22 changes: 22 additions & 0 deletions tests/Serializer/BaseSerializationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1485,6 +1485,28 @@ public function testTypedProperties()
}
}

public function testConstructorPromotionWithDefaultValues()
{
if (PHP_VERSION_ID < 80000) {
$this->markTestSkipped(sprintf('%s requires PHP 8.0', __METHOD__));
}

$builder = SerializerBuilder::create($this->handlerRegistry, $this->dispatcher);
$builder->includeInterfaceMetadata(true);
$this->serializer = $builder->build();

$vase = new TypedProperties\ConstructorPromotion\Vase('blue');
$result = $this->serialize($vase);
self::assertEquals($this->getContent('typed_props_constructor_promotion_with_default_values'), $result);
if ($this->hasDeserializer()) {
$deserialized = $this->deserialize($this->getContent('typed_props_constructor_promotion_with_default_values'), get_class($vase));
self::assertEquals($vase->color, $deserialized->color);
self::assertEquals($vase->plant, $deserialized->plant);
self::assertEquals($vase->typeOfSoil, $deserialized->typeOfSoil);
self::assertEquals($vase->daysSincePotting, $deserialized->daysSincePotting);
}
}

public function testUninitializedTypedProperties()
{
if (PHP_VERSION_ID < 70400) {
Expand Down
1 change: 1 addition & 0 deletions tests/Serializer/JsonSerializationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ protected function getContent($key)
$outputs['user_discriminator'] = '{"entityName":"User"}';
$outputs['user_discriminator_extended'] = '{"entityName":"ExtendedUser"}';
$outputs['typed_props'] = '{"id":1,"role":{"id":5},"vehicle":{"type":"car"},"created":"2010-10-01T00:00:00+00:00","updated":"2011-10-01T00:00:00+00:00","tags":["a","b"]}';
$outputs['typed_props_constructor_promotion_with_default_values'] = '{"color":"blue","type_of_soil":"potting mix","days_since_potting":-1}';
$outputs['uninitialized_typed_props'] = '{"id":1,"role":{},"tags":[]}';
$outputs['custom_datetimeinterface'] = '{"custom":"2021-09-07"}';
$outputs['data_integer'] = '{"data":10000}';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<result>
<color><![CDATA[blue]]></color>
<type_of_soil><![CDATA[potting mix]]></type_of_soil>
<days_since_potting>-1</days_since_potting>
</result>