Skip to content

Commit

Permalink
Making calls to Entity::error() not overwrite by default previous errors
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Dec 3, 2014
1 parent 40e0261 commit 0013cce
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
3 changes: 2 additions & 1 deletion src/Datasource/EntityInterface.php
Expand Up @@ -173,9 +173,10 @@ public function validate(Validator $validator);
*
* @param string|array $field The field to get errors for.
* @param string|array $errors The errors to be set for $field
* @param bool $overwrite Whether or not to overwite pre-existing errors for $field
* @return array|\Cake\Datasource\EntityInterface
*/
public function errors($field = null, $errors = null);
public function errors($field = null, $errors = null, $overwrite = false);

/**
* Stores whether or not a property value can be changed or set in this entity.
Expand Down
9 changes: 7 additions & 2 deletions src/Datasource/EntityTrait.php
Expand Up @@ -630,9 +630,10 @@ public function validate(Validator $validator) {
*
* @param string|array $field The field to get errors for, or the array of errors to set.
* @param string|array $errors The errors to be set for $field
* @param bool $overwrite Whether or not to overwite pre-existing errors for $field
* @return array|$this
*/
public function errors($field = null, $errors = null) {
public function errors($field = null, $errors = null, $overwrite = false) {
if ($field === null) {
return $this->_errors;
}
Expand All @@ -650,8 +651,12 @@ public function errors($field = null, $errors = null) {
}

foreach ($field as $f => $error) {
$this->_errors[$f] = (array)$error;
$this->_errors += [$f => []];
$this->_errors[$f] = $overwrite ?
(array)$error :
array_merge($this->_errors[$f], (array)$error);
}

return $this;
}

Expand Down
6 changes: 3 additions & 3 deletions tests/TestCase/ORM/EntityTest.php
Expand Up @@ -802,16 +802,16 @@ public function testErrors() {
$this->assertEquals([], $entity->errors('boo'));

$entity->errors('foo', 'other error');
$this->assertEquals(['other error'], $entity->errors('foo'));
$this->assertEquals(['bar', 'other error'], $entity->errors('foo'));

$entity->errors('bar', ['something', 'bad']);
$this->assertEquals(['something', 'bad'], $entity->errors('bar'));

$expected = ['foo' => ['other error'], 'bar' => ['something', 'bad']];
$expected = ['foo' => ['bar', 'other error'], 'bar' => ['something', 'bad']];
$this->assertEquals($expected, $entity->errors());

$errors = ['foo' => ['something'], 'bar' => 'else', 'baz' => ['error']];
$this->assertSame($entity, $entity->errors($errors));
$this->assertSame($entity, $entity->errors($errors, null, true));
$errors['bar'] = ['else'];
$this->assertEquals($errors, $entity->errors());
}
Expand Down

0 comments on commit 0013cce

Please sign in to comment.