Skip to content

Commit

Permalink
Add a way to restore 3.x behavior for last=true
Browse files Browse the repository at this point in the history
  • Loading branch information
dereuromark committed Aug 29, 2020
1 parent fee4015 commit 9c88bdf
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/Validation/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,13 @@ class Validator implements ArrayAccess, IteratorAggregate, Countable
*/
protected $_allowEmptyFlags = [];

/**
* Whether to apply last flag to rule(s).
*
* @var bool
*/
protected $_last = false;

/**
* Constructor
*/
Expand All @@ -189,6 +196,18 @@ public function __construct()
$this->_providers = self::$_defaultProviders;
}

/**
* Whether to apply last flag to rule(s).
* The first failing one will abort then per rule.
*
* @param bool $last If to apply last flag.
* @return void
*/
public function enableLast(bool $last = true): void
{
$this->_last = $last;
}

/**
* Validates and returns an array of failed fields and their error messages.
*
Expand Down Expand Up @@ -479,7 +498,10 @@ public function add(string $field, $name, $rule = [])

foreach ($rules as $name => $rule) {
if (is_array($rule)) {
$rule += ['rule' => $name];
$rule += [
'rule' => $name,
'last' => $this->_last,
];
}
if (!is_string($name)) {
/** @psalm-suppress PossiblyUndefinedMethod */
Expand Down Expand Up @@ -2715,6 +2737,7 @@ public function __debugInfo(): array
'_allowEmptyMessages' => $this->_allowEmptyMessages,
'_allowEmptyFlags' => $this->_allowEmptyFlags,
'_useI18n' => $this->_useI18n,
'_last' => $this->_last,
'_providers' => array_keys($this->_providers),
'_fields' => $fields,
];
Expand Down
23 changes: 23 additions & 0 deletions tests/TestCase/Validation/ValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1925,6 +1925,28 @@ public function testUsingClosureAsRule()
$this->assertEquals($expected, $validator->validate(['name' => 'foo']));
}

/**
* Tests that setting last globally will stop validating the rest of the rules
*
* @return void
*/
public function testErrorsWithLastRuleGlobal(): void
{
$validator = new Validator();
$validator->enableLast();
$validator
->notBlank('email', 'Fill something in!')
->email('email', false, 'Y u no write email?');
$errors = $validator->validate(['email' => '']);
$expected = [
'email' => [
'notBlank' => 'Fill something in!',
],
];

$this->assertEquals($expected, $errors);
}

/**
* Tests that setting last to a rule will stop validating the rest of the rules
*
Expand Down Expand Up @@ -2155,6 +2177,7 @@ public function testDebugInfo()
'published' => Validator::EMPTY_STRING,
],
'_useI18n' => true,
'_last' => false,
];
$this->assertEquals($expected, $result);
}
Expand Down

0 comments on commit 9c88bdf

Please sign in to comment.