VOOZH about

URL: https://deepwiki.com/hypervel/validation/3.1-validator-class

⇱ Validator Class | hypervel/validation | DeepWiki


Loading...
Menu

Validator Class

This document provides detailed documentation of the Validator class, which serves as the central orchestrator for all validation operations in the Hypervel Validation package. The Validator manages validation state, coordinates rule execution, accumulates error messages, and provides access to validation results.

For information about the 50+ built-in validation methods, see Built-in Validation Rules. For the complete validation execution flow, see Validation Lifecycle. For message generation specifics, see Message System.


Class Overview

The Validator class is located at src/Validator.php30 and implements the ValidatorContract interface. It uses two major traits to organize its functionality:


Sources: src/Validator.php30-33


Constructor and Initialization

The Validator is instantiated with validation context and configuration:

ParameterTypePurpose
$translatorTranslatorTranslation service for error messages
$dataarrayData under validation
$rulesarrayValidation rules to apply
$messagesarrayCustom error messages (optional)
$attributesarrayCustom attribute names (optional)

Constructor Flow


Sources: src/Validator.php288-305

The constructor performs critical initialization:

  1. Placeholder Hash Generation (src/Validator.php295-297): Creates a unique random hash used to escape dots (.) and asterisks (*) in data keys and rule definitions. This prevents conflicts with dot notation for nested arrays.

  2. Data Parsing (src/Validator.php310-330): The parseData() method recursively processes the data array, replacing . with __dot__<hash> and * with __asterisk__<hash>. This allows literal dots and asterisks in data keys while preserving dot notation for array access.

  3. Rule Expansion (src/Validator.php1050-1064): The setRules() method converts escaped dots in rule keys and calls addRules(), which uses ValidationRuleParser to expand wildcard rules like items.* into explicit rules for each array element.


Core Properties

Validation State Properties


Sources: src/Validator.php62-93

PropertyTypePurpose
$dataarrayData under validation with escaped keys
$initialRulesarrayRules as originally provided
$rulesarrayParsed and expanded rules with escaped keys
$currentRulestring|object|arrayRule currently being validated
$messagesMessageBagAccumulated validation error messages
$failedRulesarrayMap of attribute => [rule => parameters] for failures
$excludeAttributesarrayAttributes to exclude from validated data
$implicitAttributesarrayMap of wildcard patterns to expanded attributes
$distinctValuesarrayCache for "distinct" rule validation

Sources: src/Validator.php47-93

Configuration Properties


Sources: src/Validator.php102-138

PropertyTypePurpose
$customMessagesarrayDeveloper-provided error messages (highest priority)
$fallbackMessagesarrayFallback messages when translation missing
$customAttributesarrayHuman-readable attribute names for messages
$customValuesarrayHuman-readable value representations
$stopOnFirstFailureboolStop validating after first failure
$excludeUnvalidatedArrayKeysboolExclude unvalidated array keys from results
$extensionsarrayCustom validation method extensions
$replacersarrayCustom message placeholder replacers

Sources: src/Validator.php102-138

Dependency Properties

PropertyTypePurpose
$translatorTranslatorTranslation service for messages
$containerContainerInterfaceDI container for resolving extensions
$presenceVerifierPresenceVerifierInterfaceDatabase query handler for exists/unique

Sources: src/Validator.php36-43 src/Validator.php288-289


Rule Classification Arrays

The Validator maintains several arrays that classify rules by their behavior. These affect execution logic throughout the validation lifecycle:


Sources: src/Validator.php145-264

These classifications are used in:


Core Validation Methods

Primary Validation Methods


Sources: src/Validator.php392-449 src/Validator.php554-606

passes(): bool (src/Validator.php392-441)

The primary validation execution method:

  1. Initializes a new MessageBag and resets $distinctValues and $failedRules
  2. Iterates through each attribute's rules
  3. Checks if attribute should be excluded via shouldBeExcluded()
  4. Validates each rule via validateAttribute()
  5. Stops early if $stopOnFirstFailure is true and errors exist
  6. Executes all registered "after" callbacks
  7. Returns true if MessageBag is empty

fails(): bool (src/Validator.php446-449)

Returns the inverse of passes().

