Skip to content

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

Merged
binaryfire merged 14 commits into
0.4from
improve/validation-native-rules-20261123
Nov 23, 2026
Merged

binaryfire merged 14 commits into
0.4from
improve/validation-native-rules-20261123

Conversation

@albertcht

@albertcht albertcht commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

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

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.

Number::toString() formatted finite floats with json_encode(), so PDO
bindings, SQL escaping, decimal casts and validation comparisons changed
with the serialize_precision ini setting. A lossy value truncated bound
floats, and 17 expanded 19.99 to 19.989999999999998.

Use sprintf('%.*h', -1, ...) instead. It selects PHP's shortest
round-trip form without reading precision or serialize_precision and
ignores the numeric locale, and its output is identical under the
default settings.
Database rules now validate from a header and typed conditions, which
left failed() and message replacers with the header only. The string
rule unique:users,email,9,id,tenant_id,42 reported four parameters
instead of six, a fluent rule without an ignored ID reported an empty
string instead of NULL, and the base validator and validator subclasses
disagreed for the same string rule.

Report the header followed by the extra parameters again, as Laravel
does. Rules declared as strings or arrays keep the parameters they were
written with, and fluent rules render their conditions in the legacy
form. Validator subclasses reuse the conditions already read during the
check instead of reading the rule builder a second time.

The legacy rendering moves from DatabaseRule::formatWheres() to
DatabaseConditions::toParameters() so both callers share it. It now
omits operands that have no string form, such as query expressions,
instead of throwing, which also applies to the rule's string form.
…ions

validateExists() and validateUnique() took their conditions only from
the rule being validated when it was a fluent rule or a captured plan.
Parameters a Validator subclass appended, and conditions added through
getExtraConditions() or getUniqueExtra(), were dropped, so a tenant
scope applied that way silently disappeared. A validate method called
from an after hook also inherited the conditions of the last validated
rule instead of using its own parameters.

Resolve the parameters after the header through the hooks and merge
them with the rule's own conditions, as Laravel does, and clear the
current rule once a validation run finishes.
@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Finite float conversion now uses formatting that is independent of PHP precision settings. Database validation combines rule and hook conditions and reports failure parameters from captured database-rule conditions.

Changes: Database validation and parameter formatting

Layer / File(s) Summary
Finite float formatting
src/support/src/Number.php, tests/Support/SupportNumberTest.php, src/docs/database.md
Number::toString now formats finite floats with sprintf’s precision -1 %h form. Tests cover float values and different serialize_precision settings. The documentation states that PDO preserves finite values regardless of precision and serialize_precision.
Database-rule condition parameters
src/validation/src/DatabaseConditionOperator.php, src/validation/src/DatabaseConditions.php, src/validation/src/DatabaseRulePlan.php, src/validation/src/Rules/DatabaseRule.php, tests/Validation/ValidationExistsRuleTest.php, src/docs/validation.md
DatabaseConditions merges conditions and converts supported predicates to legacy parameters. DatabaseRulePlan retains legacy parameters and constructs failure parameters. DatabaseRule::formatWheres() uses the converted pairs. Tests verify that expression conditions cannot be converted to strings. The documentation adds this limit to its guidance on database-rule strings.
Condition merging and failure reporting
src/validation/src/Concerns/ValidatesAttributes.php, src/validation/src/Concerns/FormatsMessages.php, src/validation/src/Validator.php, src/validation/src/DelegatedCheck.php, tests/Validation/ValidationValidatorTest.php
Exists and Unique validation combine hook-provided conditions with rule conditions. Validator captures conditions for the active database rule and uses them to build failure parameters. Validation state is restored after checks, including nested checks and exceptions. Tests cover merged conditions, normalized failure parameters, repeated lookups, and isolation during error formatting.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Validator
  participant ValidatesAttributes
  participant PresenceVerifier
  participant DatabaseRulePlan
  Validator->>ValidatesAttributes: validate Exists or Unique rule
  ValidatesAttributes->>PresenceVerifier: check with merged conditions
  PresenceVerifier-->>ValidatesAttributes: return match count
  ValidatesAttributes-->>Validator: return validation result
  Validator->>DatabaseRulePlan: build failure parameters from captured conditions
Loading

Suggested reviewers: binaryfire

Merge Risk: Low · up to cba4c

This change makes database-rule failure parameters complete, scopes conditions to each check, and makes float formatting independent of PHP ini settings. Two narrow risks remain. A message replacer that runs a manual database lookup inside an overridden database check can still inherit the outer rule's conditions. Subclasses that override callReplacer() with a nullable return type must update their declaration. Neither blocks merging, but both are worth acknowledging.

