Improve validation rules, database batching and numeric correctness

Merged
BI
8d ago
+5462-1862

Database validation now keeps typed conditions through declaration, planning, caching and execution. This gives Hypervel's compiled validator and database batching one consistent representation, improves JSON support, and fixes correctness problems without giving up the existing optimizations.

Design

  • Replace encoded database conditions with ordered, typed predicates. JSON booleans, literal values such as NULL and !value, repeated columns, and whereIn / whereNotIn no longer need generated callbacks to preserve their meaning. These declarations can participate in batching and plan caching; explicit user callbacks retain their execution-time behavior.
  • Pass each presence check's connection, table, column and conditions in a stateless PresenceQuery. A shared verifier no longer holds a mutable current connection that nested validation or another coroutine can replace.
  • Capture reusable declarations once per validation run, preserve subclass hooks, and keep only detached data in the bounded plan cache. Data attributes and rule comparison use the same declarations, avoiding unnecessary string rendering and reconstruction.
  • Keep caller-owned mutable rule builders fresh when resolved through the container. Reused custom rules also clear their previous validation messages between runs.

Laravel's string-based condition format is convenient for handwritten rules, but it loses types and needs special handling for values that resemble its control tokens. Hypervel translates that syntax at the parsing boundary and uses typed conditions internally. This is a better fit for its planner, cache and long-lived workers, while preserving ordinary string rules and familiar fluent calls.

Correctness and consistency

  • Give in, not_in, contains and doesnt_contain one comparison policy: booleans match 0 / 1 and their string forms, null stays distinct from an empty string, and floats retain their precision. Array not_in rejects any forbidden member instead of inverting an all-members check.
  • Preserve float precision through numeric validation, decimal casts, PDO string bindings and query diagnostics. Decimal casts still apply their requested scale; applications should round explicitly when decimal equality depends on rounding.
  • Correct JSON boolean comparisons, including MariaDB's coercion behavior. JSON whereIn / whereNotIn preserve native boolean meaning while retaining indexable scalar expressions. Presence checks count precise and typed candidates consistently.
  • Fix email-length checks, regex execution-error handling, decimal matching, missing-value detection and repeated-rule messages. Preserve reusable query selections when compiling PostgreSQL and SQLite row-identifier writes.
  • Make inherited first-class callables use the concrete class's contextual bindings, consistently with constructors and array callables, including nested calls returning to an earlier class. Extend PHPStan's existing worker-state checks to services injected into FormRequest hooks, respecting custom dispatch and method bindings.

Laravel extension differences

The common Rule::exists(), unique(), where(), ignore() and membership-builder APIs remain familiar. The extension contracts change where preserving the encoded representation would complicate the typed design:

  • Custom presence verifiers accept PresenceQuery; connection selection is part of that value rather than a mutable setConnection() call. Condition application receives typed predicates, and prepareValue() receives the column before the value.
  • Database-rule subclasses customize queryConditions() and queryParameters(). Membership-rule subclasses customize toArray(). Their final __toString() methods render those declarations, and getRules() retains the builder objects.
  • Declarations are captured at the start of a validation run. Use explicit using() callbacks for database conditions that must change during a run.

These changes make custom extensions describe their intent directly instead of reproducing string encoding rules. The validation guide and Laravel porting guide explain the adaptation, comparison behavior and concrete-class contextual bindings.

Benchmarks

Most measured workloads remain close to the previous implementation. The major improvement is structured database conditions: the 100-item workload drops from 100 queries to one, and from 34.53 ms to 5.01 ms—about 6.9× faster. Data class-rule collections also improve by about 8%.

WorkloadBeforeAfterQueries before → after
Flat form0.052 ms0.054 ms0 → 0
Conditional fields39.16 ms38.03 ms0 → 0
Fluent membership, 500 items10.04 ms9.97 ms0 → 0
Flat database form0.715 ms0.739 ms3 → 3
Float database candidates, 100 items4.07 ms4.26 ms1 → 1
Structured database conditions, 100 items34.53 ms5.01 ms100 → 1
Data attributes, 1,000 items56.79 ms55.90 ms1 → 1
Data class rules, 1,000 items99.89 ms91.54 ms1 → 1

These are short paired local runs with matching dependencies and harnesses, PHP 8.4.26, Swoole 6.3.0RC1, CLI opcache enabled and JIT disabled. The slower database rows have overlapping sample ranges; the flat form adds about 1.7 µs. Neither revision grew its retained heap between the measured cache-saturation passes; the new implementation retained about 0.28 MB more at saturation. The old revision failed three correctness scenarios, which are excluded from speed comparisons.

Standalone harnesses under tests/Benchmarks/Validation and tests/Benchmarks/Data replace the application-facing validation:benchmark command. tests/Benchmarks/Validation/results.md records the measurements and spread. Regression coverage checks correctness, query counts, declaration reuse and cache ownership without timing assertions.

[!NOTE]

Fix numeric precision, validation rule declarations, and database presence queries

  • Floats are now converted with Number::toString across validation rules, message parameters, database bindings (PdoConnection.php), escaping, decimal casts, and query exception messages, so high-precision values survive round trips instead of being lost to PHP string casting
  • Validation rules no longer rely on __toString for parameterization: membership rules (In, NotIn, Contains, DoesntContain, ArrayKeys) export declarations via toArray(), and database rules are captured as DatabaseRulePlan objects at compile time, then read once per run
  • The presence-verifier API is reworked around typed PresenceQuery, DatabaseCondition, and DatabaseConditions objects; batched presence checks group by query shape, and DatabasePresenceVerifier no longer stores mutable connection state
  • ValidationData.extractDataFromPath uses an UndefinedValue marker (moved to Hypervel\Support) so a real value matching the old sentinel string is no longer treated as a missing path; not_regex now fails when the regex errors
  • Adds JSON boolean membership support (JsonBooleanIn) to whereIn with per-driver grammar compilation, fixes SQLite/Postgres row-identifier compilation to clone the builder, and makes Container.call resolve contextual bindings against the concrete called class
  • Behavioral Change: presence-verifier interface signatures changed to PresenceQuery arguments; getPresenceVerifier() no longer accepts a connection; Exists/Unique __toString is final; membership rules (in, notIn, contains, doesntContain) use a new shared typed comparison policy where null, booleans, and floats are distinct from their string forms

Macroscope summarized 5e74f78.