mtv\wp\models\User::save PHP Method

save() public method

public save ( )
    public function save()
    {
        $this->validate();
        // split the incoming data into stuff we can pass to wp_update_user and
        // stuff we have to add with update_user_meta
        $userdata = parse_user($this->attributes);
        $usermeta = array_diff_assoc($this->attributes, $userdata);
        $removemeta = array_diff(array_keys($this->_previous_attributes), array_keys($this->attributes));
        unset($usermeta['id']);
        // make sure we don't accidently save the id as meta
        // Create
        if (empty($this->id)) {
            // create the new user with all the basic data
            // wp_update_user has bugs that doesn't let you create a user with it
            // http://core.trac.wordpress.org/ticket/17009
            // TODO: just use wp_update_user once the bug is fixed
            $user_id = wp_create_user($userdata['user_login'], $userdata['user_pass'], $userdata['user_email']);
            if (is_wp_error($user_id)) {
                throw new WPException($user_id);
            }
            // We should keep track of our user id
            $userdata['ID'] = $user_id;
            $this->id = $user_id;
            // Update
        } else {
            // Check which data has changed
            $data_to_diff = get_userdata($this->id);
            $data_to_update = array_diff_assoc($userdata, (array) $data_to_diff->data);
            // If we don't have any changes, we don't have to update!
            if (empty($data_to_update)) {
                $userdata = false;
            } else {
                $userdata = array_merge(array('ID' => $this->id), $data_to_update);
            }
        }
        // If we don't have any userdata, we don't have to update!
        if ($userdata) {
            $user_id = wp_update_user($userdata);
            if (is_wp_error($user_id)) {
                throw new WPException($user_id);
            }
        }
        // Update user meta with leftover data
        foreach ($usermeta as $key => $val) {
            update_user_meta($this->id, $key, $val);
        }
        // Remove any deleted meta
        foreach ($removemeta as $key) {
            delete_user_meta($this->id, $key);
        }
        $this->fetch();
    }