Controller_Data_Mongo::save PHP Метод

save() публичный Метод

public save ( $model, $id = null )
    public function save($model, $id = null)
    {
        $data = array();
        foreach ($model->elements as $name => $f) {
            if ($f instanceof Field) {
                if (!$f->editable() && !$f->system()) {
                    continue;
                }
                if (!isset($model->dirty[$name]) && $f->defaultValue() === null) {
                    continue;
                }
                $value = $f->get();
                if ($f->type() == 'boolean' && is_bool($value)) {
                    $value = (bool) $value;
                }
                if ($f->type() == 'int') {
                    $value = (int) $value;
                }
                if ($f->type() == 'money' || $f->type() == 'float') {
                    $value = (double) $value;
                }
                $data[$name] = $value;
            }
        }
        unset($data[$model->id_field]);
        foreach ($model->_references as $our_field => $junk) {
            if (isset($data[$our_field]) && $data[$our_field] && $our_field != $model->id_field) {
                $deref = str_replace('_id', '', $our_field);
                if ($deref == $our_field) {
                    continue;
                }
                $m = $model->ref($our_field);
                if (!$m->loaded()) {
                    continue;
                }
                $data[$deref] = $m[$m->title_field];
                if ($m instanceof Mongo_Model) {
                    $data[$our_field] = new MongoID($data[$our_field]);
                }
            }
        }
        if ($model->loaded()) {
            if (empty($data)) {
                if ($model->debug) {
                    echo '<font style="color: blue">db.' . $model->table . ' is not dirty</font>';
                }
                return $model->id;
            }
            if ($model->debug) {
                echo '<font style="color: blue">db.' . $model->table . '.update({_id: ' . new MongoID($model->id) . '},{"$set":' . json_encode($data) . '})</font>';
            }
            $this->_get($model, 'db')->update(array($model->id_field => new MongoID($model->id)), array('$set' => $data));
            return $model->id;
        }
        if ($model->debug) {
            echo '<font style="color: blue">db.' . $model->table . '.save(' . json_encode($data) . ')</font>';
        }
        $this->_get($model, 'db')->save($data);
        $model->id = (string) $data[$model->id_field] ?: null;
        $model->data = $data;
        // will grab defaults here
        if ($model->debug) {
            echo '<font style="color: blue">=' . $model->id . '</font><br/>';
        }
        $model->dirty = array();
        return $model->id;
    }