VOOZH about

URL: https://deepwiki.com/hypervel/validation/7-message-system

⇱ Message System | hypervel/validation | DeepWiki


Loading...
Menu

Message System

The Message System is responsible for generating, retrieving, formatting, and customizing validation error messages. It implements a sophisticated 4-tier message lookup strategy with wildcard matching, placeholder replacement, and context-aware formatting to ensure that validation failures produce clear, customizable error messages.

This document covers the overall architecture and mechanisms of message generation. For detailed information about the lookup priority system and formatting pipeline, see Message Retrieval and Formatting. For guidance on defining custom messages and implementing custom replacers, see Custom Messages and Placeholders.

Overview

The message system is implemented primarily in the FormatsMessages trait src/Concerns/FormatsMessages.php13 which is used by the Validator class. It integrates with the translation system from hypervel/translation to provide multilingual support and leverages the ReplacesAttributes trait for attribute name transformation.

Key responsibilities:

  • Message Retrieval: Searches through multiple sources (inline, translator, defaults) to find the appropriate error message
  • Type Detection: Determines whether an attribute is numeric, array, file, or string to select appropriate size messages
  • Placeholder Replacement: Substitutes placeholders like :attribute, :input, :index, :position with actual values
  • Displayable Formatting: Converts technical attribute names and values into human-readable representations
  • Custom Replacers: Supports custom replacement logic for rule-specific placeholders
  • Wildcard Matching: Enables pattern-based message definitions for arrays and nested attributes

Sources: src/Concerns/FormatsMessages.php1-486

Message System Architecture

The following diagram shows the high-level architecture of the message system, mapping natural language concepts to code entities:


Sources: src/Concerns/FormatsMessages.php13-486

Message Retrieval Process

The message retrieval process follows a strict 4-tier priority system implemented in the getMessage() method src/Concerns/FormatsMessages.php20-73 Each tier is checked in order until a message is found.

4-Tier Lookup Priority


Sources: src/Concerns/FormatsMessages.php20-73

Tier 1: Inline Messages

Inline messages are defined in the $customMessages property passed to the validator. The getInlineMessage() method src/Concerns/FormatsMessages.php78-85 retrieves them, handling special cases for size rules which can have type-specific messages.

The getFromLocalArray() method src/Concerns/FormatsMessages.php90-130 implements wildcard pattern matching, allowing messages like:

  • items.*.name.required - matches any item index
  • addresses.*.zip - matches any address index

Key lookup keys (in order):

  1. {attribute}.{rule} - e.g., email.required
  2. {rule} - e.g., required
  3. {attribute} - e.g., email (for array of rule messages)

Sources: src/Concerns/FormatsMessages.php78-130

Tier 2: Custom Translator Messages

Custom translator messages are retrieved via getCustomMessageFromTranslator() src/Concerns/FormatsMessages.php135-161 which queries the translation system for keys like:

  • validation.custom.{attribute}.{rule} - e.g., validation.custom.email.required
  • For size rules: validation.custom.{attribute}.{rule}.{type} - e.g., validation.custom.age.max.numeric

The getWildcardCustomMessages() method src/Concerns/FormatsMessages.php166-176 supports wildcard patterns in translation files, enabling messages like:


Sources: src/Concerns/FormatsMessages.php135-176

Tier 3: Size-Specific Messages

Size rules (min, max, between, size, etc.) require different messages based on the attribute type. The getSizeMessage() method src/Concerns/FormatsMessages.php181-193 retrieves type-specific messages:

  • validation.{rule}.numeric - e.g., "The :attribute must be at least :min"
  • validation.{rule}.file - e.g., "The :attribute must be at least :min kilobytes"
  • validation.{rule}.string - e.g., "The :attribute must be at least :min characters"
  • validation.{rule}.array - e.g., "The :attribute must have at least :min items"

Sources: src/Concerns/FormatsMessages.php181-193

Tier 4: Default Messages

Default messages are retrieved from the translation system using the key validation.{rule}. If not found in the translator, the system falls back to the $fallbackMessages array property src/Concerns/FormatsMessages.php68-72

Sources: src/Concerns/FormatsMessages.php62-72

Attribute Type Detection

The getAttributeType() method src/Concerns/FormatsMessages.php198-209 determines the data type of an attribute to select appropriate size-specific messages. It uses a match expression to classify attributes:

PriorityConditionType ReturnedExample
1Has numeric rule (Integer, Numeric)"numeric"Age field with numeric rule
2Has Array or List rule"array"Items field with array rule
3Value is UploadedFile instance"file"Avatar upload field
4Default"string"All other fields

This classification is critical for size rules, ensuring that validation messages match the attribute context (e.g., "at least 5 kilobytes" for files vs. "at least 5 characters" for strings).

Sources: src/Concerns/FormatsMessages.php198-209

Placeholder Replacement System