validate(): array (src/Validator.php481-486)

Throws ValidationException if validation fails, otherwise returns validated data.

validateWithBag(string $errorBag): array (src/Validator.php493-502)

Same as validate() but sets a named error bag on the exception.

Attribute Validation

validateAttribute(string $attribute, $rule): void (src/Validator.php554-606)

Validates a single rule against an attribute:


Sources: src/Validator.php554-606

Key steps:

  1. Parses the rule string/object into rule name and parameters
  2. Replaces dot placeholders and wildcards in parameters if rule is dependent
  3. Gets the attribute value from $data
  4. Checks uploaded file validity
  5. Determines if rule should be validated via isValidatable()
  6. Routes to either custom rule validation or built-in trait method
  7. Records failure via addFailure() if validation fails

validateUsingCustomRule(string $attribute, mixed $value, Rule $rule): void (src/Validator.php747-796)

Handles validation for rule objects implementing Rule interface:

  1. Replaces placeholders in attribute name
  2. Injects validator reference if rule implements ValidatorAwareRule
  3. Injects data if rule implements DataAwareRule
  4. Calls $rule->passes($attribute, $value)
  5. Records failure and retrieves message if validation fails

Sources: src/Validator.php747-796


Validation State Methods

Determining Validatability

isValidatable($rule, string $attribute, mixed $value): bool (src/Validator.php673-683)

Determines if a rule should be executed for an attribute:


Sources: src/Validator.php673-683

The four conditions:

  1. presentOrRuleIsImplicit() (src/Validator.php688-696): Field must be present OR rule must be implicit (like Required)
  2. passesOptionalCheck() (src/Validator.php710-720): If field has Sometimes rule, it must be present in data
  3. isNotNullIfMarkedAsNullable() (src/Validator.php725-732): If field has Nullable rule and is implicit, field must not be null
  4. hasNotFailedPreviousRuleIfPresenceRule() (src/Validator.php739-742): Database rules (Exists, Unique) skip if attribute already has errors

Determining When to Stop

shouldStopValidating(string $attribute): bool (src/Validator.php801-822)

Determines if validation should stop for an attribute:

  • Returns true if attribute has Bail rule and already has messages
  • Returns true if file upload failed
  • Returns true if attribute has implicit rules and one already failed

Sources: src/Validator.php801-822

shouldBeExcluded(string $attribute): bool (src/Validator.php454-465)

Checks if an attribute is in the $excludeAttributes array or is a child of an excluded attribute.

Sources: src/Validator.php454-465


Data Access Methods

Reading Data

MethodReturn TypePurpose
getData(): arrayarrayReturns the full data array with placeholders
attributes(): arrayarrayAlias for getData()
getValue(string $attribute): mixedmixedGets value for a specific attribute using dot notation

Sources: src/Validator.php987-1018

Writing Data

MethodPurpose
setData(array $data): staticReplaces all data, re-parses, and re-expands rules
setValue(string $attribute, mixed $value): voidSets value for a specific attribute

Sources: src/Validator.php1003-1026


Rule Management Methods

Rule Definition and Access


Sources: src/Validator.php1050-1085

setRules(array $rules): static (src/Validator.php1050-1064)

Replaces all validation rules:

  1. Escapes dots in rule keys
  2. Stores in $initialRules
  3. Clears $rules
  4. Calls addRules()

addRules(array $rules): void (src/Validator.php1069-1085)

Adds rules to existing rules:

  1. Creates ValidationRuleParser instance
  2. Filters conditional rules
  3. Explodes wildcards to explicit attribute names
  4. Merges results into $rules and $implicitAttributes

getRules(): array (src/Validator.php1031-1034)

Returns rules with placeholders still present.

getRulesWithoutPlaceholders(): array (src/Validator.php1039-1045)

Returns rules with placeholders converted back to escaped dots (\.).

Sources: src/Validator.php1031-1045

Rule Queries

hasRule(string $attribute, $rules): bool (src/Validator.php957-960)

Checks if an attribute has any of the specified rules.

getRule(string $attribute, $rules): ?array (src/Validator.php965-982)

Returns [rule, parameters] if attribute has one of the specified rules, otherwise null.

Sources: src/Validator.php957-982

