Why does `requireValue` default to false?
ekisu opened this issue · comments
Detailed description
Mostly just a question, but is there a specific reason why the requireValue
option on the Field
attribute defaults to false
? It seems a bit weird IMO, because this allows code like the following to work:
use Crell\Serde\SerdeCommon;
class User {
public function __construct(
public readonly string $name,
public readonly string $address
) {}
}
$serde = new SerdeCommon();
$json = '{}';
$user = $serde->deserialize($json, from: 'json', to: User::class);
Context
Defaulting to requiring the value to be present on deserialization if the property has no default value would be a less surprising behavior; and also lower the amount of attributes needed to achieve this behavior
Possible implementation
Changing the default value, or making it configurable at the Serde
level somehow
Your environment
PHP 8.1
The main reason is that it was implemented rather late, and changing the default would have been a BC break. It also broke about a third of the existing tests, and my attempts to fix it were taking too long so I backed that out.
There is a class-level setting to require values for all properties. If you set #[ClassSettings(requireValues: true)]
, then all properties will default to required unless they override it back to false themselves.
See the bulleted list under here: https://github.com/Crell/Serde#configuration
I see, using the class-level attribute does help a lot, but it would be interesting to have some kind of serializer-level configuration for this IMO, maybe something like new SerdeCommon(requireValues: true)
Possibly, but I am very wary of adding what is effectively a deformatter or importer specific property to the main API. The only way to do that in an extensible fashion is with an array of values that can get read somewhere, but... no, that is not an API. 😄 Avoiding that was a key design goal for Serde vs Symfony.