public function RestfulEntityBase::entityValidate in RESTful 7
Validate an entity before it is saved.
Parameters
\EntityMetadataWrapper $wrapper: The wrapped entity.
Throws
1 call to RestfulEntityBase::entityValidate()
- RestfulEntityBase::setPropertyValues in plugins/
restful/ RestfulEntityBase.php - Set properties of the entity based on the request, and save the entity.
File
- plugins/
restful/ RestfulEntityBase.php, line 1006 - Contains RestfulEntityBase.
Class
- RestfulEntityBase
- An abstract implementation of RestfulEntityInterface.
Code
public function entityValidate(\EntityMetadataWrapper $wrapper) {
$this
->validateFields($wrapper);
if (!module_exists('entity_validator')) {
// Entity validator doesn't exist.
return;
}
if (!($handler = entity_validator_get_validator_handler($wrapper
->type(), $wrapper
->getBundle()))) {
// Entity validator handler doesn't exist for the entity.
return;
}
if ($handler
->validate($wrapper
->value(), TRUE)) {
// Entity is valid.
return;
}
$errors = $handler
->getErrors(FALSE);
$map = array();
foreach ($this
->getPublicFields() as $field_name => $value) {
if (empty($value['property'])) {
continue;
}
if (empty($errors[$value['property']])) {
// Field validated.
continue;
}
$map[$value['property']] = $field_name;
$params['@fields'][] = $field_name;
}
if (empty($params['@fields'])) {
// There was a validation error, but on non-public fields, so we need to
// throw an exception, but can't say on which fields it occurred.
throw new \RestfulBadRequestException('Invalid value(s) sent with the request.');
}
$params['@fields'] = implode(',', $params['@fields']);
$e = new \RestfulBadRequestException(format_plural(count($map), 'Invalid value in field @fields.', 'Invalid values in fields @fields.', $params));
foreach ($errors as $property_name => $messages) {
if (empty($map[$property_name])) {
// Entity is not valid, but on a field not public.
continue;
}
$field_name = $map[$property_name];
foreach ($messages as $message) {
$message['params']['@field'] = $field_name;
$output = format_string($message['message'], $message['params']);
$e
->addFieldError($field_name, $output);
}
}
// Throw the exception.
throw $e;
}