Skip to content

Commit b35780c

Browse files
vjiksamdarkarogachev
authored
Consider missing attribute in context validation (#557)
Co-authored-by: Alexander Makarov <[email protected]> Co-authored-by: Alexey Rogachev <[email protected]>
1 parent 5a95ebe commit b35780c

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

src/ValidationContext.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@ final class ValidationContext
5353
*/
5454
private ?AttributeTranslatorInterface $defaultAttributeTranslator = null;
5555

56+
/**
57+
* @var bool Whether {@see $dataSet} is missing.
58+
*/
59+
private bool $isDataSetMissing = false;
60+
5661
/**
5762
* @param array $parameters Arbitrary parameters.
5863
* @param AttributeTranslatorInterface|null $attributeTranslator Optional attribute translator instance to use.
@@ -127,11 +132,15 @@ public function validate(mixed $data, callable|iterable|object|string|null $rule
127132

128133
$currentDataSet = $this->dataSet;
129134
$currentAttribute = $this->attribute;
135+
$isCurrentDataSetMissing = $this->isDataSetMissing;
130136

137+
// The lack of an attribute means that in the context of further validation there is no data set at all.
138+
$this->isDataSetMissing = $this->isAttributeMissing();
131139
$result = $this->validator->validate($data, $rules, $this);
132140

133141
$this->dataSet = $currentDataSet;
134142
$this->attribute = $currentAttribute;
143+
$this->isDataSetMissing = $isCurrentDataSetMissing;
135144

136145
return $result;
137146
}
@@ -262,7 +271,8 @@ public function setParameter(string $name, mixed $value): self
262271
*/
263272
public function isAttributeMissing(): bool
264273
{
265-
return $this->attribute !== null && !$this->getDataSet()->hasAttribute($this->attribute);
274+
return $this->isDataSetMissing
275+
|| ($this->attribute !== null && !$this->getDataSet()->hasAttribute($this->attribute));
266276
}
267277

268278
/**

tests/Rule/StopOnErrorTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use Yiisoft\Validator\Rule\Length;
88
use Yiisoft\Validator\Rule\Number;
9+
use Yiisoft\Validator\Rule\Required;
910
use Yiisoft\Validator\Rule\StopOnError;
1011
use Yiisoft\Validator\Rule\StopOnErrorHandler;
1112
use Yiisoft\Validator\Tests\Rule\Base\DifferentRuleInHandlerTestTrait;
@@ -128,6 +129,19 @@ public function dataValidationFailed(): array
128129
],
129130
],
130131
],
132+
'case4' => [
133+
['b' => null],
134+
[
135+
'a' => new StopOnError([
136+
new Required(),
137+
]),
138+
'b' => new Required(),
139+
],
140+
[
141+
'a' => ['Value not passed.'],
142+
'b' => ['Value cannot be blank.'],
143+
],
144+
],
131145
];
132146
}
133147

0 commit comments

Comments
 (0)