Conditional Rules

sometimes($attribute, $rules, callable $callback): static (src/Validator.php1090-1107)

Conditionally adds rules based on a callback:

  1. Creates Fluent payload from data
  2. For each attribute pattern:
    • Explodes rules (expands wildcards)
    • Invokes callback with payload and iteration data
    • If callback returns true, adds rules via addRules()

Sources: src/Validator.php1090-1107


Validation Result Methods

Retrieving Results


Sources: src/Validator.php481-548 src/Validator.php869-924

Success Methods

MethodReturn TypeDescription
validated(): arrayarrayReturns only validated attributes with placeholders restored
safe(?array $keys): ValidatedInput|arrayValidatedInput|arrayReturns ValidatedInput wrapper or subset of validated data
valid(): arrayarrayReturns all data except attributes with errors

Sources: src/Validator.php507-548 src/Validator.php869-879

Failure Methods

MethodReturn TypeDescription
messages(): MessageBagMessageBagReturns message bag (alias: errors(), getMessageBag())
failed(): arrayarrayReturns $failedRules map
invalid(): arrayarrayReturns only attributes with errors

Sources: src/Validator.php884-924 src/Validator.php929-952

Validated Data Logic

The validated() method (src/Validator.php519-549) implements specific logic:

  1. Runs passes() if not already run
  2. Throws exception if validation failed
  3. Iterates through rules:
    • Skips array/list attributes if excludeUnvalidatedArrayKeys is true and child rules exist
    • Includes only attributes with defined rules
  4. Restores placeholders before returning

Sources: src/Validator.php519-549


Extension System

Adding Custom Validators

The Validator supports three types of extensions:


Sources: src/Validator.php1139-1200 src/Validator.php1385-1429

Extension Methods

MethodPurpose
addExtension(string $rule, $extension)Registers a custom validation method
addImplicitExtension(string $rule, $extension)Registers an implicit custom validator (validates absent fields)
addDependentExtension(string $rule, $extension)Registers a dependent custom validator (references other fields)
addExtensions(array $extensions)Registers multiple custom validators at once

Sources: src/Validator.php1139-1200

Extensions can be:

  • Closures: Called directly with validation parameters
  • Class strings: Resolved from container and method called (format: ClassName@methodName)

Extensions are invoked via __call() magic method when a validate{Rule}() method doesn't exist.

Sources: src/Validator.php1416-1429

Adding Custom Replacers

MethodPurpose
addReplacer(string $rule, $replacer)Registers a custom message placeholder replacer
addReplacers(array $replacers)Registers multiple replacers at once

Sources: src/Validator.php1205-1222

Replacers customize how placeholders are replaced in error messages for specific rules.


Configuration Methods

Message Customization

MethodPurpose
setCustomMessages(array $messages)Merges custom inline messages
setFallbackMessages(array $messages)Sets fallback messages
setAttributeNames(array $attributes)Replaces all custom attribute names
addCustomAttributes(array $attributes)Adds custom attribute names
setValueNames(array $values)Replaces all custom value names
addCustomValues(array $values)Adds custom value names

Sources: src/Validator.php1225-1290

Behavior Configuration

MethodPurpose
stopOnFirstFailure(bool $stop = true)Sets whether to stop on first failure
setImplicitAttributesFormatter(?callable $formatter)Sets formatter for wildcard attribute names
excludeUnvalidatedArrayKeys = trueProperty to exclude unvalidated array keys

Sources: src/Validator.php1129-1262

Callbacks

after($callback): static (src/Validator.php373-387)

Registers callbacks to execute after validation:

  • Accepts single callback, array of callbacks, or array of objects with after() method
  • Callbacks receive the Validator instance as parameter
  • Executed in passes() after all rules validated

Sources: src/Validator.php373-387


Dependency Management

Translator

MethodPurpose
getTranslator(): TranslatorReturns translator instance
setTranslator(Translator $translator)Replaces translator

Sources: src/Validator.php1361-1372

The translator is injected via constructor and used by the FormatsMessages trait to translate error messages.

Presence Verifier

