Skip to content

Commit

Permalink
Added validation to Marshaller::merge()
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Nov 23, 2014
1 parent 0daf589 commit bd185ac
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/ORM/Marshaller.php
Expand Up @@ -307,16 +307,22 @@ protected function _loadBelongsToMany($assoc, $ids) {
* @return \Cake\Datasource\EntityInterface
*/
public function merge(EntityInterface $entity, array $data, array $options = []) {
$options += ['validate' => true];
$propertyMap = $this->_buildPropertyMap($options);
$tableName = $this->_table->alias();

if (isset($data[$tableName])) {
$data = $data[$tableName];
}

$errors = $this->_validate($data, $options, false);
$schema = $this->_table->schema();
$properties = [];
foreach ($data as $key => $value) {
if (!empty($errors[$key])) {
continue;
}

$columnType = $schema->columnType($key);
$original = $entity->get($key);

Expand All @@ -340,6 +346,7 @@ public function merge(EntityInterface $entity, array $data, array $options = [])

if (!isset($options['fieldList'])) {
$entity->set($properties);
$entity->errors($errors);
return $entity;
}

Expand All @@ -349,6 +356,7 @@ public function merge(EntityInterface $entity, array $data, array $options = [])
}
}

$entity->errors($errors);
return $entity;
}

Expand Down
36 changes: 36 additions & 0 deletions tests/TestCase/ORM/MarshallerTest.php
Expand Up @@ -1603,4 +1603,40 @@ public function testPassingCustomValidator() {
$this->assertNotEmpty($entity->errors('thing'));
}

/**
* Test merge with validation error
*
* @return void
*/
public function testMergeWithValidation() {
$data = [
'title' => 'My title',
'author_id' => 'foo',
];
$marshall = new Marshaller($this->articles);
$entity = new Entity([
'title' => 'Foo',
'body' => 'My Content',
'author_id' => 1
]);
$entity->accessible('*', true);
$entity->isNew(false);
$entity->clean();

$this->articles->validator()
->requirePresence('thing', 'update')
->add('author_id', 'numeric', ['rule' => 'numeric']);

$expected = clone $entity;
$result = $marshall->merge($expected, $data, []);

$this->assertSame($expected, $result);
$this->assertSame(1, $result->author_id);
$this->assertNotEmpty($result->errors('thing'));

$this->articles->validator()->requirePresence('thing', 'create');
$result = $marshall->merge($entity, $data, []);
$this->assertEmpty($result->errors('thing'));
}

}

0 comments on commit bd185ac

Please sign in to comment.