0 follower

Final Class Yiisoft\Validator\Rule\Nested

InheritanceYiisoft\Validator\Rule\Nested
ImplementsYiisoft\Validator\AfterInitAttributeEventInterface, Yiisoft\Validator\DumpedRuleInterface, Yiisoft\Validator\PropagateOptionsInterface, Yiisoft\Validator\SkipOnEmptyInterface, Yiisoft\Validator\SkipOnErrorInterface, Yiisoft\Validator\WhenInterface
Uses TraitsYiisoft\Validator\Rule\Trait\SkipOnEmptyTrait, Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait, Yiisoft\Validator\Rule\Trait\WhenTrait

Used to define rules for validation of nested structures:

  • For one-to-one relation, using Nested rule is enough.
  • One-to-many and many-to-many relations require pairing with {@see \Yiisoft\Validator\Rule\Each} rule.

An example with blog post:

$rule = new Nested([
    'title' => [new Length(max: 255)],
    // One-to-one relation
    'author' => new Nested([
        'name' => [new Length(min: 1)],
    ]),
    // One-to-many relation
    'files' => new Each([
         new Nested([
            'url' => [new Url()],
        ]),
    ]),
]);

There is an alternative way to write this using dot notation and shortcuts:

$rule = new Nested([
    'title' => [new Length(max: 255)],
    'author.name' => [new Length(min: 1)],
    'files.*.url' => [new Url()],
]);

Also it's possible to use plain keys and omit arrays for single rules:

  • $rules = [
     new Nested([
         'author' => [
             'name' => new Length(min: 1),
         ],
     ]),
    ];
    

For more examples please refer to the guide.

It's also possible to use DTO objects with PHP attributes, see {@see \Yiisoft\Validator\DataSet\ObjectDataSet} documentation and guide for details.

Supports propagation of options (see {@see \Yiisoft\Validator\Helper\PropagateOptionsHelper::propagate()} for available options and requirements).

See also Yiisoft\Validator\Rule\NestedHandler Corresponding handler performing the actual validation.

Public Methods

Hide inherited methods

Method Description Defined By
__construct() Yiisoft\Validator\Rule\Nested
afterInitAttribute() Yiisoft\Validator\Rule\Nested
getHandler() Yiisoft\Validator\Rule\Nested
getIncorrectDataSetTypeMessage() Gets error message used when validation fails because the validated value is an object providing wrong type of data (neither array nor an object). Yiisoft\Validator\Rule\Nested
getIncorrectInputMessage() Gets error message used when validation fails because the validated value is neither an array nor an object. Yiisoft\Validator\Rule\Nested
getName() Yiisoft\Validator\Rule\Nested
getNoPropertyPathMessage() Gets error message used when validation fails because {@see $requirePropertyPath} option was enabled and the validated array contains missing data item. Yiisoft\Validator\Rule\Nested
getNoRulesWithNoObjectMessage() Gets error message used when validation fails because the validated value is not an object and the rules were not explicitly specified via {@see $rules}. Yiisoft\Validator\Rule\Nested
getOptions() Yiisoft\Validator\Rule\Nested
getRules() Gets a set of rules for running the validation. Yiisoft\Validator\Rule\Nested
getSkipOnEmpty() A getter for $skipOnEmpty property. Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait
getValidatedObjectPropertyVisibility() Gets visibility levels to use for parsed properties when validated value is an object providing rules / data. Yiisoft\Validator\Rule\Nested
getWhen() A getter for $when property. Yiisoft\Validator\Rule\Trait\WhenTrait
isPropertyPathRequired() Whether to require a single data item to be passed in data according to declared nesting level structure (all keys in the sequence must be the present). Disabled by default. Yiisoft\Validator\Rule\Nested
propagateOptions() Yiisoft\Validator\Rule\Nested
shouldSkipOnError() A getter for $skipOnError property. Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait
skipOnEmpty() An immutable setter to change $skipOnEmpty property. Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait
skipOnError() An immutable setter to change $skipOnError property. Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait
when() An immutable setter to change $when property. Yiisoft\Validator\Rule\Trait\WhenTrait

Constants

Hide inherited constants