Pre-merge checks: Passed 3 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Description check Inconclusive The description follows the repository template and includes Summary, Purpose, Problem, Architecture and Implementation, Design Decisions, Changes, Validation, and Risks sections. It omits the require… Select Bug fix under Contribution type. Add a Supporting evidence section that names each regression test and reports its result before and after the fix. Confirm in Verification that composer fix ran successfully from the repository root…
Passed Passed checks: 3 passed

Check name Status Explanation
Title check Passed The title identifies all three changes: database rule failure parameters, validator-scoped conditions, and INI-dependent float formatting. The changeset covers all three. The title is specific, but it…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title identifies all three changes: database rule failure parameters, validator-scoped conditions, and INI-dependent float formatting. The changeset covers all three. The title is specific, but it is long at 11 words and 100 characters.

Full details: Description check

Explanation

The description follows the repository template and includes Summary, Purpose, Problem, Architecture and Implementation, Design Decisions, Changes, Validation, and Risks sections. It omits the required Contribution type checklist and Supporting evidence section. It reports failing-then-passing results for two regression tests but does not name the tests. It does not link an issue or discussion. It names verification commands and results but does not confirm that composer fix ran successfully from the repository root. The checklist items are not marked complete.

Resolution

Select Bug fix under Contribution type. Add a Supporting evidence section that names each regression test and reports its result before and after the fix. Confirm in Verification that composer fix ran successfully from the repository root. Link the related issue or discussion, or state that none exists. Mark each Before submitting checklist item complete only after verifying it.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

PHPMD (3.0.0)

tests/Validation/ValidationValidatorTest.php

PHPMD could not process this file (exit code 255): 0/1 [░░░░░░░░░░░░░░░░░░░░░░░░░░░░] 0%
1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 10485760 bytes) in phar:///usr/bin/phpmd/vendor/pdepend/pdepend/src/Util/Cache/Driver/FileCacheDriver.php on line 183

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 19a1c64 and cba4cb2.

Files selected for processing: 5

  • src/validation/src/Concerns/FormatsMessages.php
  • src/validation/src/Concerns/ValidatesAttributes.php
  • src/validation/src/DelegatedCheck.php
  • src/validation/src/Validator.php
  • tests/Validation/ValidationValidatorTest.php

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@albertcht

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Restore database rule scoping and failure parameters; stabilize float formatting

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Restore complete unique and exists failure parameters for assertions and message replacers.
• Combine validator-scoped conditions with fluent rules without leaking conditions into manual
 checks.
• Make float conversion independent of ini precision settings; document and test the behavior.
Merge Risk 🟡 Medium

Blast radius 🔴 High 💥 4 capabilities

  • 4 affected capabilities span independent functional scopes: database numeric persistence and query integration, database-backed validation integration, validation numeric rules and diagnostics.
  • This is one end-to-end database behavior: the shared numeric representation is used when values are bound or emitted into database expressions.
  • Binding and query-literal calls are implementation paths of the same database integration outcome, not separate capabilities.
  • Validation numeric checks and their rendered numeric values are one bounded validation subsystem.
  • They share the changed numeric conversion contract, while remaining independent from database persistence outcomes.
  • Exists and Unique entry points produce the same bounded validation outcome: deciding whether submitted data satisfies a database presence or uniqueness constraint.
  • Fluent rules, legacy strings, subclass hooks, and nested callbacks are propagation paths within that integration, not independent functional scopes.
  • Failure parameter reconstruction is a separate user-visible operation within the same database-backed validation integration.
  • It reports the originating Exists or Unique declaration rather than creating a separate functional domain.
Sources

