/**
* Persists an entity based on the fields that are marked as dirty and
* returns the same entity after a successful save or false in case
* of any error.
*
* Triggers the `Model.beforeSave` and `Model.afterSave` events.
*
* ## Options
*
* - `checkRules` Defaults to true. Check deletion rules before deleting the record.
*
* @param \Cake\Datasource\EntityInterface $entity The entity to be saved
* @param array $options An array of options to be used for the event
* @return \Cake\Datasource\EntityInterface|bool
*/
public function save(EntityInterface $entity, $options = [])
{
$options += ['checkRules' => true];
$options = new ArrayObject($options);
$event = $this->dispatchEvent('Model.beforeSave', ['entity' => $entity, 'options' => $options]);
if ($event->isStopped()) {
return $event->result;
}
if ($entity->errors()) {
return false;
}
$mode = $entity->isNew() ? RulesChecker::CREATE : RulesChecker::UPDATE;
if ($options['checkRules'] && !$this->checkRules($entity, $mode, $options)) {
return false;
}
$type = $this->connection()->getIndex()->getType($this->name());
$id = $entity->id ?: null;
$data = $entity->toArray();
unset($data[$id]);
$doc = new ElasticaDocument($id, $data);
$doc->setAutoPopulate(true);
$result = $type->addDocument($doc);
$entity->id = $doc->getId();
$entity->_version = $doc->getVersion();
$entity->isNew(false);
$entity->source($this->name());
$entity->clean();
$this->dispatchEvent('Model.afterSave', ['entity' => $entity, 'options' => $options]);
return $entity;
}