public function update(EntityInterface $entity, array $options = [])
{
// Run beforeSave and beforeUpdate to know whether or not we can continue
if (false === $this->eventEmitter()->emit('beforeSave', [$entity, $this]) || false === $this->eventEmitter()->emit('beforeUpdate', [$entity, $this])) {
return false;
}
// Run validation unless disabled via options
if (!isset($options['validate']) || isset($options['validate']) && $options['validate'] !== false) {
if (!$this->validate($entity, $options)) {
return false;
}
}
if (isset($options['relations']) && $options['relations'] === true) {
$this->saveBelongsToRelations($entity, $options);
}
// Prepare data
$data = $entity->dataModified();
// Save only known, defined fields
$entityFields = $this->fields();
$entityName = $this->entity();
$extraData = array_diff_key($data, $entityFields);
$data = array_intersect_key($data, $entityFields);
// If there are extra fields here, throw an error
if (!isset($options['strict']) || isset($options['strict']) && $options['strict'] === true) {
if (count($extraData) > 0) {
throw new Exception("Update error: Unknown fields provided for " . $entityName . ": '" . implode("', '", array_keys($extraData)) . "'");
}
}
// Do type conversion
$data = $this->convertToDatabaseValues($entityName, $data);
if (count($data) > 0) {
$result = $this->resolver()->update($this->table(), $data, [$this->primaryKeyField() => $this->primaryKey($entity)]);
$entity->data($entity->data(null, true, false), false);
if (isset($options['relations']) && $options['relations'] === true) {
$this->saveHasRelations($entity, $options);
}
// Run afterSave and afterUpdate
if (false === $this->eventEmitter()->emit('afterSave', [$entity, $this, &$result]) || false === $this->eventEmitter()->emit('afterUpdate', [$entity, $this, &$result])) {
$result = false;
}
} else {
$result = true;
if (isset($options['relations']) && $options['relations'] === true) {
$this->saveHasRelations($entity, $options);
}
}
return $result;
}