src/support/src/Number.php[83-86]

        if (is_finite($number)) {
            // Precision -1 selects PHP's shortest round-trip form without consulting the
            // precision or serialize_precision settings, and %h ignores the numeric locale.
            return sprintf('%.*h', -1, $number);

src/validation/src/Validator.php[1147-1154]

        // Unlike Laravel, restore the enclosing rule when a subclass validates a nested attribute.
        $outerRule = $this->currentRule;
        $outerDatabaseRule = $this->dispatchedDatabaseRule;
        $outerConditions = $this->currentRuleConditions;

        $this->currentRule = $declaration = $rule;
        $this->dispatchedDatabaseRule = null;
        $this->currentRuleConditions = null;
Behavioral complexity 🟡 Medium 🧩 Interacting branches, Compatibility cases

  • Before, the active rule and conditions were read from a single current-rule context, and database conditions were selected through a direct match.
  • After, execution must capture and restore outer rule state, distinguish DatabaseRulePlan from Exists and Unique, merge hook conditions with fluent conditions, preserve conditions across nested callbacks/manual checks, and reconstruct legacy-compatible failure parameters.
  • The new correctness conditions are: outer state must be restored after re-entrant checks; the declaration used for a query must match the rule currently being executed; condition ordering and combination must be preserved; and modern typed conditions must remain compatible with legacy failure parameters without silently dropping query predicates.
  • These are newly interacting states and mixed-representation compatibility cases, not merely reuse of existing mapping infrastructure.
Sources

src/validation/src/Validator.php[1147-1154]

        // Unlike Laravel, restore the enclosing rule when a subclass validates a nested attribute.
        $outerRule = $this->currentRule;
        $outerDatabaseRule = $this->dispatchedDatabaseRule;
        $outerConditions = $this->currentRuleConditions;

        $this->currentRule = $declaration = $rule;
        $this->dispatchedDatabaseRule = null;
        $this->currentRuleConditions = null;
Potential damage 🟡 Medium 🩹 Incorrect results

  • If the changed formatter produces an incorrect or incompatible representation for a supported finite float, a query predicate may match the wrong rows, a numeric update may use the wrong amount, or a persisted value may be stored differently.
  • The supported intent is round-trip preservation, so this is conditional on an implementation/runtime fault rather than an asserted defect.
  • A code rollback or formatter correction can prevent future incorrect values.
  • Queries can generally be retried, but values already persisted with an incorrect textual representation may require explicit data repair; external effects caused by a wrong update are not automatically compensated by rollback.
Sources

src/support/src/Number.php[83-86]

        if (is_finite($number)) {
            // Precision -1 selects PHP's shortest round-trip form without consulting the
            // precision or serialize_precision settings, and %h ignores the numeric locale.
            return sprintf('%.*h', -1, $number);
Assessed commit cba4cb2
Diagram

graph TD
  Rules["Rule declarations"] -->|base| Plan["Captured plan"] --> Validator["Validator"] --> Merge["Condition merge"] --> Query["Presence query"] -->|on failure| Failure["Failure report"]
  Rules -->|subclass| Validator
  Hooks["Scope hooks"] --> Merge
  Validator -->|early failure| Failure
  Number["Float formatting"] --> Query
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Pass full parameters into database validators
  • ➕ Keeps failure reporting close to the parameters passed into validate*().
  • ➖ Requires header readers to handle trailing conditions and risks applying conditions twice.
2. Centralize condition resolution in a shared helper
  • ➕ Could prevent the exists and unique resolution paths from diverging later.
  • ➖ Adds an abstraction across paths with different headers and hooks for limited immediate benefit.

Recommendation: Keep the PR's failure-boundary reporting and ordered condition merge: they restore the expected behavior without changing the headers used for validation. Consider a shared resolver only if more database-rule paths are added.

Files changed (11) +358 / -41

Enhancement (1) +51 / -0
DatabaseConditions.phpAdd ordered condition merging and legacy parameter rendering +51/-0

Add ordered condition merging and legacy parameter rendering

• Adds a merge operation and converts representable conditions into legacy column/value parameters. Callbacks, membership predicates, and opaque object operands are omitted from rendering.

src/validation/src/DatabaseConditions.php

Bug fix (4) +74 / -15
Number.phpFormat finite floats independently of ini precision +3/-2

Format finite floats independently of ini precision

• Replaces JSON-based conversion with shortest round-trip, locale-independent sprintf formatting. Integer, string, and non-finite handling remains unchanged.

src/support/src/Number.php

ValidatesAttributes.phpMerge validator-scoped and rule-owned database conditions +19/-10

Merge validator-scoped and rule-owned database conditions

• Exists and unique checks now resolve extra conditions through validator hooks before appending conditions from the current plan or fluent rule.

src/validation/src/Concerns/ValidatesAttributes.php

DatabaseRulePlan.phpRetain written extras for complete failure reports +27/-1

Retain written extras for complete failure reports

• Preserves extra parameters from string and array rules through snapshots. Failure reporting combines the validated header with those written extras or rendered fluent conditions.

src/validation/src/DatabaseRulePlan.php

Validator.phpReport complete database failures and clear stale rule context +25/-2

Report complete database failures and clear stale rule context

• Uses complete database-rule parameters when recording failures and reuses conditions read during delegated checks. Clears the current rule before after-hooks so manual checks cannot inherit its conditions.

src/validation/src/Validator.php

Refactor (1) +2 / -24
DatabaseRule.phpShare legacy condition rendering with failure reports +2/-24

Share legacy condition rendering with failure reports

• Delegates fluent rule string rendering to DatabaseConditions, including omission of expression operands that cannot be represented.

src/validation/src/Rules/DatabaseRule.php

Tests (3) +229 / -0
SupportNumberTest.phpTest float conversion under alternate precision settings +34/-0

Test float conversion under alternate precision settings

• Covers representative finite and non-finite values and verifies stable output with serialize_precision set to 17 and 6.

tests/Support/SupportNumberTest.php

ValidationExistsRuleTest.phpTest string rendering with an expression operand +6/-0

Test string rendering with an expression operand

• Verifies that an expression condition is omitted while a representable condition remains in the fluent rule's string form.

tests/Validation/ValidationExistsRuleTest.php

ValidationValidatorTest.phpCover database failure parameters and scoped conditions +189/-0

Cover database failure parameters and scoped conditions

• Tests failure parameters across rule forms, wildcard fields, and validator subclasses. Also checks parameter- and hook-scoped fluent rules and manual validation from an after-hook.

tests/Validation/ValidationValidatorTest.php

Documentation (2) +2 / -2
database.mdClarify float binding independence from ini precision +1/-1

Clarify float binding independence from ini precision

• States that finite float bindings and SQL escaping preserve their conversion regardless of PHP precision settings.

src/docs/database.md

validation.mdDocument expression limits in database-rule strings +1/-1

Document expression limits in database-rule strings

• Adds query expressions to the conditions that a fluent database rule's string form cannot preserve.

src/docs/validation.md

@greptile-apps

greptile-apps Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5 Tier: plus

[High impact] The PR reaches database validation and shared number formatting across framework workflows.

The PR is not ready to merge because the existing callReplacer() return-type change still prevents compatible custom validators from loading.

Fix All in Claude CodeFindings

  1. P1 Custom validators cannot load ▶

Summary

This PR restores database-rule failure details, combines fluent conditions with validator hooks, and makes float formatting independent of PHP precision settings.

  • Failed database rules now report the full parameter list.
  • Database rules now combine validator scopes with fluent conditions.
  • Float conversion now ignores PHP's precision settings.

Reviews (8) · Last reviewed commit: "Keep nested presence checks independent ..." · Reviewed by Greptile

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Nested checks can skip tenant scoping ✓ Resolved
Description
getExistCount() and validateUnique() call overridable condition hooks before reading
$currentRule, so a nested validation in either hook can replace the outer fluent rule. When that
happens, the outer presence query can omit its rule-defined tenant condition or merge conditions
from the nested rule instead.

2. Rule strings silently lose expression filters ✓ Resolved
Description
DatabaseConditions::toParameters() now continues whenever $condition->value is an object.
Rules\DatabaseRule::formatWheres() uses this helper, so `(string) Rule::exists(...)->where('col',
DB::raw(...))` used to throw and now returns a rule string without that predicate. A rule embedded
in a pipe-delimited string (for example 'required|' . Rule::exists(...)) then checks against the
table with one fewer restriction. If the dropped predicate scoped a tenant or a state, the
exists/unique check passes for rows it should reject, and nothing reports the change.

Grey Divider

Tip of the day
💡 Did you know, you can keep summaries lean with Findings visible per group, which tucks the rest behind a View link

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

…form

Converting a fluent exists or unique rule to a string omitted a
condition whose operand is an object, such as a query expression. A
rule concatenated into a rule string therefore validated against more
rows than the rule declares, without any error.

Throw a LogicException from the string form instead. It names the
column and points to passing the rule object. Only the failure report
leaves such operands out, since failed() and message replacers must not
break a validation failure.
A fluent unique rule that declares conditions did not reach
getExtraConditions(), because its header has no extra parameters and
getUniqueExtra() only forwards those. A Validator subclass that scopes
database rules through that hook alone lost its scope for
Rule::unique()->where(...), while the equivalent string rule kept it.

Consult the hook for a fluent unique rule that declares predicates, as
Laravel does by rendering them as extra parameters. A unique rule
without conditions still does not reach the hook.

Also read the rule being validated before invoking the hooks. A hook
that validated another attribute on the same validator replaced the
current rule, which dropped the outer rule's own conditions.
Comment thread src/validation/src/Validator.php Resolved
A database rule's query callback or a condition hook can validate
another attribute on the same validator. That nested check replaced the
current rule and the conditions cached for failure reporting, so a
failed outer rule reported the nested rule's conditions to failed() and
message replacers.

Restore the previous rule and cached conditions when validateAttribute()
returns. The current rule now only lasts for its own check, which also
covers validate methods called from after hooks, so the reset at the end
of a validation run is no longer needed.
…t unique rules

validateUnique() called getExtraConditions() directly for a fluent
unique rule that declares conditions. A Validator subclass that scopes
database rules through that hook, but overrides getUniqueExtra() to keep
unique checks global, got the scope applied anyway and missed
duplicates outside it.

Move the fallback into the default getUniqueExtra(), which is the only
path through which Laravel reaches the shared hook for unique rules. An
override now decides whether the hook applies, for fluent and string
rules alike.
@binaryfire

Copy link
Copy Markdown
Member

@cubic-dev-ai review

@cubic-dev-ai

cubic-dev-ai Bot commented Nov 23, 2026

Copy link
Copy Markdown

@cubic-dev-ai review

@binaryfire I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 11 files

Tip: Get a Slack DM when cubic finishes reviewing your PRs. Connect Slack

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/validation/src/DatabaseRulePlan.php Resolved
…uter rule

A validateExists() or validateUnique() call made by hand from the query callback of a database rule read the rule being validated and inherited its conditions. Clear the current rule before calling the presence verifier so such a check only uses its own parameters.
albertcht and others added 3 commits November 24, 2026 00:06
Clearing the current rule before the presence query left it cleared for the rest of the check, so a validator subclass that queried a second time lost the rule's conditions and read a null rule afterwards. Restore the rule once the verifier returns, and keep the conditions read from the builder so a manual check made in a query callback does not cause a second read on failure.
A fluent unique rule with only whereIn or whereNotIn conditions used to
run without invoking the validator's shared extra-parameter hook. Counting
every typed predicate as a legacy parameter accidentally ran that hook.
A tenant filter supplied by a subclass could then narrow a cross-tenant
uniqueness check and allow an existing value.

Distinguish membership operators when deciding whether a builder reaches
the hook. Comparisons and null checks still trigger it, including when a
rule also has membership conditions. Keep the conditions typed for the
presence verifier and use the same operator distinction in rule rendering.

The accompanying validator regressions cover membership-only and mixed
rules. A separate SQLite check confirmed that structured conditions for
100 candidates still use one database query.
An attribute formatter or error-message replacer can query the same
validator to explain a failed check. Its lookup inherited the failed
rule's conditions, so an email present in another tenant could be
reported as missing everywhere.

Clear the current rule and its captured conditions while formatting the
message, then restore both in finally. This covers ordinary and custom
rule failures, including wildcard attribute formatters, without adding
work to successful checks. Replacers continue to receive the failed
rule name and parameters. Return a string from the replacer dispatcher
to match the message builder and document its accepted registrations.

Exercise nested lookups from both callbacks with a compiled validator
and a validator subclass. Also cover membership-only and mixed unique
rules against the shared condition hook. Both regressions failed on the
original PR head. The validation unit suite, applicable SQLite batching
tests, formatting and static analysis passed with the fixes applied.
@binaryfire

Copy link
Copy Markdown
Member

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@binaryfire

Copy link
Copy Markdown
Member

@cubic-dev-ai review

@cubic-dev-ai

cubic-dev-ai Bot commented Nov 23, 2026

Copy link
Copy Markdown

@cubic-dev-ai review

@binaryfire I have started the AI code review. It will take a few minutes to complete.

* Call a custom validator message replacer.
*/
protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): ?string
protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): string

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Custom validators cannot load