Constant Value Description Defined By
EACH_SHORTCUT '*' A character acting as a shortcut when using alternative (short) syntax with {@see Nested} and {@see Each} combinations. Yiisoft\Validator\Rule\Nested
SEPARATOR '.' A character acting as a separator when using alternative (short) syntax. Yiisoft\Validator\Rule\Nested

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( iterable|object|string|null $rules null, integer $validatedObjectPropertyVisibility ReflectionProperty::IS_PRIVATE ReflectionProperty::IS_PROTECTED ReflectionProperty::IS_PUBLIC, integer $rulesSourceClassPropertyVisibility ReflectionProperty::IS_PRIVATE ReflectionProperty::IS_PROTECTED ReflectionProperty::IS_PUBLIC, string $noRulesWithNoObjectMessage 'Nested rule without rules requires {property} to be an object. ' '{type} given.', string $incorrectDataSetTypeMessage 'An object data set data for {property} can only have an array ' 'type. {type} given.', string $incorrectInputMessage '{Property} must be an array or an object. {type} given.', boolean $requirePropertyPath false, string $noPropertyPathMessage 'Property "{path}" is not found in {property}.', boolean $handleEachShortcut true, boolean $propagateOptions false, boolean|callable|null $skipOnEmpty null, boolean $skipOnError false, Closure|null $when null )
$rules iterable|object|string|null

Rules for validating nested structure. The following types are supported:

  • Array or object implementing {@see \Traversable} interface containing rules. Either iterables containing {@see \Yiisoft\Validator\RuleInterface} implementations or a single rule instances are expected. All iterables regardless of the nesting level will be converted to arrays at the end.
  • Object implementing {@see \Yiisoft\Validator\RulesProviderInterface}.
  • Name of a class containing rules declared via PHP attributes.
  • null if validated value is an object. It can either implement {@see \Yiisoft\Validator\RulesProviderInterface} or contain rules declared via PHP attributes.
$validatedObjectPropertyVisibility integer

Visibility levels to use for parsed properties when validated value is an object providing rules / data. For example: public and protected only, this means that the rest (private ones) will be skipped. Defaults to all visibility levels (public, protected and private). See {@see \Yiisoft\Validator\DataSet\ObjectDataSet} for details on providing rules / data in validated object and {@see \Yiisoft\Validator\Rule\ObjectParser} for overview how parsing works.

$rulesSourceClassPropertyVisibility integer

Visibility levels to use for parsed properties when {@see $rules} source is a name of the class providing rules. For example: public and protected only, this means that the rest (private ones) will be skipped. Defaults to all visibility levels (public, protected and private). See {@see \Yiisoft\Validator\DataSet\ObjectDataSet} for details on providing rules via class and {@see \Yiisoft\Validator\Rule\ObjectParser} for overview how parsing works.

$noRulesWithNoObjectMessage string

Error message used when validation fails because the validated value is not an object and the rules were not explicitly specified via {@see $rules}:

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {type}: the type of the value being validated.
$incorrectDataSetTypeMessage string

Error message used when validation fails because the validated value is an object providing wrong type of data (neither array nor an object).

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {type}: the type of the data set retrieved from the validated object.
$incorrectInputMessage string

Error message used when validation fails because the validated value is neither an array nor an object.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {type}: the type of the value being validated.
$requirePropertyPath boolean

Whether to require a single data item to be passed in data according to declared nesting level structure (all keys in the sequence must be the present). Used only when validated value is an array. Enabled by default. See {@see $noPropertyPathMessage} for customization of error message.

$noPropertyPathMessage string

Error message used when validation fails because {@see $requirePropertyPath} option was enabled and the validated array contains missing data item.

You may use the following placeholders in the message:

  • {path}: the path of the value being validated. Can be either a simple key of integer / string type for a single nesting level or a sequence of keys concatenated using dot notation (see {@see \Yiisoft\Validator\Rule\SEPARATOR}).
  • {property}: the translated label of the property being validated.
$handleEachShortcut boolean

Whether to handle {@see \Yiisoft\Validator\Rule\EACH_SHORTCUT}. Enabled by default meaning shortcuts are supported. Can be disabled if they are not used to prevent additional checks and improve performance.

$propagateOptions boolean

Whether the propagation of options is enabled (see {@see \Yiisoft\Validator\Helper\PropagateOptionsHelper::propagate()} for supported options and requirements). Disabled by default.

$skipOnEmpty boolean|callable|null

Whether to skip this Nested rule with all defined {@see $rules} if the validated value is empty / not passed. See {@see \Yiisoft\Validator\SkipOnEmptyInterface}.

$skipOnError boolean

