Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Serializer] Add context flag for AbstractNormalizer to prevent usage of null for non-optional nullable constructor parameters without default valueΒ #49504

Closed
@christian-kolb

Description

@christian-kolb

Description

The PR #40522 introduced a fallback for nullable properties to be set to null when they aren't provided as parameters.

A drawback of that approach is that it easier for bugs to appear through typos or renamings of those properties. I think the current implementation makes perfect sense, but would love a context flag PREVENT_NULLABLE_FALLBACK.

It would also be possible to turn it around and change the default. Then it would be in line with SKIP_NULL_VALUES of the AbstractObjectNormalizer, but that might be to big of a change.

I think the only change necessary to implement it would be from:

} elseif ($constructorParameter->hasType() && $constructorParameter->getType()->allowsNull()) {
    $params[] = null;
}

to:

} elseif ($constructorParameter->hasType() && $constructorParameter->getType()->allowsNull() && !isset($context[self::PREVENT_NULLABLE_FALLBACK])) {
    $params[] = null;
}

I'd be happy to provide a PR for it, if this is an addition the community is fine with. I would really love to have this in the component to find bugs easier on refactoring πŸ™‚

Example

final class Product
{
    public function __construct(
        public string $name,
        public ?int $costsInCent,
    ) {
    }
}

// This works and results in $costsInCent as null
$product = $this->serializer->deserialize('{"name": "foo"}', Product::class, JsonEncoder::FORMAT);

// After the change only the following is valid
$product = $this->serializer->deserialize(
    '{"name": "foo", "costsInCent": null}',
    Product::class,
    JsonEncoder::FORMAT,
    [
        AbstractNormalizer::PREVENT_NULLABLE_FALLBACK,
    ],
);

// This would result in an error due to missing parameters
$product = $this->serializer->deserialize(
    '{"name": "foo"}',
    Product::class,
    JsonEncoder::FORMAT,
    [
        AbstractNormalizer::PREVENT_NULLABLE_FALLBACK,
    ],
);

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions