VOOZH about

URL: https://deepwiki.com/hypervel/validation/7.1-message-retrieval-and-formatting

⇱ Message Retrieval and Formatting | hypervel/validation | DeepWiki


Loading...
Menu

Message Retrieval and Formatting

This document explains the message retrieval and formatting system implemented in the FormatsMessages trait. This system provides a sophisticated 4-tier message lookup mechanism with fallback behavior and a comprehensive placeholder replacement pipeline.

For information about defining custom messages and implementing custom replacers, see Custom Messages and Placeholders. For details about the broader message system architecture, see Message System.

Overview

The message system consists of two distinct phases:

  1. Message Retrieval: A priority-based lookup system that searches through four tiers of message sources
  2. Message Formatting: A transformation pipeline that replaces placeholders with contextual values

The FormatsMessages trait (src/Concerns/FormatsMessages.php13) implements both phases and is used by the Validator class to generate human-readable error messages when validation rules fail.

Sources: src/Concerns/FormatsMessages.php1-485

Message Lookup Priority System

Four-Tier Lookup Architecture

The message retrieval system follows a strict priority order, searching each tier until a message is found:


Flow Control: The getMessage() method (src/Concerns/FormatsMessages.php20-73) orchestrates this lookup sequence, returning immediately when a message is found at any tier.

Sources: src/Concerns/FormatsMessages.php20-73

Tier 1: Inline Messages

Inline messages have the highest priority and are defined through the $customMessages array passed to the validator instance. These messages allow developers to specify error messages directly in their validation code.

Lookup Method: getInlineMessage() (src/Concerns/FormatsMessages.php78-85)

Key Pattern: {attribute}.{rule} or just {rule}

Inline Message Structure

PatternExampleDescription
{attribute}.{rule}email.requiredSpecific attribute and rule
{rule}requiredAll attributes with this rule
{attribute}emailAll rules for this attribute

For size rules (min, max, size, between), inline messages can be arrays specifying different messages per attribute type:


Wildcard Support: The getFromLocalArray() method (src/Concerns/FormatsMessages.php90-130) supports wildcard patterns in message keys:


The wildcard matching logic (src/Concerns/FormatsMessages.php101-115) converts asterisks to regex patterns and performs pattern matching against the target attribute.

Sources: src/Concerns/FormatsMessages.php78-130

Tier 2: Custom Translator Messages

If no inline message is found, the system queries the translator service using structured keys.

Lookup Method: getCustomMessageFromTranslator() (src/Concerns/FormatsMessages.php135-161)

Key Pattern: validation.custom.{attribute}.{rule}

Translation Key Examples

AttributeRuleTranslation Key
emailrequiredvalidation.custom.email.required
user.namemaxvalidation.custom.user.name.max
items.0integervalidation.custom.items.0.integer

For size rules, the system attempts a type-specific lookup first:

validation.custom.{attribute}.{rule}.{type} // e.g., validation.custom.age.min.numeric
validation.custom.{attribute}.{rule} // fallback

Wildcard Matching in Translator

The getWildcardCustomMessages() method (src/Concerns/FormatsMessages.php166-176) enables wildcard patterns in translation files:


The wildcard matching process:

  1. Extracts all custom messages from validation.custom namespace
  2. Converts to dot notation using Arr::dot()
  3. Compares each key against the search pattern using Str::is()

Sources: src/Concerns/FormatsMessages.php135-176

Tier 3: Size-Specific Messages

Size rules (min, max, size, between, gt, gte, lt, lte) require different messages depending on whether the attribute is a number, file, array, or string.

Lookup Method: getSizeMessage() (src/Concerns/FormatsMessages.php181-193)

Key Pattern: validation.{rule}.{type}

Attribute Type Detection

The getAttributeType() method (src/Concerns/FormatsMessages.php198-209) determines the attribute type using this precedence:


Type Detection Logic (src/Concerns/FormatsMessages.php203-208):


Example Size Messages

For a min:10 rule:

  • Numeric attribute: "The age must be at least 10."
  • Array attribute: "The items must have at least 10 items."
  • File attribute: "The document must be at least 10 kilobytes."
  • String attribute: "The name must be at least 10 characters."

Sources: src/Concerns/FormatsMessages.php181-209

Tier 4: Default Messages

When no custom message is found and the rule is not a size rule (or no size-specific message exists), the system falls back to default messages.

Lookup Method: Direct translator query in getMessage() (src/Concerns/FormatsMessages.php62-66)

Key Pattern: validation.{rule}

Fallback Array: If the translator also has no message, the system checks the $fallbackMessages array (src/Concerns/FormatsMessages.php68-72) as a last resort. This ensures the system always returns a message, even if it's just the translation key itself.

Sources: src/Concerns/FormatsMessages.php62-73

Message Formatting Pipeline

Once a message is retrieved, it passes through a multi-stage formatting pipeline that replaces placeholders with contextual values.


Orchestration Method: makeReplacements() (src/Concerns/FormatsMessages.php214-233)

Sources: src/Concerns/FormatsMessages.php214-233

Standard Placeholder Replacement

:attribute Placeholder

Replaces with the displayable name of the attribute being validated.

Method: replaceAttributePlaceholder() (src/Concerns/FormatsMessages.php313-320)

Variations: Supports case transformations:

  • :attribute → lowercase: "email address"
  • :ATTRIBUTE → uppercase: "EMAIL ADDRESS"
  • :Attribute → title case: "Email Address"

Implementation:


Sources: src/Concerns/FormatsMessages.php313-320

:input Placeholder

Replaces with the displayable representation of the actual value being validated.

Method: replaceInputPlaceholder() (src/Concerns/FormatsMessages.php400-409)

