Skip to content

Commit

Permalink
Fix "Not" rule on first level
Browse files Browse the repository at this point in the history
  • Loading branch information
henriquemoody committed Oct 14, 2015
1 parent 62761ff commit 6f9a577
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 29 deletions.
49 changes: 20 additions & 29 deletions library/Rules/Not.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,56 +20,47 @@ class Not extends AbstractRule

public function __construct(Validatable $rule)
{
if ($rule instanceof AllOff) {
$rule = $this->absorbComposite($rule);
}

$this->rule = $rule;
}

public function validate($input)
{
if ($this->rule instanceof AllOff) {
return $this->rule->validate($input);
}

return!$this->rule->validate($input);
return (false == $this->rule->validate($input));
}

public function assert($input)
{
if ($this->rule instanceof AllOff) {
return $this->rule->assert($input);
if ($this->validate($input)) {
return true;
}

try {
$this->rule->assert($input);
} catch (ValidationException $e) {
return true;
$rule = $this->rule;
if ($rule instanceof AllOf) {
$rule = $this->absorbAllOf($rule, $input);
}

throw $this->rule
throw $rule
->reportError($input)
->setMode(ValidationException::MODE_NEGATIVE);
}

protected function absorbComposite(AbstractComposite $compositeRule)
private function absorbAllOf(AllOf $rule, $input)
{
if (!$compositeRule instanceof AllOff) {
return $compositeRule;
}

$compositeRuleClone = clone $compositeRule;
$compositeRuleClone->removeRules();
$rules = $rule->getRules();
$current = null;
while (($current = array_shift($rules))) {
$rule = $current;
if (!$rule instanceof AllOf) {
continue;
}

foreach ($compositeRule->getRules() as $rule) {
if ($rule instanceof AbstractComposite) {
$compositeRuleClone->addRule($this->absorbComposite($rule));
} else {
$compositeRuleClone->addRule(new static($rule));
if (!$rule->validate($input)) {
continue;
}

$rules = $rule->getRules();
}

return $compositeRuleClone;
return $rule;
}
}
20 changes: 20 additions & 0 deletions tests/integration/not_without_recursion.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
--TEST--
not() with recursion should update mode from related rules
--FILE--
<?php
require 'vendor/autoload.php';

use Respect\Validation\Validator;
use Respect\Validation\Exceptions\ValidationExceptionInterface;

try {
$validator = Validator::not(
Validator::intVal()->positive()
);
$validator->check(2);
} catch (ValidationExceptionInterface $exception) {
echo $exception->getMainMessage().PHP_EOL;
}
?>
--EXPECTF--
2 must not be positive

0 comments on commit 6f9a577

Please # to comment.