Whether to skip this Nested rule with all defined {@see $rules} if any of the previous rules gave an error. See {@see \Yiisoft\Validator\SkipOnErrorInterface}.

$when Closure|null

A callable to define a condition for applying this Nested rule with all defined {@see $rules}. See {@see \Yiisoft\Validator\WhenInterface}.

                public function __construct(
    iterable|object|string|null $rules = null,
    private int $validatedObjectPropertyVisibility = ReflectionProperty::IS_PRIVATE
    | ReflectionProperty::IS_PROTECTED
    | ReflectionProperty::IS_PUBLIC,
    private int $rulesSourceClassPropertyVisibility = ReflectionProperty::IS_PRIVATE
    | ReflectionProperty::IS_PROTECTED
    | ReflectionProperty::IS_PUBLIC,
    private string $noRulesWithNoObjectMessage = 'Nested rule without rules requires {property} to be an object. '
    . '{type} given.',
    private string $incorrectDataSetTypeMessage = 'An object data set data for {property} can only have an array '
    . 'type. {type} given.',
    private string $incorrectInputMessage = '{Property} must be an array or an object. {type} given.',
    private bool $requirePropertyPath = false,
    private string $noPropertyPathMessage = 'Property "{path}" is not found in {property}.',
    private bool $handleEachShortcut = true,
    private bool $propagateOptions = false,
    bool|callable|null $skipOnEmpty = null,
    private bool $skipOnError = false,
    private ?Closure $when = null,
) {
    $this->skipOnEmpty = $skipOnEmpty;
    $this->prepareRules($rules);
}

            
afterInitAttribute() public method

public void afterInitAttribute ( object $object )
$object object

                public function afterInitAttribute(object $object): void
{
    if ($this->rules === null) {
        return;
    }
    foreach ($this->rules as $rules) {
        if (is_array($rules)) {
            foreach ($rules as $rule) {
                if ($rule instanceof AfterInitAttributeEventInterface) {
                    $rule->afterInitAttribute($object);
                }
            }
        } else {
            if ($rules instanceof AfterInitAttributeEventInterface) {
                $rules->afterInitAttribute($object);
            }
        }
    }
}

            
getHandler() public method

public string getHandler ( )

                public function getHandler(): string
{
    return NestedHandler::class;
}

            
getIncorrectDataSetTypeMessage() public method

Gets error message used when validation fails because the validated value is an object providing wrong type of data (neither array nor an object).

public string getIncorrectDataSetTypeMessage ( )
return string

Error message / template.

                public function getIncorrectDataSetTypeMessage(): string
{
    return $this->incorrectDataSetTypeMessage;
}

            
getIncorrectInputMessage() public method

Gets error message used when validation fails because the validated value is neither an array nor an object.

public string getIncorrectInputMessage ( )
return string

Error message / template.

                public function getIncorrectInputMessage(): string
{
    return $this->incorrectInputMessage;
}

            
getName() public method

public string getName ( )

                public function getName(): string
{
    return self::class;
}

            
getNoPropertyPathMessage() public method

Gets error message used when validation fails because {@see $requirePropertyPath} option was enabled and the validated array contains missing data item.

public string getNoPropertyPathMessage ( )
return string

Error message / template.

                public function getNoPropertyPathMessage(): string
{
    return $this->noPropertyPathMessage;
}

            
getNoRulesWithNoObjectMessage() public method

Gets error message used when validation fails because the validated value is not an object and the rules were not explicitly specified via {@see $rules}.

public string getNoRulesWithNoObjectMessage ( )
return string

Error message / template.

                public function getNoRulesWithNoObjectMessage(): string
{
    return $this->noRulesWithNoObjectMessage;
}

            
getOptions() public method

public array getOptions ( )

                #[ArrayShape([
    'requirePropertyPath' => 'bool',
    'noRulesWithNoObjectMessage' => 'array',
    'incorrectDataSetTypeMessage' => 'array',
    'incorrectInputMessage' => 'array',
    'noPropertyPathMessage' => 'array',
    'skipOnEmpty' => 'bool',
    'skipOnError' => 'bool',
    'rules' => 'array|null',
])]
public function getOptions(): array
{
    return [
        'noRulesWithNoObjectMessage' => [
            'template' => $this->noRulesWithNoObjectMessage,
            'parameters' => [],
        ],
        'incorrectDataSetTypeMessage' => [
            'template' => $this->incorrectDataSetTypeMessage,
            'parameters' => [],
        ],
        'incorrectInputMessage' => [
            'template' => $this->incorrectInputMessage,
            'parameters' => [],
        ],
        'noPropertyPathMessage' => [
            'template' => $this->getNoPropertyPathMessage(),
            'parameters' => [],
        ],
        'requirePropertyPath' => $this->isPropertyPathRequired(),
        'skipOnEmpty' => $this->getSkipOnEmptyOption(),
        'skipOnError' => $this->skipOnError,
        'rules' => $this->rules === null ? null : RulesDumper::asArray($this->rules),
    ];
}

            
getRules() public method

