LM-Commons / LmcUser

A generic user registration and authentication module for Laminas. Supports Laminas\Db and Doctrine2. (Formerly ZfcUser)
BSD 3-Clause "New" or "Revised" License
14 stars 16 forks source link

Adding new user using base User entity and mapper fails #50

Closed visto9259 closed 3 months ago

visto9259 commented 4 months ago

@matwright

When using the off-the-shelf LmcUser, i.e. using the default \LmcUser\Entity\User class and the default LmcUser\Mapper\User class, the mapper fails when inserting a new user in the user table with the exception:

Laminas\Db\Adapter\Exception\InvalidQueryException
File:
C:\enofily\tutorials\lmc-user-tutorial\vendor\laminas\laminas-db\src\Adapter\Driver\Pdo\Statement.php:223
Message:
Statement could not be executed (23000 - 19 - UNIQUE constraint failed: user.user_id)

I am surprised that no one has ever reported this error before. Probably due to the fact that most people do not use the default classes.

The error is in the setId() method of the \LmcUser\Entity\User class:

    /**
     * Set id.
     *
     * @param  int $id
     * @return UserInterface
     */
    public function setId($id)
    {
        $this->id = (int) $id;
        return $this;
    }

When the $id parameter is null, as it will be when creating a new user from, for example, the register form, then $this->id is set 0. Then when inserting into the database, this id conflicts with the existing user rows that have a user_id of 0.

I understand that the (int) casting would be useful to convert an $id that is not an integer. But null should remain null and not be converted to 0.

Unless you know of other cases where we need to cast a null to 0, I will make the change to this method to set the $id property to null when the $id param is null.