Skip to content

Commit

Permalink
Added option to pass a validation object to the marshaller
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Nov 23, 2014
1 parent 099ce17 commit 0daf589
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 7 deletions.
32 changes: 25 additions & 7 deletions src/ORM/Marshaller.php
Expand Up @@ -114,13 +114,7 @@ public function one(array $data, array $options = []) {
}
}

$errors = [];
if ($options['validate']) {
$type = is_string($options['validate']) ? $options['validate'] : 'default';
$validator = $this->_table->validator($type);
$errors = $validator->errors($data, $entity->isNew());
}

$errors = $this->_validate($data, $options, true);
$primaryKey = $schema->primaryKey();
$properties = [];
foreach ($data as $key => $value) {
Expand Down Expand Up @@ -157,6 +151,30 @@ public function one(array $data, array $options = []) {
return $entity;
}

/**
* Returns the validation errors for a data set based on the passed options
*
* @param array $data The data to validate.
* @param array $options The options passed to this marshaller.
* @param bool $isNew Whether it is a new entity or one to be updated.
* @return array The list of validation errors.
*/
protected function _validate($data, $options, $isNew) {
if (!$options['validate']) {
return [];
}

if ($options['validate'] === true) {
$options['validate'] = $this->_table->validator('default');
}

if (is_string($options['validate'])) {
$options['validate'] = $this->_table->validator($options['validate']);
}

return $options['validate']->errors($data, $isNew);
}

/**
* Create a new sub-marshaller and marshal the associated data.
*
Expand Down
18 changes: 18 additions & 0 deletions tests/TestCase/ORM/MarshallerTest.php
Expand Up @@ -1585,4 +1585,22 @@ public function testSkipValidation() {
$this->assertEmpty($entity->user->errors('thing'));
}

/**
* Tests that it is possible to pass a validator directly in the options
*
* @return void
*/
public function testPassingCustomValidator() {
$data = [
'title' => 'Thing',
'body' => 'hey'
];

$validator = clone $this->articles->validator();
$validator->requirePresence('thing');
$marshall = new Marshaller($this->articles);
$entity = $marshall->one($data, ['validate' => $validator]);
$this->assertNotEmpty($entity->errors('thing'));
}

}

0 comments on commit 0daf589

Please sign in to comment.