bcit-ci / CodeIgniter

Open Source PHP Framework (originally from EllisLab)
https://codeigniter.com/
MIT License
18.27k stars 7.61k forks source link

Model.php Return Type Object causes Error when Saving. (Fixed with this modification) #4950

Closed timothymarois closed 7 years ago

timothymarois commented 7 years ago

Currently if you use your models to return data types of object instead of array, you will be hit with an error once you try to use the save() method. Because of the doProtectedFields, to resolve this. the method should look like this (checking if its an object first)

    protected function doProtectFields($data)
    {
        if (empty($this->allowedFields))
        {
            if ($this->protectFields === false) return $data;

            throw new DatabaseException('No Allowed fields specified for model: '. get_class($this));
        }

        foreach ($data as $key => $val)
        {
            if ( ! in_array($key, $this->allowedFields))
            {
                if (is_object($data)) {
                    unset($data->$key);
                }
                else {
                    unset($data[$key]);
                }
            }
        }

        return $data;
    }
timothymarois commented 7 years ago

Found more issues with return type of object. Within the method update() must update to

if ($this->useTimestamps && ! array_key_exists($this->updatedField, $data))
{
    if (is_object($data)) {
        $data->{$this->updatedField} = $this->setDate();
    }
    else {
            $data[$this->updatedField] = $this->setDate();
    }
}

(again, its being caused because it believes all data is returned as an array. I would fork and fix these myself, but Im busy on other projects and finding these along the way)

jim-parry commented 7 years ago

Er, I don't see doProtectFields in the repo !? Is this a support issue or a bug report?

jim-parry commented 7 years ago

You have raised this in the CodeIgniter3 repo, and it looks like a CodeIgniter4 issue.

timothymarois commented 7 years ago

Oh.... whoops. This is for CI4. I just realized I'm posting on the wrong Repo.