Fix database rule failure parameters, validator-scoped conditions and ini-dependent float formatting

Merged
AL
4h ago
+853-89

Summary

This PR fixes three regressions in the native validation rules work:

  1. failed() and message replacers report the complete parameter list for unique and exists rules again.
  2. Conditions that a Validator subclass adds through parameters or the getExtraConditions() / getUniqueExtra() hooks combine with a fluent rule's own conditions again, and a manual validate*() call no longer inherits the previous rule's conditions.
  3. Number::toString() no longer depends on the serialize_precision ini setting.

Purpose

Applications and packages ported from Laravel rely on the first two behaviors: custom replacers and failed() assertions read the extra parameters, and multi-tenant validators scope every database rule from a subclass. Both must keep working when a rule is written with the fluent builders. The third change protects PDO bindings, SQL escaping, decimal casts and validation comparisons from a PHP setting that is outside the framework's control.

Problem

Failure parameters were truncated. Database rules validate from a header (table, column, ignored ID, ID column) plus typed conditions, and only the header reached addFailure().

  • unique:users,email,9,id,tenant_id,42 reported ['users', 'email', '9', 'id'] instead of all six parameters.
  • A fluent Rule::unique() without an ignored ID reported '' instead of 'NULL'.
  • The same string rule reported the full list in a Validator subclass and the header only in the base Validator.

Validator-level scoping was dropped for fluent rules. validateExists() and validateUnique() took their conditions only from the current rule when it was a fluent rule or a captured plan.

  • A subclass that appended tenant_id, 42 to $parameters produced a query without tenant_id, so exists passed for another tenant's row.
  • Conditions added by overriding getExtraConditions() or getUniqueExtra() were skipped the same way.
  • A fluent unique rule that declares conditions never reached getExtraConditions(), while the equivalent string rule unique:users,email,NULL,id,active,1 did.
  • $validator->validateExists('team', 5, ['teams', 'id', 'tenant_id', '8']) called from an after() hook ran with the conditions of the last validated rule instead of its own parameters.

Float formatting followed serialize_precision. Number::toString() used json_encode().

  • With serialize_precision=17, 19.99 was bound as 19.989999999999998, so where('price', 19.99) on a DECIMAL column found no row, and Rule::numeric()->max(19.99) rejected the string input '19.99'.
  • With serialize_precision=6, 1234567.89 was bound as 1.23457e+6 and stored as 1234570.00 without a warning.

Architecture and Implementation

Failure reporting

  • DatabaseRulePlan keeps the extra parameters of a string or array rule exactly as written, and gains failureParameters(array $header). It returns the header followed by those parameters, or, for a fluent rule, by the conditions rendered in the legacy form.
  • Validator::validateAttribute() calls it only when a check fails. The validate*() methods still receive the header alone, so a plan's conditions are never applied twice.
  • The header passed in is the one that was validated, so resolved field references such as [items.0.id] are reported as before.
  • In a Validator subclass the rule object is not captured as a plan. The conditions read during the check are kept on the validator and reused for the report. If the check failed before reading them (for example a nested array value), they are read once at that point.

Legacy rendering and the string form

  • The rendering moved from DatabaseRule::formatWheres() to DatabaseConditions::toParameters(), which the string form and the failure report share.
  • Callbacks and whereIn / whereNotIn have no legacy form and are omitted, as before.
  • An operand that is an object, such as a query Expression, cannot be rendered. (string) $rule throws a LogicException that names the column. The failure report calls toParameters(omitOpaqueOperands: true) and leaves the operand out.

Condition merging

  • validateExists() and validateUnique() always resolve the parameters after the header through getExtraConditions() / getUniqueExtra(), then merge the result with the current rule's conditions through the new DatabaseConditions::merge().
  • A fluent unique rule reaches the shared hook for comparisons and null checks. A rule containing only whereIn(), whereNotIn() or callbacks keeps its original query scope.
  • An independent lookup inside a condition hook, query callback, or error-message callback uses its own parameters. Subclasses can still inspect the rule being validated.
  • merge() returns either operand unchanged when the other is empty, so the base validator's batched and per-item paths still build identical presence queries.
  • After nested attribute validation, $currentRule again describes the enclosing check. At the end of a top-level check it is cleared.

