Skip to content
Permalink
Browse files

Allowing Entity to get errors in nested entities

  • Loading branch information...
lorenzo committed Dec 23, 2013
1 parent 13b25e1 commit 2109a5cc6f016faeff0c5bfb6a56d050efb45e1c
Showing with 70 additions and 1 deletion.
  1. +38 −1 Cake/ORM/Entity.php
  2. +32 −0 Cake/Test/TestCase/ORM/EntityTest.php
@@ -605,7 +605,11 @@ public function errors($field = null, $errors = null) {
}
if (is_string($field) && $errors === null) {
return isset($this->_errors[$field]) ? $this->_errors[$field] : [];
$errors = isset($this->_errors[$field]) ? $this->_errors[$field] : [];
if (!$errors) {
$errors = $this->_nestedErrors($field);
}
return $errors;
}
if (!is_array($field)) {
@@ -619,6 +623,39 @@ public function errors($field = null, $errors = null) {
return $this;
}
/**
* Auxiliary method for getting errors in nested entities
*
* @param string field the field in this entity to check for errors
* @return array errors in nested entity if any
*/
protected function _nestedErrors($field) {
if (!isset($this->_properties[$field])) {
return [];
}
$value = $this->_properties[$field];
if (is_scalar($value) || (is_object($value) && !($value instanceof self))) {
return [];
}
if ($value instanceof self) {
return $value->errors();
}
$errors = [];
if (is_array($value) || $value instanceof \Traversable) {
foreach ($value as $k => $v) {
if (!($v instanceof self)) {
break;
}
$errors[$k] = $v->errors();
}
}
return $errors;
}
/**
* Stores whether or not a property value can be changed or set in this entity.
* The special property '*' can also be marked as accessible or protected, meaning
@@ -781,6 +781,38 @@ public function testErrors() {
$this->assertEquals($errors, $entity->errors());
}
/**
* Tests that it is possible to get errors for nested entities
*
* @return void
*/
public function testErrorsDeep() {
$entity = new Entity;
$entity2 = new Entity;
$entity3 = new Entity;
$entity->set('foo', 'bar');
$entity->set('thing', 'baz');
$entity->set('user', $entity2);
$entity->set('owner', $entity3);
$entity->errors('thing', ['this is a mistake']);
$entity2->errors(['a' => ['error1'], 'b' => ['error2']]);
$entity3->errors(['c' => ['error3'], 'd' => ['error4']]);
$expected = ['a' => ['error1'], 'b' => ['error2']];
$this->assertEquals($expected, $entity->errors('user'));
$expected = ['c' => ['error3'], 'd' => ['error4']];
$this->assertEquals($expected, $entity->errors('owner'));
$entity->set('multiple', [$entity2, $entity3]);
$expected = [
['a' => ['error1'], 'b' => ['error2']],
['c' => ['error3'], 'd' => ['error4']]
];
$this->assertEquals($expected, $entity->errors('multiple'));
}
/**
* Tests that changing the value of a property will remove errors
* stored for it

0 comments on commit 2109a5c

Please sign in to comment.
You can’t perform that action at this time.