public function save() { $def = $this->getDefinition(); $db = $this->getAdapter(); $filesToCopy = array(); $columns = array(); $placeHolders = array(); $updates = array(); $values = array(); //Add fields foreach (array_keys($def['columns']) as $column) { if ($column == 'id') { continue; } $setField = true; //Check for owner fields if ($this->isOwnerField($column)) { $ownerName = substr($column, 0, -3); if (isset($this->_data[$ownerName])) { $this->{$column} = $this->_data[$ownerName]->id; } } $value = $this->{$column}; //Run preSave functions $columnCamelized = \ATP\Inflector::camelize($column); $func = "preSave{$columnCamelized}"; if (method_exists($this, $func)) { $value = $this->{$func}($value); } //Process file fields if (is_array($value)) { if ($value['error'] != 4) { $filesToCopy[$column] = $value; $file = new \ATP\ActiveRecord\File(); $file->setFrom($value); $value = $file; $this->{$column} = $file; } else { //Don't update the file field if there was an error or no new file was updated $setField = false; } } //Serialize file fields if (is_object($value)) { $value = $value->toJson(); } //Add the field to the query if ($setField) { if ($this->isOwnerField($column) && empty($value)) { $value = null; } $columns[] = "`{$column}`"; $values[] = $value; $placeHolders[] = "?"; $updates[] = "`{$column}`=?"; } } if (!$this->id) { //Insert new object if id is not set $sql = "INSERT INTO {$def['table']} "; $sql .= "(" . implode(", ", $columns) . ") values ("; $sql .= implode(", ", $placeHolders); $sql .= ") ON DUPLICATE KEY UPDATE "; $sql .= implode(", ", $updates); $values = array_merge($values, $values); } else { //Otherwise, update existing object $sql = "UPDATE {$def['table']} SET "; $sql .= implode(", ", $updates); $sql .= " WHERE id=" . $this->id; $sql .= " LIMIT 1"; } //Save object $stmt = $db->query($sql, $values); //Update id if needed $id = $this->id; if (empty($id)) { $this->id = $db->getDriver()->getLastGeneratedValue(); } //Process files foreach ($filesToCopy as $name => $data) { $path = realpath(dirname($_SERVER['SCRIPT_FILENAME'])); $path .= "/uploads"; $path .= "/{$def['table']}/{$this->id}/"; if (!is_dir($path)) { mkdir($path, 0755, true); } $path .= $data['name']; if (!move_uploaded_file($data['tmp_name'], $path)) { die; } } $this->postSave(); }
public function temp() { $models = \Zend_Registry::get('config')->models->toArray(); $className = $models[\ATP\Inflector::camelize($this->_type)]['class']; return new $className(); }