Description
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,
],
);