VOOZH about

URL: https://deepwiki.com/hypervel/validation/4.1-rule-facade-and-factory

⇱ Rule Facade and Factory | hypervel/validation | DeepWiki


Loading...
Menu

Rule Facade and Factory

Purpose and Scope

This document covers the Rule facade class, which provides static factory methods for creating rule objects in a fluent, expressive manner. The facade serves as the primary public API for instantiating rule objects, offering a cleaner alternative to direct class instantiation.

For information about the specific rule objects created by these factory methods, see Built-in Rule Objects. For details on how rules are executed within the validation lifecycle, see Validation Lifecycle. For information about the ValidatorFactory which creates Validator instances, see Creating Validators.

Sources: src/Rule.php1-273


Facade Architecture

The Rule class implements the facade pattern, providing static methods that instantiate and return configured rule objects. It uses the Macroable trait to allow runtime extension with custom factory methods.


Sources: src/Rule.php36-38


Factory Method Categories

The Rule facade organizes its factory methods into several logical categories based on the type of validation being performed:

Complete Method Reference

CategoryMethodReturnsPurpose
Type Validationarray($keys = null)ArrayRuleValidates array structure with optional key constraints
date()DateValidates date formats
dateTime()DateValidates datetime format (Y-m-d H:i:s)
numeric()NumericValidates numeric values with precision control
file()FileValidates file uploads with size/type constraints
imageFile($allowSvg = false)ImageFileValidates image files with dimension constraints
enum($type)EnumValidates against enum class values
Format Validationemail()EmailValidates email addresses with configurable strategies
dimensions($constraints = [])DimensionsValidates image dimensions
Database Validationunique($table, $column = 'NULL')UniqueValidates uniqueness in database
exists($table, $column = 'NULL')ExistsValidates existence in database
List Validationin($values)InValidates value is in allowed list
notIn($values)NotInValidates value is not in forbidden list
contains($values)ContainsValidates array contains required values
doesntContain($values)DoesntContainValidates array doesn't contain forbidden values
Conditional RulesrequiredIf($callback)RequiredIfConditionally requires field
excludeIf($callback)ExcludeIfConditionally excludes field from validated data
prohibitedIf($callback)ProhibitedIfConditionally prohibits field presence
when($condition, $rules, $defaultRules = [])ConditionalRulesApplies rules based on condition
unless($condition, $rules, $defaultRules = [])ConditionalRulesInverse of when()
Logical OperationsanyOf($rules)AnyOfPasses if any of the given rules pass
Structure & NestingforEach($callback)NestedRulesApplies rules to nested array items
Authorizationcan($ability, ...$arguments)CanValidates user authorization
Compilationcompile($attribute, $rules, $data = null)objectCompiles rules into parsed structure

Sources: src/Rule.php43-248


Factory Method Implementation Patterns

The factory methods follow consistent implementation patterns based on the complexity of the rule being created:


Sources: src/Rule.php43-248

Value Normalization in Collection Methods

The collection-based factory methods (in(), notIn(), contains(), doesntContain()) normalize their input to handle multiple input types:


Sources: src/Rule.php105-148

This normalization allows flexible method signatures:

  • Rule::in(['admin', 'user']) - Direct array
  • Rule::in('admin', 'user') - Variadic arguments
  • Rule::in($enumCase) - Enum value
  • Rule::in($collection) - Arrayable object

Conditional Rule Construction

The when() and unless() methods provide conditional rule application, creating ConditionalRules objects that evaluate conditions at validation time:


Sources: src/Rule.php51-68

The when() method src/Rule.php51-57 accepts:

  • $condition: A boolean or callable that determines which rules to apply
  • $rules: Rules to apply when condition is truthy
  • $defaultRules: Rules to apply when condition is falsy (optional)

The unless() method src/Rule.php62-68 inverts this logic, applying $defaultRules when condition is truthy and $rules when falsy.


Rule Compilation

The static compile() method src/Rule.php253-272 provides programmatic access to the rule parsing system, converting mixed rule formats into a standardized structure:


Sources: src/Rule.php253-272

The compilation process:

  1. Parser Creation src/Rule.php255-257: Creates ValidationRuleParser with undotted data using Arr::undot(Arr::wrap($data))

  2. Format Detection src/Rule.php259-269: Determines if rules are in nested associative format

    • Associative arrays (not lists) are expanded to dot-notation: ['user' => ['name' => 'required']] becomes ['attribute.user.name' => 'required']
    • Other formats are wrapped: 'required|email' becomes ['attribute' => 'required|email']
  3. Conditional Filtering src/Rule.php271: Applies ValidationRuleParser::filterConditionalRules() to evaluate ConditionalRules based on provided data

  4. Explosion src/Rule.php271: Calls parser->explode() to parse rule strings, expand wildcards, and create final structure

Sources: src/Rule.php253-272


Extensibility via Macroable

The Rule facade uses the Macroable trait src/Rule.php38 enabling runtime addition of custom factory methods:

FeatureDescription
Static Macro RegistrationAdd custom factory methods globally using Rule::macro()
Method Availability CheckUse Rule::hasMacro() to check if custom method exists
Dynamic Method ResolutionMacros are resolved via __callStatic() magic method

This allows packages and applications to extend the Rule facade with domain-specific factory methods without modifying the core class.

Sources: src/Rule.php38


Usage Patterns

Basic Factory Usage

The most common pattern is calling static factory methods directly:


Fluent Configuration

Rule objects returned by factory methods often support fluent configuration:


Conditional Application

The when() and unless() methods enable dynamic rule application:


Nested Structure Validation

The forEach() method applies rules to array items:


Sources: src/Rule.php43-248


Integration with Validator

The Rule facade is typically used when defining validation rules for the Validator:


Sources: src/Rule.php1-273

Rule objects created by the facade are passed to ValidatorFactory::make() alongside string rules and closures, providing a consistent interface for rule definition while maintaining type safety and IDE support.