Constraint: Only replaces for scalar or null values to avoid issues with arrays and objects.

Value Transformation: Uses getDisplayableValue() (src/Concerns/FormatsMessages.php414-439) which:

  1. Checks $customValues array for custom representations
  2. Queries translator at validation.values.{attribute}.{value}
  3. Converts booleans to "true"/"false"
  4. Converts null to "empty"
  5. Casts arrays to "array"
  6. Returns string representation for everything else

Sources: src/Concerns/FormatsMessages.php400-439

:index and :position Placeholders

These placeholders are used for nested array validation to indicate which element failed validation.

Methods:

Difference:

  • :index uses zero-based indexing (0, 1, 2...)
  • :position uses one-based indexing (1, 2, 3...)

Named Position Support

Both placeholders support named variants for nested arrays:

PlaceholderReplacementExample
:indexFirst numeric segment0
:first-indexFirst numeric segment0
:second-indexSecond numeric segment1
:third-indexThird numeric segment2

Example for attribute items.0.tags.1:

  • :first-index0
  • :second-index1

Implementation Details (src/Concerns/FormatsMessages.php350-376):

The replaceIndexOrPositionPlaceholder() method:

  1. Splits attribute by dots: items.0.tags.1['items', '0', 'tags', '1']
  2. Identifies numeric segments
  3. Replaces placeholders with appropriate values
  4. Applies optional modifier (for position: $segment + 1)

Word Mapping (src/Concerns/FormatsMessages.php381-395): Numbers 1-10 map to English words (first, second, third, etc.) for readable placeholder names.

Sources: src/Concerns/FormatsMessages.php325-395

Displayable Attribute Names

The system provides multiple mechanisms for customizing how attribute names appear in error messages.

Attribute Name Resolution Flow


Method: getDisplayableAttribute() (src/Concerns/FormatsMessages.php238-272)

Inline Custom Attributes

Defined through the $customAttributes array passed to the validator.

Lookup: getAttributeFromLocalArray() (src/Concerns/FormatsMessages.php289-308)

Pattern Matching: Supports wildcard patterns:


The wildcard matching (src/Concerns/FormatsMessages.php297-304):

  1. Converts * to regex pattern: ([^.]*)
  2. Performs full pattern match against attribute
  3. Returns matched custom name

Sources: src/Concerns/FormatsMessages.php289-308

Translation-Based Attributes

Queried from the translator at validation.attributes.

Method: getAttributeFromTranslations() (src/Concerns/FormatsMessages.php277-284)

Structure:


The translation array is converted to dot notation using Arr::dot() before matching, enabling nested key lookups.

Sources: src/Concerns/FormatsMessages.php277-284

Implicit Attribute Formatting

For implicit attributes (those defined via implicit rules like required), a custom formatter can be applied.

Formatter: Optional $implicitAttributesFormatter closure (src/Concerns/FormatsMessages.php266-268)

Default Behavior: If no formatter is set, the raw attribute name is used without modification.

Sources: src/Concerns/FormatsMessages.php265-269

Default Formatting

When no custom name or translation exists, the system applies default formatting (src/Concerns/FormatsMessages.php271):


This converts emailAddressemail_addressemail address.

Sources: src/Concerns/FormatsMessages.php271

Custom Replacers

The formatting pipeline supports custom replacer functions for rule-specific placeholder substitution.

Replacer Execution Flow


Registered Replacers

Custom replacers are stored in the $replacers array (src/Concerns/FormatsMessages.php225) and invoked via callReplacer() (src/Concerns/FormatsMessages.php461-473).

Supported Types:

  1. Closure replacers: Direct callable functions
  2. String replacers: Class-based replacers resolved via container

Method Signature:


Class-Based Replacers (src/Concerns/FormatsMessages.php478-484):


Sources: src/Concerns/FormatsMessages.php225-484

Method-Based Replacers

If no registered replacer exists, the system checks for a method named replace{Rule} on the validator instance (src/Concerns/FormatsMessages.php228-230).

Example: For a between rule, the system looks for replaceBetween() method.

These methods are typically defined in the ValidatesAttributes trait and handle rule-specific placeholder replacements like :min, :max, :size, etc.

Sources: src/Concerns/FormatsMessages.php228-230

Supporting Utilities

Attribute List Transformation

The getAttributeList() method (src/Concerns/FormatsMessages.php444-456) converts an array of attribute names to their displayable forms.

Use Case: Rules that reference multiple attributes (e.g., same:password_confirmation) need to display all attribute names in a readable format.

Implementation:


Sources: src/Concerns/FormatsMessages.php444-456

Placeholder Escaping

The system includes a method for replacing placeholders in attribute names themselves (not messages), referenced at src/Concerns/FormatsMessages.php24 but defined in the ReplacesAttributes trait.

This handles special attribute name patterns like wildcards that need to be resolved before message lookup.

Sources: src/Concerns/FormatsMessages.php24

Summary of Message Retrieval Process

The complete message retrieval and formatting process:


Key Classes and Methods:

EntityLocationPurpose
FormatsMessagessrc/Concerns/FormatsMessages.php13Main trait implementing message system
getMessage()src/Concerns/FormatsMessages.php20Orchestrates 4-tier lookup
makeReplacements()src/Concerns/FormatsMessages.php214Orchestrates formatting pipeline
getDisplayableAttribute()src/Concerns/FormatsMessages.php238Resolves displayable attribute names
getDisplayableValue()src/Concerns/FormatsMessages.php414Resolves displayable values
getAttributeType()src/Concerns/FormatsMessages.php198Determines attribute type for size rules

Sources: src/Concerns/FormatsMessages.php1-485

Refresh this wiki

On this page