MethodPurpose
getPresenceVerifier(?string $connection): PresenceVerifierInterfaceReturns presence verifier, optionally setting connection
setPresenceVerifier(PresenceVerifierInterface $verifier)Sets presence verifier instance

Sources: src/Validator.php1293-1316

The presence verifier is optional and required only for database validation rules (exists, unique). For details, see Database Integration.

Container

setContainer(ContainerInterface $container): void (src/Validator.php1377-1380)

Sets the PSR-11 container used to resolve class-based extensions.

Sources: src/Validator.php1377-1380


Exception Handling

setException($exception): static (src/Validator.php1335-1346)

Configures which exception class to throw on validation failure:

  • Must extend ValidationException
  • Default is ValidationException::class
  • Throws InvalidArgumentException if invalid class provided

getException(): string (src/Validator.php1323-1326)

Returns the configured exception class name.

Sources: src/Validator.php1323-1346


Helper Methods

Placeholder Management

The Validator uses a unique placeholder system to handle dots and asterisks in attribute names:

MethodPurpose
parseData(array $data): arrayRecursively replaces . and * with placeholders
replacePlaceholders(array $data): arrayRecursively restores placeholders to original characters
replacePlaceholderInString(string $value): stringReplaces placeholders in a single string

Sources: src/Validator.php310-358

The placeholder hash is stored in static property $placeholderHash (src/Validator.php269) and generated once per request.

Parameter Processing

MethodPurpose
replaceDotInParameters(array $params): arrayReplaces escaped dots with placeholder in parameters
replaceDotPlaceholderInParameters(array $params): arrayRestores placeholders to dots in parameters
replaceAsterisksInParameters(array $params, array $keys): arrayReplaces asterisks with actual keys

Sources: src/Validator.php363-368 src/Validator.php653-668

Attribute Management

removeAttribute(string $attribute): void (src/Validator.php470-474)

Removes an attribute from both $data and $rules.

excludeAttribute(string $attribute): void (src/Validator.php859-864)

Adds attribute to $excludeAttributes array.

addFailure(string $attribute, string $rule, array $params): void (src/Validator.php827-854)

Records a validation failure:

  1. Restores placeholders in attribute name
  2. Handles exclude rules specially
  3. Generates and adds error message
  4. Records in $failedRules

Sources: src/Validator.php470-474 src/Validator.php827-864

Wildcard Support

getPrimaryAttribute(string $attribute): string (src/Validator.php639-648)

Given an explicit attribute like items.0.name, returns the wildcard pattern like items.*.name by looking up in $implicitAttributes.

getExplicitKeys(string $attribute): array (src/Validator.php621-632)

Extracts the actual keys that replaced wildcards. For example, given foo.1.bar.spark.baz and pattern foo.*.bar.*.baz, returns [1, 'spark'].

Sources: src/Validator.php621-648


Integration Points

With ValidatesAttributes Trait

The Validator delegates to trait methods for built-in validation rules:


Sources: src/Validator.php599-605

With FormatsMessages Trait

The Validator uses the trait for message generation:


Sources: src/Validator.php846-851

With ValidationRuleParser


Sources: src/Validator.php558 src/Validator.php1074-1075


Usage Patterns

Basic Validation Flow


Sources: src/Validator.php288-305 src/Validator.php392-441

With Custom Configuration


Sources: src/Validator.php1129-1134 src/Validator.php1227-1232 src/Validator.php481-486

With After Callbacks


Sources: src/Validator.php373-387


Summary

The Validator class serves as the central orchestrator for the Hypervel Validation package. It:

  • Manages validation state including data, rules, messages, and failures
  • Coordinates execution between built-in trait methods and custom rule objects
  • Handles complex attribute naming with dots and wildcards through placeholder system
  • Provides flexible configuration for messages, attributes, and behavior
  • Supports extensions for custom validators and message replacers
  • Integrates with external dependencies (Translator, PresenceVerifier, Container)
  • Implements sophisticated rule classification and conditional logic
  • Returns multiple result views (validated, valid, invalid, failed, messages)

The class maintains clear separation of concerns by delegating validation logic to the ValidatesAttributes trait and message formatting to the FormatsMessages trait, while maintaining overall control of the validation lifecycle.

Sources: src/Validator.php1-1431

Refresh this wiki

On this page