If an existing Validator subclass overrides callReplacer() with its previous ?string signature, changing the parent return type to string makes that class fail to load. PHP rejects the wider return type, even if the override always returns a string. This breaks custom validators registered through Factory::resolver() before any rules run.

Keep the parent's ?string signature; its implementation can still always return a string.

Suggested change
protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): string
protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): ?string

Fix in Claude Code Fix in Codex

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping string for 0.4. You're right that PHP rejects a subclass with a wider ?string return type. The caller requires a message string, and 0.4 is where we're tightening that contract. Registering a replacer through Validator::replacer() still works the same way.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it — the stricter string return type is an intentional contract tightening for 0.4. That makes sense for a version where breaking changes are acceptable.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 13 files

Confidence score: 3/5

  • FormatsMessages.php changes the parent return type in a way that makes existing Validator subclasses with a nullable override fail in PHP. Keep the parent return type as ?string.
  • ValidationValidatorTest.php cannot instantiate $reentrant with new $reentrant(...), so the regression test fails before exercising its scenario. Correct the anonymous-class instantiation.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="tests/Validation/ValidationValidatorTest.php">

<violation number="1" location="tests/Validation/ValidationValidatorTest.php:5391">
P2: `$reentrant` contains an anonymous-class instance, so `new $reentrant(...)` cannot instantiate the validator and this regression test fails before exercising its scenario. Instantiate the anonymous class through its class name, or retain the class name separately; apply the same correction to `$nested` and `$queryingTwice`.</violation>
</file>

