codeigniter4 / shield

Authentication and Authorization for CodeIgniter 4
https://shield.codeigniter.com
MIT License
352 stars 130 forks source link

Extended UserModel class doesn't execute a function included in the beforeUpdate collection of callbacks #1054

Closed Elvis254 closed 6 months ago

Elvis254 commented 6 months ago

PHP Version

8.2.0

CodeIgniter4 Version

4.4.5

Shield Version

1.0.1

Which operating systems have you tested for this bug?

Windows

Which server did you use?

apache

Database

MariaDB 10.2

Did you customize Shield?

I customized the UserModel class to include a function to generate a full name of a user from their first and last name before insert and before update. I also customized the User entity class to include two functions to set the first and last name of a user after cleaning the string input and performing formatting on it like capitalization.

What happened?

I altered the users table and added four columns on it i.e. fullname, firstname, lastname and mobile. Then extended the UserModel class to add a function that generates a full name beforeInsert and beforeUpdate. The problem arises when the beforeUpdate fails to generate the full name and save it on the users table but the beforeInsert works as expected. I use the full name column for search purposes. Here is the code am using:

namespace App\Models;

use CodeIgniter\Shield\Models\UserModel as ShieldUserModel;

class UserModel extends ShieldUserModel
{
    protected function initialize(): void
    {
        parent::initialize();

        $this->returnType = \App\Entities\User::class;

        $this->allowedFields = [
            ...$this->allowedFields,
            'fullname', 'firstname', 'lastname', 'mobile',
        ];

        $this->beforeInsert = [
            ...$this->beforeInsert,
            'generateFullName'
        ];

        $this->beforeUpdate = [
            ...$this->beforeUpdate,
            'generateFullName'
        ];
    }

    protected function generateFullName(array $data)
    {
        if ( ! isset($data['data']['firstname']) || ! isset($data['data']['lastname'])) {
            return $data;
        }

        $data['data']['fullname'] = $data['data']['firstname'].' '.$data['data']['lastname'];

        return $data;
    }
}

Steps to Reproduce

Make the beforeUpdate functionality work as expected i.e. make it execute the generate full name function.

Expected Output

The full name gets generated and saved on the users table.

Anything else?

No response