Skip to content

[Auto-Validator] Decimal fields cannot be type-hinted as float #32260

Closed
@spackmat

Description

@spackmat

This is a follow-up-problem related to #32124

Symfony version(s) affected: 4.3.2

Description
After the changes made for #32124 (and updating to 4.3.2), my properties type-hinted as floats throw validation errors about their type, when the automatic validations constraints feature is enabled.

The PropertyInfoLoader automatically adds type constraints based on the internal doctrine type, which is string for decimal fields. So when my getters and setters only accept and return type-hinted float-values, the NumberType-fields for those decimal-properties are always invalid.

I could go through all my entities and make them work with string type-hints (like before they were strict typed), but as they are handling in fact float values from the interface-perspective, I have a strong feeling that the automatic type validation constraint is the wrong part here. That Doctrine handles decimal-fields as strings feels just wrong in a strict-mode type-hinted world, so I type-hinted all my decimal properties with float and casted the values accordingly. Now the form and the auto-validator hunt me.

How to reproduce
Have an entity with a decimal-type property and have getters and setters for it using float-type-hints (with a cast to float in the getter). Then try to save a form with a NumberType for that property: you'll get a "must be string" validation constrain for perfectly valid numeric values.

Possible Solution
I see two ways out:

  1. The PropertyInfoLoader could handle decimal fields, as an exception, in another way. Leaving out the type constraint on those fields at all (as there is no "string or float") or loose it to scalar. Or maybe do some magic and find out the return type of the getter of a property and set the type validator to that type, as it works with the values, the getter returns.
  2. Document a strong warning about typecasting the decimal-properties of Doctrine-entities to float, telling devs that and why this is a bad idea and why this might feel wrong, but is actually the only correct way.

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