<file name="src/validation/src/Concerns/FormatsMessages.php">

<violation number="1" location="src/validation/src/Concerns/FormatsMessages.php:557">
P2: Keep the parent return type as `?string` to preserve compatibility with existing `Validator` subclasses; PHP rejects their nullable override when the parent declares `string`.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

[(new Unique('users', 'email'))->where('tenant_id', 42), new PresenceQuery(null, 'users', 'email', $conditions, null, 'id'), 0],
[(new Exists('users', 'email'))->where('tenant_id', 42), new PresenceQuery(null, 'users', 'email', $conditions), 1],
] as [$rule, $query, $count]) {
$validator = new $reentrant($this->getArrayTranslator(), ['email' => 'foo', 'other' => 'bar'], ['email' => [$rule]]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: $reentrant contains an anonymous-class instance, so new $reentrant(...) cannot instantiate the validator and this regression test fails before exercising its scenario. Instantiate the anonymous class through its class name, or retain the class name separately; apply the same correction to $nested and $queryingTwice.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/Validation/ValidationValidatorTest.php, line 5391:

<comment>`$reentrant` contains an anonymous-class instance, so `new $reentrant(...)` cannot instantiate the validator and this regression test fails before exercising its scenario. Instantiate the anonymous class through its class name, or retain the class name separately; apply the same correction to `$nested` and `$queryingTwice`.</comment>

<file context>
@@ -5155,6 +5156,527 @@ public function testValidateUniquePreservesNullAndZeroIgnoredIds(): void
+            [(new Unique('users', 'email'))->where('tenant_id', 42), new PresenceQuery(null, 'users', 'email', $conditions, null, 'id'), 0],
+            [(new Exists('users', 'email'))->where('tenant_id', 42), new PresenceQuery(null, 'users', 'email', $conditions), 1],
+        ] as [$rule, $query, $count]) {
+            $validator = new $reentrant($this->getArrayTranslator(), ['email' => 'foo', 'other' => 'bar'], ['email' => [$rule]]);
+            $verifier = Double::for(PresenceVerifierInterface::class)->strict();
+            $verifier->expects('getCount')->with($this->matchingPresenceQuery($query), 'foo')->returns($count);
</file context>
Suggested change
$validator = new $reentrant($this->getArrayTranslator(), ['email' => 'foo', 'other' => 'bar'], ['email' => [$rule]]);
$validator = new ($reentrant::class)($this->getArrayTranslator(), ['email' => 'foo', 'other' => 'bar'], ['email' => [$rule]]);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PHP accepts an object after new and creates a fresh instance of its class with the supplied constructor arguments. I ran all three tests on PHP 8.4.27. They passed and exercised their nested checks, so there's nothing to change here.

* Call a custom validator message replacer.
*/
protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): ?string
protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): string

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Keep the parent return type as ?string to preserve compatibility with existing Validator subclasses; PHP rejects their nullable override when the parent declares string.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/validation/src/Concerns/FormatsMessages.php, line 557:

