Skip to content

Coerce scalar properties without loss - #37

Merged
yuriizee merged 1 commit into
3.xfrom
lossless-scalar-coercion
Nov 27, 2026
Merged

yuriizee merged 1 commit into
3.xfrom
lossless-scalar-coercion

Conversation

@yuriizee

Copy link
Copy Markdown
Contributor

A property typed int, float, string or bool without a cast now accepts only values that convert without loss: "3" and 3.0 into int, a numeric string into float, int/float/Stringable into string, and "false", "no", "0", "" into bool as false. Anything else throws DataHydrationException naming the field ("Invalid value for field 'age': Cannot convert string to int without loss."). tryFrom() returns null, and fromResult() and with() apply the same rules. In 2.x PHP's weak coercion applied, so "1.9" became 1 and "false" became true.

How it works

  • The from() hydrator is compiled with strict_types, both through eval and in the .meta.php cache file, so values of the declared type go straight to the constructor with no extra checks.
  • When the constructor rejects an argument with a TypeError, ScalarCoercion::input() converts the plain scalar fields that need it and the call is retried once.
  • If no field needed converting, the original TypeError is rethrown (redacted as before), so a TypeError from the constructor body never runs the body twice.
  • fromResult(), fromLazy(), with() and property assignments check the type inline.
  • Union types (int|string) are checked strictly and not converted.
  • ParameterMeta gets a scalarType field with a __set_state default. The cache format is bumped to sdo-cache-5.

Benchmark

Medians of 9 rounds against the base. Everything is within ±2%, except cold "Hydration: flat", where the base itself swings between 3.1M and 4.1M ops/s from run to run.

A first version checked the type inline in every field and cost 6–18% on nested data and collections; this design replaced it.

Mutation testing

The only escaped mutants are equivalent ones: whitespace or ordering in the generated catch, and the int-range bound that guards the float→int cast against PHP 8.5's out-of-range warning.

Docs: hydration.md ("Scalar Types"), UPGRADE-3.0, CHANGELOG, the upgrade skill.

Closes #24.

Hydrators compile with strict_types; when the constructor rejects an argument, plain int, float, string and bool fields are converted only if lossless and the call is retried, so input of the declared type costs nothing extra. Lossy input throws DataHydrationException naming the field. Closes #24.
@yuriizee
yuriizee merged commit 0dfb1f5 into 3.x Nov 27, 2026
6 checks passed
@yuriizee
yuriizee deleted the lossless-scalar-coercion branch November 27, 2026 13:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant