diff --git a/CHANGELOG.md b/CHANGELOG.md index 07eca1e19..96c65079e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,8 @@ ## 2.6.3 under development -- no changes in this release. +- Bug #752: Allow access to sibling properties in nested validation context, e.g. in `when` callbacks and + `targetProperty` of compare rules (@WarLikeLaux, @vjik) ## 2.6.2 November 23, 2026 diff --git a/docs/guide/en/built-in-rules-nested.md b/docs/guide/en/built-in-rules-nested.md index 02ac38ae5..e0f0dc2d1 100644 --- a/docs/guide/en/built-in-rules-nested.md +++ b/docs/guide/en/built-in-rules-nested.md @@ -388,10 +388,15 @@ attributes] section. - For more information about possible data / rules combinations passed for validation, refer to the [Using validator] section. -### Conditional validation within nested structures +### Accessing sibling properties -When using `when` callbacks inside `Nested`, the validation context provides access to sibling properties — other -properties at the same nesting level. Use `$context->getDataSet()->getPropertyValue()` to read them. +For rules attached to named properties, `Nested` validates a property together with its whole scope. Because of +this, the validation context provides access to sibling properties — other properties at the same nesting level: + +- in `when` callbacks and custom rules, via `$context->getDataSet()->getPropertyValue()`; +- in comparison rules, via the `targetProperty` option. + +#### `when` callbacks For example, to require `content` only when `isEnabled` is `true`: @@ -426,6 +431,53 @@ $result = (new Validator())->validate($data, $rules); This works at any depth, including when combined with `Each`. For more details and examples, see the [Conditional validation] guide. +#### Comparison rules + +Comparison rules can compare the validated property with a sibling one. Use the `targetProperty` option for this: + +```php +use Yiisoft\Validator\Rule\Equal; +use Yiisoft\Validator\Rule\Nested; +use Yiisoft\Validator\Rule\Number; +use Yiisoft\Validator\Validator; + +$data = [ + 'discountPercent' => 10, + 'confirmedDiscountPercent' => 10, +]; +$rules = new Nested([ + 'discountPercent' => new Number(min: 0), + 'confirmedDiscountPercent' => new Equal(targetProperty: 'discountPercent'), +]); +$result = (new Validator())->validate($data, $rules); +``` + +Here `confirmedDiscountPercent` must be equal to the sibling `discountPercent` property. For more comparison options, +see the [`Compare` rule] guide. + +#### Custom rules + +A custom rule handler receives a `ValidationContext` as the third argument of its `validate()` method. Sibling +properties are resolved there the same way: + +```php +public function validate(mixed $value, RuleInterface $rule, ValidationContext $context): Result +{ + $isEnabled = (bool) $context->getDataSet()->getPropertyValue('isEnabled'); + // ... +} +``` + +For more information about creating custom rules, see the [Creating custom rules] guide. + +#### Numeric keys + +A rule attached to a numeric key — an integer key like `0` or a path whose last segment is numeric, like +`'items.1'` — behaves differently: the selected value is validated as is, without the containing list. Sibling items +are not available in this case — `$context->getDataSet()->getPropertyValue()` returns `null` for them, and the +`targetProperty` option cannot reference them. To access properties of the same item in a list, combine `Each` with +`Nested` as shown above. + ### Using keys containing separator / shortcut If a key contains the separator (`.`), or `Each` shortcut (`*`), it must be escaped with backslash (`\`) in @@ -501,5 +553,7 @@ $data = [ [Basic usage]: #basic-usage-one-to-one-relation [JSFiddle]: https://jsfiddle.net/fys8uadr/ [Conditional validation]: conditional-validation.md +[`Compare` rule]: built-in-rules-compare.md +[Creating custom rules]: creating-custom-rules.md [Configuring rules via PHP attributes]: configuring-rules-via-php-attributes.md [Using validator]: using-validator.md diff --git a/docs/guide/en/conditional-validation.md b/docs/guide/en/conditional-validation.md index c63c1ad33..c9bd87f14 100644 --- a/docs/guide/en/conditional-validation.md +++ b/docs/guide/en/conditional-validation.md @@ -343,8 +343,18 @@ $rules = new Nested([ $result = (new Validator())->validate($data, $rules); ``` +Sibling access works because, for named properties, `Nested` uses the whole scope the property belongs to as the +validation data. The same data set is available in custom rules and in comparison rules with `targetProperty`, see +the [`Nested` rule] guide for details. + +Note that only named properties provide such access. When a rule is attached to a numeric leaf — an integer key or a +path ending with a numeric segment, like `'items.1'` — the selected value is validated as is, without the containing +list. In this case `$context->getDataSet()->getPropertyValue()` returns `null` for any sibling property, and the +`targetProperty` option of comparison rules cannot reference them. + As an alternative to functions, callable classes can be used instead. This approach has the advantage of code reusability. See the [Skip on empty] section for an example. [Configuring empty condition in other rules]: #configuring-empty-condition-in-other-rules [Skip on empty]: #skiponempty---skipping-a-rule-if-the-validated-value-is-empty +[`Nested` rule]: built-in-rules-nested.md diff --git a/src/Rule/NestedHandler.php b/src/Rule/NestedHandler.php index 2c6242a94..2c39f7f6c 100644 --- a/src/Rule/NestedHandler.php +++ b/src/Rule/NestedHandler.php @@ -14,6 +14,7 @@ use Yiisoft\Validator\RuleInterface; use Yiisoft\Validator\ValidationContext; +use function array_key_exists; use function array_slice; use function is_array; use function is_int; @@ -68,11 +69,11 @@ public function validate(mixed $value, RuleInterface $rule, ValidationContext $c $compoundResult = new Result(); foreach ($rule->getRules() as $valuePath => $rules) { - if ($rule->isPropertyPathRequired() && !ArrayHelper::pathExists($data, $valuePath)) { - $valuePathList = is_int($valuePath) - ? [$valuePath] - : StringHelper::parsePath($valuePath); + $valuePathList = is_int($valuePath) + ? [$valuePath] + : StringHelper::parsePath($valuePath); + if ($rule->isPropertyPathRequired() && !ArrayHelper::pathExists($data, $valuePath)) { $compoundResult->addError( $rule->getNoPropertyPathMessage(), [ @@ -86,32 +87,32 @@ public function validate(mixed $value, RuleInterface $rule, ValidationContext $c continue; } - $validatedValue = ArrayHelper::getValueByPath($data, $valuePath); + $property = end($valuePathList); + $validateValueItself = is_int($valuePath) || (string) (int) $property === $property; - if (is_int($valuePath)) { - $itemResult = $context->validate($validatedValue, $rules); - } else { - $valuePathList = StringHelper::parsePath($valuePath); - $property = end($valuePathList); - $itemResult = $context->validate( - ArrayHelper::keyExists($data, $valuePathList) ? [$property => $validatedValue] : [], + $itemResult = $validateValueItself + ? $context->validate( + ArrayHelper::getValueByPath($data, $valuePath), + $rules, + ) + : $context->validate( + $this->getPropertyScopeData($data, $valuePathList), [$property => $rules], ); - } if ($itemResult->isValid()) { continue; } foreach ($itemResult->getErrors() as $error) { - $valuePathList = is_int($valuePath) - ? [$valuePath, ...$error->getValuePath()] - : [...StringHelper::parsePath($valuePath), ...array_slice($error->getValuePath(), 1)]; + $errorValuePath = $validateValueItself + ? [...$valuePathList, ...$error->getValuePath()] + : [...$valuePathList, ...array_slice($error->getValuePath(), 1)]; $compoundResult->addErrorWithoutPostProcessing( $error->getMessage(), $error->getParameters(), - $valuePathList, + $errorValuePath, ); } } @@ -122,4 +123,26 @@ public function validate(mixed $value, RuleInterface $rule, ValidationContext $c return $compoundResult; } + + /** + * Get the data of the scope a property with a given value path belongs to, so it also contains sibling + * properties. Only arrays are traversed, any other intermediate value is treated as a missing path. + * + * @param array $data The data to get the scope from. + * @param array $valuePathList A parsed value path of the validated property. + * + * @return array The scope data. An empty array when the scope cannot be resolved. + */ + private function getPropertyScopeData(array $data, array $valuePathList): array + { + $scopeData = $data; + foreach (array_slice($valuePathList, 0, -1) as $key) { + if (!is_array($scopeData) || !array_key_exists($key, $scopeData)) { + return []; + } + $scopeData = $scopeData[$key]; + } + + return is_array($scopeData) ? $scopeData : []; + } } diff --git a/tests/Rule/Nested/NestedTest.php b/tests/Rule/Nested/NestedTest.php index 419a27cf6..e0964858b 100644 --- a/tests/Rule/Nested/NestedTest.php +++ b/tests/Rule/Nested/NestedTest.php @@ -20,6 +20,7 @@ use Yiisoft\Validator\Rule\Callback; use Yiisoft\Validator\Rule\Count; use Yiisoft\Validator\Rule\Each; +use Yiisoft\Validator\Rule\Equal; use Yiisoft\Validator\Rule\FilledAtLeast; use Yiisoft\Validator\Rule\In; use Yiisoft\Validator\Rule\Integer; @@ -1060,6 +1061,67 @@ public function getRules(): iterable ['' => 17], new Nested(['' => new Integer(min: 15)]), ], + 'sibling access skips rule when sibling is false' => [ + [ + 'push' => [ + 'isEnabled' => false, + 'content' => null, + ], + ], + new Nested([ + 'push' => new Nested([ + 'isEnabled' => [new BooleanValue()], + 'content' => [ + new Required( + when: static function (mixed $value, ValidationContext $context): bool { + return (bool) $context->getDataSet()->getPropertyValue('isEnabled'); + }, + ), + ], + ]), + ]), + ], + 'sibling access with each and nested' => [ + [ + 'tasks' => [ + [ + 'push' => [ + 'isEnabled' => false, + 'content' => null, + ], + ], + ], + ], + new Nested([ + 'tasks' => new Each( + new Nested([ + 'push' => new Nested([ + 'isEnabled' => [new BooleanValue()], + 'content' => [ + new Required( + when: static function (mixed $value, ValidationContext $context): bool { + return (bool) $context->getDataSet()->getPropertyValue('isEnabled'); + }, + ), + ], + ]), + ]), + ), + ]), + ], + 'compare rule targetProperty sibling access' => [ + [ + 'p' => 1, + 'p2' => 1, + ], + new Nested(['p2' => new Equal(targetProperty: 'p')]), + ], + 'numeric last path segment' => [ + [ + 'items' => [[1], [2]], + ], + new Nested(['items.1' => new Count(max: 1)]), + ], ]; } @@ -1284,6 +1346,70 @@ public function hasProperty(string $property): bool 'properties.abc' => ['Abc cannot be blank.'], ], ], + 'sibling access in when callback' => [ + [ + 'push' => [ + 'isEnabled' => true, + 'content' => null, + ], + ], + new Nested([ + 'push' => new Nested([ + 'isEnabled' => [new BooleanValue()], + 'content' => [ + new Required( + when: static function (mixed $value, ValidationContext $context): bool { + return (bool) $context->getDataSet()->getPropertyValue('isEnabled'); + }, + ), + ], + ]), + ]), + [ + 'push.content' => ['Content cannot be blank.'], + ], + ], + 'sibling access in when callback inside Each' => [ + [ + 'tasks' => [ + [ + 'push' => [ + 'isEnabled' => true, + 'content' => null, + ], + ], + ], + ], + new Nested([ + 'tasks' => new Each( + new Nested([ + 'push' => new Nested([ + 'isEnabled' => [new BooleanValue()], + 'content' => [ + new Required( + when: static function (mixed $value, ValidationContext $context): bool { + return (bool) $context->getDataSet()->getPropertyValue('isEnabled'); + }, + ), + ], + ]), + ]), + ), + ]), + [ + 'tasks.0.push.content' => ['Content cannot be blank.'], + ], + ], + 'compare rule targetProperty sibling access with different values' => [ + [ + 'p' => 1, + 'p2' => 2, + ], + new Nested(['p2' => new Equal(targetProperty: 'p')]), + [ + 'p2' => ['P2 must be equal to "p".'], + ], + ], 'deep level of nesting with plain keys' => [ [ 'level1' => [ @@ -1313,6 +1439,66 @@ public function hasProperty(string $property): bool 'level1.level2.level3.name' => ['Name must contain at least 5 characters.'], ], ], + 'dotted path with missing intermediate key' => [ + [ + 'level1' => [ + 'x' => 1, + ], + ], + new Nested([ + 'level1.level2.key' => [new Required()], + ]), + [ + 'level1.level2.key' => ['Key not passed.'], + ], + ], + 'dotted path with scalar intermediate value' => [ + [ + 'level1' => 'scalar', + ], + new Nested([ + 'level1.level2' => [new Required()], + ]), + [ + 'level1.level2' => ['Level2 not passed.'], + ], + ], + 'dotted path with scalar intermediate value and deeper path' => [ + [ + 'level1' => 'scalar', + ], + new Nested([ + 'level1.level2.key' => [new Required()], + ]), + [ + 'level1.level2.key' => ['Key not passed.'], + ], + ], + 'numeric last path segment' => [ + [ + 'items' => [[1], [2]], + ], + new Nested([ + 'items.1' => [new Count(exactly: 5)], + ]), + [ + 'items.1' => ['Value must contain exactly 5 items.'], + ], + ], + 'numeric last path segment with nested rules' => [ + [ + 'items' => [ + ['name' => 'abcde'], + ['name' => 'ab'], + ], + ], + new Nested([ + 'items.1' => new Nested(['name' => [new Length(min: 5)]]), + ]), + [ + 'items.1.name' => ['Name must contain at least 5 characters.'], + ], + ], 'error messages with properties in nested structure' => [ [ 'user' => [