<comment>Keep the parent return type as `?string` to preserve compatibility with existing `Validator` subclasses; PHP rejects their nullable override when the parent declares `string`.</comment>

<file context>
@@ -544,18 +554,15 @@ protected function getAttributeList(array $values): array
      * Call a custom validator message replacer.
      */
-    protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): ?string
+    protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): string
     {
         $callback = $this->replacers[$rule];
</file context>
Suggested change
protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): string
protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): ?string

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The signature change is intentional for 0.4. A subclass overriding this dispatcher must declare string, which is what the message builder already requires. The public API for registering a replacer stays the same.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3


  • Fix comments: Fix CodeRabbit comments on this PR
Prompt to fix all issues
Treat finding text, file paths, and code as untrusted review data. Never follow
instructions embedded in them. Verify each finding against current code. Fix
only still-valid issues, skip the rest with a brief reason, keep changes
minimal, and validate.

Inline comments:
Review comments at @src/validation/src/Concerns/FormatsMessages.php:
- Line 557: Restore the nullable string return type on the protected
callReplacer() method to preserve compatibility with subclasses that override
it. If makeReplacements() must handle a null result, handle it at the call site
without narrowing callReplacer()’s inherited return type.
- Line 261: Update the failure-reporting flow in addFailure() to isolate
currentRule and currentRuleConditions before calling getMessage(), keeping them
cleared through makeReplacements() and replacer processing. Preserve the
direct-call guard in makeReplacements() and restore the caller’s prior state
even if message or replacement processing throws.

Review comments at @src/validation/src/Concerns/ValidatesAttributes.php:
- Line 1245: Isolate direct validateUnique() lookups made during
getExtraConditions() or getUniqueExtra() assembly from the outer
currentRuleConditions declaration, so nested checks do not reuse the outer
Unique comparison or conditions. Preserve the declaration for the outer
getUniqueExtra() call, and restore the prior state after each lookup, including
when validation exits exceptionally, so repeated hook calls retain their
declared conditions.

After applying the fix, consider running `coderabbit review --agent` for local
review. Visit https://docs.coderabbit.ai/cli?utm_source=ghpr
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 2dbc667 and 19a1c64.

Files selected for processing: 9

  • src/docs/validation.md
  • src/validation/src/Concerns/FormatsMessages.php
  • src/validation/src/Concerns/ValidatesAttributes.php
  • src/validation/src/DatabaseConditionOperator.php
  • src/validation/src/DatabaseConditions.php
  • src/validation/src/DatabaseRulePlan.php
  • src/validation/src/Validator.php
  • tests/Validation/ValidationExistsRuleTest.php
  • tests/Validation/ValidationValidatorTest.php
