/** * Abstract save function to handle INSERT and UPDATE queries into * the database. This function will call beforeSave(). If it fails, * it will return false. It will then call validate() which, if it * fails, will return false. Data structures are built based on the * object's class variables. If the object's ID field is null, the * function will run an INSERT query, otherwise it will run an * UPDATE query. Afterwards, the afterSave() function is called. * If this returns true, the query is committed and the function * returns true. Otherwise, it is the query is rolled back and the * function returns false. * * @return bool true on success, false on failure */ public function save() { $this->validate(); if (!empty($this->_errors)) { return false; } if ($this->beforeSave() == false) { return false; } $schema = static::getSchema(); $saveValues = array(); foreach ($this as $col => $val) { if ($schema[$col]['type'] == 'datetime' && $this->{$col} !== null) { $val = $this->{$col}->setTimezone('UTC')->toDateTimeString(); } if ($col == 'created' || $col == 'modified') { continue; } if (array_key_exists($col, $schema)) { $saveValues[$col] = $val; } } // If ID is not null, then UPDATE row in the database, else INSERT new row if ($this->{"{$this->_idField}"}) { // Update query if (array_key_exists('modified', static::getSchema())) { $this->modified = Carbon::now(); $saveValues['modified'] = $this->modified->setTimezone('UTC')->toDateTimeString(); } $success = static::queryBuilder()->update($saveValues)->where(array('id' => $this->{$this->_idField}))->execute(); } else { // Insert query if (array_key_exists('created', static::getSchema())) { $this->created = Carbon::now(); $saveValues['created'] = $this->created->setTimezone('UTC')->toDateTimeString(); } $success = static::queryBuilder()->insert($saveValues)->execute(); $this->{"{$this->_idField}"} = self::$_db->lastInsertId(); } if ($this->afterSave() == false) { return false; } return $success; }