Float formatting

  • Number::toString() uses sprintf('%.*h', -1, $number). Precision -1 selects PHP's shortest round-trip form without reading precision or serialize_precision, and %h ignores the numeric locale.

Design Decisions and Trade-offs

  • Report at the failure boundary instead of widening the validated parameters. Passing the full list to validate*() would have required every header reader to tolerate a tail and risked double-applying conditions.
  • Verbatim parameters for string and array rules, rendered parameters for fluent rules. Verbatim storage reproduces the previous output exactly, including native values in array rules.
  • Throw from the string form, omit only in the failure report. A rule string that silently lost a predicate would validate against more rows than the rule declares, so (string) $rule fails loudly. A failure report must not turn a validation failure into an exception, so it omits the operand.
  • Laravel's merge order and hook reach. Parameter and hook conditions come first, followed by the rule's own. The shared hook runs for a unique rule only when it has extra conditions.
  • The hook receives no segments for a fluent rule. Typed conditions are not rendered and parsed again, because that would reinterpret literal values such as NULL. A hook can add conditions to a fluent rule but cannot inspect or rewrite the builder's own.
  • Keep the database declaration local to its check. The validator passes a builder or compiled plan to the check that owns it. If a subclass calls the parent check twice, each call uses the same declaration. Error reporting uses the conditions that check read.
  • Native formatter, no process-wide settings. No custom float formatter was added and no ini value is modified at runtime.
  • Accepted limitation. The validation plan cache and presence lookup keys are still built with serialize(), which follows serialize_precision. A lossy value (1–16) can make rules with close float parameters share a cached plan. This is unchanged, and validation.md keeps its statement that float conversion relies on PHP's default serialize_precision=-1.

Changes

Support

  • Number::toString(): format finite floats with sprintf('%.*h', -1, ...).

Validation

  • DatabaseConditions: add toParameters() and merge(). DatabaseConditionOperator::isMembership() identifies In and NotIn.
  • DatabaseRulePlan: retain the written extra parameters; add failureParameters().
  • Rules\DatabaseRule::formatWheres(): delegate to DatabaseConditions::toParameters(), which throws for an operand without a string form.
  • Concerns\ValidatesAttributes combines each check's own conditions with its validator hooks.
  • callReplacer() returns a string. Closure replacers run directly and class-based replacers go through callClassBasedReplacer().
  • Validator reports complete database-rule failure parameters and restores the enclosing rule after a nested check.

Documentation

  • database.md: PDO float bindings and SQL escaping no longer depend on precision or serialize_precision.
  • validation.md: a rule whose condition uses a query expression cannot be converted to a string.

Tests

  • SupportNumberTest: output of Number::toString(), including under serialize_precision 17 and 6.
  • ValidationValidatorTest:
    • failure parameters for string, array, fluent and wildcard rules, an expression operand and a value rejected before any query, in the base validator and a subclass;
    • subclasses that add a scope through parameters or either condition hook, including unique rules with no predicates, membership predicates alone, and membership mixed with a comparison;
    • a condition hook that validates another attribute and performs a separate database lookup;
    • independent database lookups during message selection, attribute formatting, message replacement and an after() hook.
  • ValidationExistsRuleTest: the string form rejects a condition with an expression operand.

Validation

Two regression tests failed on 19a1c648b: a message selector missed an existing row, and a nested uniqueness check re-entered the outer condition hook. Both pass with the fix. All 2,172 validation unit tests passed, as did the applicable SQLite batching tests.