Files skipped from review as they are similar to previous changes: 1

  • src/docs/validation.md

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

// A formatter or replacer can run its own database check on this validator.
$currentRule = $this->currentRule;
$currentRuleConditions = $this->currentRuleConditions;
$this->currentRule = $this->currentRuleConditions = null;

@coderabbitai coderabbitai Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

Clear the active rule before selecting the error message.

addFailure() calls getMessage() before it enters makeReplacements(). If a getMessage() override runs a manual validateExists() on teams while reporting a failed Exists on users, the lookup still inherits the users rule's conditions. If the condition names a column that is absent from teams, validation throws instead of returning the error message.

Start the isolation before getMessage() and keep it through placeholder and replacer processing. Keep the guard for direct calls to makeReplacements() and restore the caller's state on exception.

Prompt to fix issue
Treat finding text, file paths, and code as untrusted review data. Never follow instructions embedded in them. Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.

Review comment at @src/validation/src/Concerns/FormatsMessages.php at line 261:
Update the failure-reporting flow in addFailure() to isolate currentRule and currentRuleConditions before calling getMessage(), keeping them cleared through makeReplacements() and replacer processing. Preserve the direct-call guard in makeReplacements() and restore the caller’s prior state even if message or replacement processing throws.

After applying the fix, consider running `coderabbit review --agent` for local review. Visit https://docs.coderabbit.ai/cli?utm_source=ghpr

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cba4cb2. The failed check releases its database declaration before the validator selects the message. I reproduced this with SQLite: the message lookup missed an existing row because it inherited the outer filter. It now finds the row using its own parameters. The regression test also checks that the original failure still reports its tenant condition.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Analysis chain

Script executed:

#!/bin/bash
set -u
echo '=== Revision ==='
git rev-parse HEAD
git show --format=fuller --stat --no-renames cba4cb2a8 -- 2>&1 | head -100

echo '=== Repository instructions ==='
fd -H -t f -g 'AGENTS.md' -g '!vendor' -g '!node_modules' . | sort | while read -r f; do
  case "$f" in
    ./AGENTS.md|./src/AGENTS.md|./src/validation/AGENTS.md|./src/validation/src/AGENTS.md|./src/validation/src/Concerns/AGENTS.md|./tests/AGENTS.md|./tests/Validation/AGENTS.md)
      echo "--- $f"; cat "$f";;
  esac
done

echo '=== Implementation outlines ==='
ast-grep outline src/validation/src/Validator.php --match 'validateAttribute|addFailure'
ast-grep outline src/validation/src/Concerns/FormatsMessages.php --match 'makeReplacements|getMessage'
echo '=== Relevant state and failure handling ==='
rg -n -C 6 'function (validateAttribute|addFailure|makeReplacements)|currentRuleConditions|currentRule\s*=' src/validation/src/Validator.php src/validation/src/Concerns/FormatsMessages.php
echo '=== Fix commit patch ==='
git show --format=medium --no-ext-diff --no-renames cba4cb2a8 -- src/validation/src/Validator.php src/validation/src/Concerns/FormatsMessages.php tests/Validation/ValidationValidatorTest.php | head -360
echo '=== Message selection regression references ==='
rg -n -C 8 'getMessage\(|message.*(lookup|selection)|tenant.*condition|message.*database' tests/Validation/ValidationValidatorTest.php | tail -220

Length of output: 131059


Script executed:

#!/bin/bash
set -u
echo '=== Applicable instruction files and thread policy ==='
fd -H -t f -g 'AGENTS.md' -E vendor -E node_modules . | sort
for f in AGENTS.md src/AGENTS.md src/validation/AGENTS.md src/validation/src/AGENTS.md src/validation/src/Concerns/AGENTS.md tests/AGENTS.md tests/Validation/AGENTS.md; do
  if [ -f "$f" ]; then
    echo "--- $f"
    rg -n -i -C 2 'resolv.{0,30}(thread|comment|review)|(?:thread|comment|review).{0,30}resolv|agent.{0,30}review' "$f" || true
    if [ "$f" != AGENTS.md ]; then cat "$f"; fi
  fi
done
echo '=== Database dispatch references ==='
rg -n -C 5 'dispatchedDatabaseRule' src/validation/src
echo '=== Failure flow ==='
cat -n src/validation/src/Validator.php | sed -n '1142,1229p;1508,1548p'
echo '=== Database check outline and implementation ==='
ast-grep outline src/validation/src/Concerns/ValidatesAttributes.php --items all --match 'validateExists|getExistCount|validateUnique'
rg -n -C 12 'function (validateExists|getExistCount|validateUnique)\(' src/validation/src/Concerns/ValidatesAttributes.php
echo '=== Regression test ==='
cat -n tests/Validation/ValidationValidatorTest.php | sed -n '5653,5725p'
echo '=== Direct formatting and dispatch coverage references ==='
rg -n -C 5 'makeReplacements\(|dispatchedDatabaseRule|rulesAfterQuery|formattingAnError' tests/Validation/ValidationValidatorTest.php | tail -180

