Skip to content

Commit 519ad85

Browse files
committed
Rules::getIterator() moves BLANK before FILLED [Closes #233]
fixes addText()->setRequired()->addCondition(Form::BLANK)->toggle(), ie. condition after required
1 parent 64442a6 commit 519ad85

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

src/Forms/Rules.php

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -289,11 +289,15 @@ public static function validateRule(Rule $rule): bool
289289
*/
290290
public function getIterator(): \Iterator
291291
{
292-
$rules = $this->rules;
293-
if ($this->required) {
294-
array_unshift($rules, $this->required);
292+
$priorities = [
293+
0 => [], // BLANK
294+
1 => $this->required ? [$this->required] : [],
295+
2 => [], // other rules
296+
];
297+
foreach ($this->rules as $rule) {
298+
$priorities[$rule->validator === Form::BLANK && $rule->control === $this->control ? 0 : 2][] = $rule;
295299
}
296-
return new \ArrayIterator($rules);
300+
return new \ArrayIterator(array_merge(...$priorities));
297301
}
298302

299303

tests/Forms/Rules.required.phpt

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ test(function () { // Rules
4343
});
4444

4545

46-
test(function () { // 'required' is always the first rule
46+
test(function () { // 'required/blank' is always the first rule
4747
$form = new Form;
4848
$input = $form->addText('text');
4949
$rules = $input->getRules();
@@ -59,8 +59,17 @@ test(function () { // 'required' is always the first rule
5959
@$rules->addRule(~$form::REQUIRED); // @ - negative rules are deprecated
6060
$items = iterator_to_array($rules);
6161
Assert::count(3, $items);
62-
Assert::same(Form::BLANK, $items[2]->validator);
63-
Assert::false($items[2]->isNegative);
62+
Assert::same(Form::BLANK, $items[0]->validator);
63+
Assert::false($items[0]->isNegative);
64+
65+
Assert::false($rules->validate());
66+
Assert::same(['This field is required.'], $input->getErrors());
67+
68+
$rules->addCondition($form::BLANK);
69+
$items = iterator_to_array($rules);
70+
Assert::count(4, $items);
71+
Assert::same(Form::BLANK, $items[0]->validator);
72+
Assert::same(Form::BLANK, $items[1]->validator);
6473

6574
Assert::false($rules->validate());
6675
Assert::same(['This field is required.'], $input->getErrors());

0 commit comments

Comments
 (0)