After a message is retrieved, the makeReplacements() method src/Concerns/FormatsMessages.php214-233 substitutes placeholders with actual values. The replacement process follows this sequence:


Sources: src/Concerns/FormatsMessages.php214-233

Standard Placeholders

PlaceholderReplacementMethodExample
:attribute, :ATTRIBUTE, :AttributeDisplayable attribute namereplaceAttributePlaceholder() 313-320email → "email address"
:inputDisplayable valuereplaceInputPlaceholder() 400-409"test" → "test"
:indexZero-based array indexreplaceIndexPlaceholder() 325-332items.2.name → "2"
:positionOne-based array positionreplacePositionPlaceholder() 337-345items.2.name → "3"

Sources: src/Concerns/FormatsMessages.php313-409

Advanced Index/Position Placeholders

The system supports multiple numeric segments in nested arrays using ordinal word placeholders src/Concerns/FormatsMessages.php350-395:

  • :first-index, :second-index, :third-index, etc.
  • :first-position, :second-position, :third-position, etc.

For example, with attribute items.0.tags.2, you can use:

  • :first-index → "0"
  • :second-index → "2"
  • :first-position → "1"
  • :second-position → "3"

The numberToIndexOrPositionWord() method src/Concerns/FormatsMessages.php381-395 maps numbers 1-10 to ordinal words (first, second, third, etc.).

Sources: src/Concerns/FormatsMessages.php350-395

Displayable Names and Values

The message system converts technical attribute names and values into human-readable representations.

Displayable Attribute Names

The getDisplayableAttribute() method src/Concerns/FormatsMessages.php238-272 searches multiple sources for attribute display names, in order:


Sources: src/Concerns/FormatsMessages.php238-272

Wildcard Support for Attribute Names

The getAttributeFromLocalArray() method src/Concerns/FormatsMessages.php289-308 supports wildcard patterns for attribute names:


The pattern matching converts * to regex ([^.]*) and performs case-insensitive matching.

Sources: src/Concerns/FormatsMessages.php289-308

Displayable Values

The getDisplayableValue() method src/Concerns/FormatsMessages.php414-439 converts attribute values into human-readable strings:

Value TypeDisplay FormatSource
Custom value mappingDefined in $customValuesLine 416-418
Array"array"Line 420-422
Translation keyvalidation.values.{attribute}.{value}Line 424-428
Boolean true"true"Line 430-432
Boolean false"false"Line 430-432
Null"empty"Line 434-436
Other scalarCast to stringLine 438

Sources: src/Concerns/FormatsMessages.php414-439

Custom Message Replacers

The system provides an extension mechanism for custom placeholder replacement logic through the $replacers property on the validator.

Replacer Execution Flow


Sources: src/Concerns/FormatsMessages.php214-233

Replacer Types

The callReplacer() method src/Concerns/FormatsMessages.php461-473 supports two types of custom replacers:

  1. Closure Replacers: Direct callable functions

    
    
  2. Class-Based Replacers: String references to class methods

    • Format: "ClassName" or "ClassName@method"
    • Default method name: replace
    • Resolved via callClassBasedReplacer() Line 478-484
    • Uses container to instantiate the class

Sources: src/Concerns/FormatsMessages.php461-484

Integration with ValidatesAttributes

Built-in validation methods in the ValidatesAttributes trait often include corresponding replacer methods. For example:

  • validateMin()replaceMin()
  • validateBetween()replaceBetween()
  • validateSame()replaceSame()

These methods are automatically called by makeReplacements() when they exist src/Concerns/FormatsMessages.php228-230

Sources: src/Concerns/FormatsMessages.php228-230

Usage in Validator Class

The FormatsMessages trait is used by the Validator class throughout the validation lifecycle:

StageMethod UsagePurpose
Rule failuregetMessage(attribute, rule)Retrieve appropriate error message
Message assemblymakeReplacements(message, attribute, rule, params)Replace placeholders with values
Error collectionAdds to MessageBagAccumulates formatted errors
ResponseReturns MessageBagProvides all validation errors

The validator maintains several arrays that the message system accesses:

  • $customMessages - Inline messages provided by developer
  • $customAttributes - Custom attribute display names
  • $customValues - Custom value display names
  • $fallbackMessages - Default fallback messages
  • $replacers - Custom placeholder replacers

Sources: src/Concerns/FormatsMessages.php13-486

Key Design Patterns

The message system employs several design patterns:

  1. Priority Chain: 4-tier lookup with clear fallback hierarchy
  2. Template Method: makeReplacements() defines replacement sequence, subclasses can override individual replacers
  3. Strategy Pattern: Custom replacers allow injecting custom replacement logic
  4. Decorator Pattern: Messages are progressively enhanced through replacement stages
  5. Wildcard Matching: Pattern-based message and attribute name lookup for flexibility

These patterns ensure extensibility while maintaining backward compatibility and predictable behavior.

Sources: src/Concerns/FormatsMessages.php1-486