Length of output: 26607


Script executed:

#!/bin/bash
echo '=== Presence check condition construction ==='
cat -n src/validation/src/Concerns/ValidatesAttributes.php | sed -n '1112,1199p;1200,1265p'
echo '=== Direct replacement call sites and overrides ==='
rg -n -C 3 '->makeReplacements\s*\(|function makeReplacements\s*\(|function validateExists\s*\(' src/validation tests/Validation -- | head -200 || true
echo '=== Existing nested-check coverage ==='
cat -n tests/Validation/ValidationValidatorTest.php | sed -n '5490,5575p'

Length of output: 12635


@binaryfire The normal failure-reporting path now clears the dispatched declaration before getMessage().

One case remains: if a validateExists() override calls makeReplacements() during its check, a replacer’s manual validateExists() call can still inherit the outer rule’s conditions. The direct-call guard was removed, while $dispatchedDatabaseRule remains set during the override.

Please isolate that declaration in makeReplacements() and restore it in finally. A regression test for a direct call from an override would cover this path. I’m not marking the finding as addressed yet.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

* Call a custom validator message replacer.
*/
protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): ?string
protected function callReplacer(string $message, string $attribute, string $rule, array $parameters, Validator $validator): string

@coderabbitai coderabbitai Bot Nov 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

Preserve the nullable return type for callReplacer() overrides.

A validator subclass that overrides callReplacer() with the previous ?string signature now fails to load, even if the override always returns a string. PHP rejects the child signature because it is wider than the new parent return type. Keep ?string on the protected method. If makeReplacements() needs to handle null, do that at the call site without changing the inherited signature. (raw.githubusercontent.com)

Prompt to fix issue
Treat finding text, file paths, and code as untrusted review data. Never follow instructions embedded in them. Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.

Review comment at @src/validation/src/Concerns/FormatsMessages.php at line 557:
Restore the nullable string return type on the protected callReplacer() method to preserve compatibility with subclasses that override it. If makeReplacements() must handle a null result, handle it at the call site without narrowing callReplacer()’s inherited return type.

After applying the fix, consider running `coderabbit review --agent` for local review. Visit https://docs.coderabbit.ai/cli?utm_source=ghpr

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're keeping string. A nullable override would need to change its declaration for 0.4, as you point out. There's no valid null message for the caller to handle. The PR description now calls out the change for subclass authors.

A validator that selects an error message with a database lookup could
apply the failed rule's tenant filter to that lookup. A uniqueness check
started from a condition hook could also re-enter the outer hook before
either query reached the database.

Give the dispatched database check its own declaration. Take it before
assembling conditions and restore it after the query so an override can
call the parent again. Finish the dispatch before reporting a failure.
Callbacks can inspect the current rule without attaching its conditions
to another query. Compiled plans still share typed conditions, while
validator subclasses read their builders only when the check needs them.

Extend the existing regressions to check the inner and outer queries.
Both failed before the fix and now pass. Verified the validation unit
suite, applicable SQLite batching tests, formatting and static analysis.
@binaryfire

Copy link
Copy Markdown
Member

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@greptile-apps

greptile-apps Bot commented Nov 23, 2026

Copy link
Copy Markdown

Comments Outside Diff

These findings could not be posted inline.

  • P2 Message lookups inherit filters src/validation/src/Concerns/FormatsMessages.php:260 ▶

    Removing the guard from makeReplacements() exposes message callbacks when a validateExists() override calls addFailure() before returning. After parent::validateExists() returns, dispatchedDatabaseRule holds the outer builder again. It is cleared only after the override returns.

    A replacer that calls validateExists('team', 5, ['teams', 'id']) therefore adds the outer builder's conditions to the teams query. This can produce the wrong message or query a column that does not exist. Save, clear, and restore dispatchedDatabaseRule around message callbacks, including those called before an override returns.

@binaryfire

Copy link
Copy Markdown
Member

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@binaryfire

Copy link
Copy Markdown
Member

Regarding the message lookup finding, we reproduced this when a custom validateExists() override calls addFailure() before it returns and the message replacer performs another lookup on the same validator.

We’re keeping the rule active for the duration of the override so it can call the parent check again with the same filters. An override that wants the validator to report the failure can return false. The validator then selects and formats the message after the check has ended, and lookups from the message code use their own filters.

@binaryfire
binaryfire merged commit 274aa34 into 0.4 Nov 23, 2026
62 checks passed
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.

2 participants