/** * Сохранение записи * * @param array $data * @return $this */ public function save(array $data) { // Не пропускаем к базе возможно установленные левые ключи $data = array_intersect_key($data, array_flip(static::fields())); $this->data = array_merge($this->data, $data); // Ничего на обновление нет? if (!$this->data) { return $this; } // intersect потому что обработка переменных идет на $this->data, посылам только нужные запросы на сервер $data = array_intersect_key($this->data, $data); if ($this->validate($data)->errors) { return $this; } $saved = false; // Валидация прошла успешно, обновляем или вставляем новую запись if (!$this->is_new) { // Если не нужно обновлять главный ключ if (isset($this->data['id']) && $this->id === (string) $this->data['id']) { unset($this->data['id']); } $saved = $this->dbUpdateByIds($data, [$this->id]); $this->data['id'] = $this->id; // Обновим кэш завершающим этапом // В кэш обработанные данные через prepare не попадают Cache::remove(static::class . ':' . $this->getId()); } else { if (isset($data['id'])) { $this->id = (string) $data['id']; } if (!$this->id) { $this->id = static::generateId(); } $data['id'] = $this->id; $saved = $this->dbInsert($data); // Дополняем нулл значениями $this->data = array_merge(array_fill_keys(static::fields(), null), $data); } if ($saved) { $this->is_new ? $this->onCreate() : $this->onUpdate(); $this->onSave(); } $this->is_new = false; $this->prepare($this->data); return $this; }