Skip to content

Commit bd185ac

Browse files
committed
Added validation to Marshaller::merge()
1 parent 0daf589 commit bd185ac

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/ORM/Marshaller.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,16 +307,22 @@ protected function _loadBelongsToMany($assoc, $ids) {
307307
* @return \Cake\Datasource\EntityInterface
308308
*/
309309
public function merge(EntityInterface $entity, array $data, array $options = []) {
310+
$options += ['validate' => true];
310311
$propertyMap = $this->_buildPropertyMap($options);
311312
$tableName = $this->_table->alias();
312313

313314
if (isset($data[$tableName])) {
314315
$data = $data[$tableName];
315316
}
316317

318+
$errors = $this->_validate($data, $options, false);
317319
$schema = $this->_table->schema();
318320
$properties = [];
319321
foreach ($data as $key => $value) {
322+
if (!empty($errors[$key])) {
323+
continue;
324+
}
325+
320326
$columnType = $schema->columnType($key);
321327
$original = $entity->get($key);
322328

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

341347
if (!isset($options['fieldList'])) {
342348
$entity->set($properties);
349+
$entity->errors($errors);
343350
return $entity;
344351
}
345352

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

359+
$entity->errors($errors);
352360
return $entity;
353361
}
354362

tests/TestCase/ORM/MarshallerTest.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1603,4 +1603,40 @@ public function testPassingCustomValidator() {
16031603
$this->assertNotEmpty($entity->errors('thing'));
16041604
}
16051605

1606+
/**
1607+
* Test merge with validation error
1608+
*
1609+
* @return void
1610+
*/
1611+
public function testMergeWithValidation() {
1612+
$data = [
1613+
'title' => 'My title',
1614+
'author_id' => 'foo',
1615+
];
1616+
$marshall = new Marshaller($this->articles);
1617+
$entity = new Entity([
1618+
'title' => 'Foo',
1619+
'body' => 'My Content',
1620+
'author_id' => 1
1621+
]);
1622+
$entity->accessible('*', true);
1623+
$entity->isNew(false);
1624+
$entity->clean();
1625+
1626+
$this->articles->validator()
1627+
->requirePresence('thing', 'update')
1628+
->add('author_id', 'numeric', ['rule' => 'numeric']);
1629+
1630+
$expected = clone $entity;
1631+
$result = $marshall->merge($expected, $data, []);
1632+
1633+
$this->assertSame($expected, $result);
1634+
$this->assertSame(1, $result->author_id);
1635+
$this->assertNotEmpty($result->errors('thing'));
1636+
1637+
$this->articles->validator()->requirePresence('thing', 'create');
1638+
$result = $marshall->merge($entity, $data, []);
1639+
$this->assertEmpty($result->errors('thing'));
1640+
}
1641+
16061642
}

0 commit comments

Comments
 (0)