Earlier local verification on PHP 8.4.27 with Swoole 6.2.4:

  • tests/Validation: 2167 tests passed.
  • tests/Integration/Validation: passed on the default test connection (115 tests, 4 skipped) and on MySQL 8.4.11 (115 tests, 1 skipped).
  • tests/Data (2183) and tests/Foundation (1711, 3 skipped): passed.
  • tests/Telescope (516) and SupportNumberTest (28): passed at 2dbc667f9, before the last two commits, which only touch the validation package.
  • Two intermediate commits were tested in isolation from an exported tree: tests/Validation passed with 2163 tests at bdcdb7015 and 2166 tests at 2d75cd09d.
  • PHPStan on src/validation/src, src/support/src/Number.php and the changed test files: no errors.
  • php-cs-fixer dry run on the changed PHP files: no changes required.
  • Number::toString() output was compared with the previous implementation over roughly 800,000 floats: identical under default settings, and unchanged under serialize_precision 17 and 6 and a comma-decimal locale.
  • Bound float text, escape(), toRawSql() and increment() amounts were identical under five combinations of precision and serialize_precision on SQLite.
  • Each problem above, and each automated review finding, was reproduced before the change and confirmed fixed afterwards on in-memory SQLite; the original three were also confirmed on MySQL 8.4.11.

Risks and Review Notes

  • Custom message replacers. A validator subclass that overrides the protected callReplacer() method must declare string as its return type. Normal replacer registration is unchanged.
  • failed() output grows. Code asserting the header-only output of this branch will see the extra parameters. The new output matches Laravel.
  • Hooks now apply to fluent rules. Validator subclasses can scope fluent rules through their condition hooks. A fluent unique rule containing only membership predicates still skips the shared hook.
  • A scope added through both hooks appears twice. For a unique rule with conditions, a subclass that adds the same condition in getUniqueExtra() and getExtraConditions() produces tenant_id = ? and tenant_id = ?. The equivalent string rule behaves the same way, and the result is unaffected.
  • $currentRule is null after a run. Subclasses that read it inside after() hooks will no longer see the last validated rule.
  • (string) $rule throws a LogicException for expression operands. It previously failed with a generic conversion Error, so only the exception type and message change.
  • Documentation and the recorded plan. docs/plans/2026-11-15-validation-native-rules.md says not to claim independence from serialize_precision. database.md now makes that claim for PDO bindings and SQL escaping only; please confirm this is acceptable. Floats nested inside JSON-cast attributes are encoded by json_encode() before binding and still follow the setting.
  • Allocation. The base validator creates one empty DatabaseConditions per presence check because the hooks are always called. A 2,999-item comparison against the previous code showed no difference outside measurement noise; it was not a rigorous benchmark.
  • Review focus. validateAttribute() supplies the declaration for each database check. getExistCount() and validateUnique() take and restore it around the hooks and query. DatabaseConditions::toParameters() renders failure details.

Related Information

  • Follow-up to #745, which introduced typed database conditions, DatabaseRulePlan and Number::toString().
  • Follow-up commits cover nested database checks, unique-rule hook behavior and expression operands in rule strings.
  • No issues or follow-up tickets are linked.

[!NOTE]

Fix database rule failure parameters, scoped conditions, and float formatting in Validator

  • Number::toString now formats finite floats via sprintf('%h') with precision -1, so output is the shortest round-trip form and ignores PHP precision/serialize_precision settings. Non-finite floats still render as NAN, INF, and -INF.
  • The validator tracks the database rule dispatched to each check, so validateUnique and getExistCount combine conditions from the dispatched rule (plan or Unique/Exists builder) with conditions supplied by validation parameters and extra-condition hooks. Nested validation restores the enclosing rule state.
  • DatabaseRulePlan::failureParameters builds legacy-style parameter lists for failed database rules, preserving legacy extras and rendering typed conditions via DatabaseConditions::toParameters (booleans become integers, floats use Number::toString).
  • DatabaseRule::formatWheres uses toParameters, and FormatsMessages::callReplacer now always returns a string.
  • Risk: converting a database rule to a string throws LogicException when a condition has a non-membership object operand without a string form; membership predicates no longer trigger the unique-condition hook.
  • Behavioral Change: manual database lookups made inside query callbacks or hooks now use their own conditions instead of inheriting the outer rule's conditions.

Macroscope summarized cba4cb2.

Summary by CodeRabbit

  • Bug Fixes
    • Database validation rules now consistently combine conditions from rule definitions and validation hooks. Failed checks report the appropriate conditions, and nested validation no longer causes conditions to leak between checks.
    • Finite floating-point values are now converted consistently regardless of PHP’s precision settings.
  • Documentation
    • Clarified that finite values are preserved independently of PHP precision settings and that database rules with query expressions cannot be converted to strings.