Skip to content

Commit 6f9a577

Browse files
committed
Fix "Not" rule on first level
1 parent 62761ff commit 6f9a577

File tree

2 files changed

+40
-29
lines changed

2 files changed

+40
-29
lines changed

library/Rules/Not.php

Lines changed: 20 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -20,56 +20,47 @@ class Not extends AbstractRule
2020

2121
public function __construct(Validatable $rule)
2222
{
23-
if ($rule instanceof AllOff) {
24-
$rule = $this->absorbComposite($rule);
25-
}
26-
2723
$this->rule = $rule;
2824
}
2925

3026
public function validate($input)
3127
{
32-
if ($this->rule instanceof AllOff) {
33-
return $this->rule->validate($input);
34-
}
35-
36-
return!$this->rule->validate($input);
28+
return (false == $this->rule->validate($input));
3729
}
3830

3931
public function assert($input)
4032
{
41-
if ($this->rule instanceof AllOff) {
42-
return $this->rule->assert($input);
33+
if ($this->validate($input)) {
34+
return true;
4335
}
4436

45-
try {
46-
$this->rule->assert($input);
47-
} catch (ValidationException $e) {
48-
return true;
37+
$rule = $this->rule;
38+
if ($rule instanceof AllOf) {
39+
$rule = $this->absorbAllOf($rule, $input);
4940
}
5041

51-
throw $this->rule
42+
throw $rule
5243
->reportError($input)
5344
->setMode(ValidationException::MODE_NEGATIVE);
5445
}
5546

56-
protected function absorbComposite(AbstractComposite $compositeRule)
47+
private function absorbAllOf(AllOf $rule, $input)
5748
{
58-
if (!$compositeRule instanceof AllOff) {
59-
return $compositeRule;
60-
}
61-
62-
$compositeRuleClone = clone $compositeRule;
63-
$compositeRuleClone->removeRules();
49+
$rules = $rule->getRules();
50+
$current = null;
51+
while (($current = array_shift($rules))) {
52+
$rule = $current;
53+
if (!$rule instanceof AllOf) {
54+
continue;
55+
}
6456

65-
foreach ($compositeRule->getRules() as $rule) {
66-
if ($rule instanceof AbstractComposite) {
67-
$compositeRuleClone->addRule($this->absorbComposite($rule));
68-
} else {
69-
$compositeRuleClone->addRule(new static($rule));
57+
if (!$rule->validate($input)) {
58+
continue;
7059
}
60+
61+
$rules = $rule->getRules();
7162
}
7263

73-
return $compositeRuleClone;
64+
return $rule;
7465
}
7566
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
--TEST--
2+
not() with recursion should update mode from related rules
3+
--FILE--
4+
<?php
5+
require 'vendor/autoload.php';
6+
7+
use Respect\Validation\Validator;
8+
use Respect\Validation\Exceptions\ValidationExceptionInterface;
9+
10+
try {
11+
$validator = Validator::not(
12+
Validator::intVal()->positive()
13+
);
14+
$validator->check(2);
15+
} catch (ValidationExceptionInterface $exception) {
16+
echo $exception->getMainMessage().PHP_EOL;
17+
}
18+
?>
19+
--EXPECTF--
20+
2 must not be positive

0 commit comments

Comments
 (0)