Gets a set of rules for running the validation.

public array|null getRules ( )
return array|null

A set of rules. null means the rules are expected to be provided with a validated value.

                public function getRules(): ?array
{
    return $this->rules;
}

            
getSkipOnEmpty() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait::getSkipOnEmpty()

A getter for $skipOnEmpty property.

public boolean|callable|null getSkipOnEmpty ( )
return boolean|callable|null

A current raw (non-normalized) value.

                public function getSkipOnEmpty(): bool|callable|null
{
    return $this->skipOnEmpty;
}

            
getValidatedObjectPropertyVisibility() public method

Gets visibility levels to use for parsed properties when validated value is an object providing rules / data.

Defaults to all visibility levels (public, protected and private)

public integer getValidatedObjectPropertyVisibility ( )
return integer

A number representing visibility levels.

                public function getValidatedObjectPropertyVisibility(): int
{
    return $this->validatedObjectPropertyVisibility;
}

            
getWhen() public method

Defined in: Yiisoft\Validator\Rule\Trait\WhenTrait::getWhen()

A getter for $when property.

public Closure|null getWhen ( )
return Closure|null

Current value:

  • null - always apply the validation.
  • callable - apply the validation depending on a return value: true - apply, false - do not apply.

                public function getWhen(): ?Closure
{
    return $this->when;
}

            
isPropertyPathRequired() public method

Whether to require a single data item to be passed in data according to declared nesting level structure (all keys in the sequence must be the present). Disabled by default.

public boolean isPropertyPathRequired ( )
return boolean

true if required and false otherwise.

                public function isPropertyPathRequired(): bool
{
    return $this->requirePropertyPath;
}

            
propagateOptions() public method

public void propagateOptions ( )

                public function propagateOptions(): void
{
    if ($this->rules === null) {
        return;
    }
    $rules = [];
    foreach ($this->rules as $attributeRulesIndex => $attributeRules) {
        $rules[$attributeRulesIndex] = is_iterable($attributeRules)
            ? PropagateOptionsHelper::propagate($this, $attributeRules)
            : PropagateOptionsHelper::propagateToRule($this, $attributeRules);
    }
    $this->rules = $rules;
}

            
shouldSkipOnError() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait::shouldSkipOnError()

A getter for $skipOnError property.

public boolean shouldSkipOnError ( )
return boolean

Current value. true means to skip the current rule when the previous one errored and false - do not skip.

                public function shouldSkipOnError(): bool
{
    return $this->skipOnError;
}

            
skipOnEmpty() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait::skipOnEmpty()

An immutable setter to change $skipOnEmpty property.

public $this skipOnEmpty ( boolean|callable|null $value )
$value boolean|callable|null

A new value.

return $this

The new instance with a changed value.

                public function skipOnEmpty(bool|callable|null $value): static
{
    $new = clone $this;
    $new->skipOnEmpty = $value;
    return $new;
}

            
skipOnError() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait::skipOnError()

An immutable setter to change $skipOnError property.

public $this skipOnError ( boolean $value )
$value boolean

A new value. true means to skip the current rule when the previous one errored and false - do not skip.

return $this

The new instance with a changed value.

                public function skipOnError(bool $value): static
{
    $new = clone $this;
    $new->skipOnError = $value;
    return $new;
}

            
when() public method

Defined in: Yiisoft\Validator\Rule\Trait\WhenTrait::when()

An immutable setter to change $when property.

public $this when ( Closure|null $value )
$value Closure|null

A new value:

  • null - always apply the validation.
  • callable - apply the validation depending on a return value: true - apply, false - do not apply.
return $this

The new instance with a changed value.

                public function when(?Closure $value): static
{
    $new = clone $this;
    $new->when = $value;
    return $new;
}