public function save($entity, $data = null, array $options = array())
{
$self = static::_object();
$_meta = array('model' => get_called_class()) + $self->_meta;
$_schema = $self->schema();
$defaults = array('validate' => true, 'events' => $entity->exists() ? 'update' : 'create', 'whitelist' => null, 'callbacks' => true, 'locked' => $self->_meta['locked']);
$options += $defaults;
$params = compact('entity', 'data', 'options');
$filter = function ($self, $params) use($_meta, $_schema) {
$entity = $params['entity'];
$options = $params['options'];
if ($params['data']) {
$entity->set($params['data']);
}
if (($whitelist = $options['whitelist']) || $options['locked']) {
$whitelist = $whitelist ?: array_keys($_schema->fields());
}
if ($rules = $options['validate']) {
$events = $options['events'];
$validateOpts = compact('events', 'whitelist');
if (is_array($rules)) {
$validateOpts['rules'] = $rules;
}
if (!$entity->validates($validateOpts)) {
return false;
}
}
$type = $entity->exists() ? 'update' : 'create';
$query = $self::invokeMethod('_instance', array('query', compact('type', 'whitelist', 'entity') + $options + $_meta));
return $self::connection()->{$type}($query, $options);
};
if (!$options['callbacks']) {
return $filter(get_called_class(), $params);
}
return static::_filter(__FUNCTION__, $params, $filter);
}