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'], $data['_version']);
$doc = new ElasticaDocument($id, $data);
$doc->setAutoPopulate(true);
$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;
}