Elao/PhpEnums

Doctrine sometimes converts field value to string. AbstractEnumType should handle this case

Closed this issue · 2 comments

Let me start by saying that I use a custom enum DBAL implementation, but it is heavily based on this one.

This was the problematic code:

$duels = $this->duelRepository->findBy([
    'duelStatus' => DuelStatus::IN_PROGRESS,
]);

Where DuelStatus is an enum field

#[ORM\Column(type: DuelStatus::class, options: ['default' => DuelStatus::IN_PROGRESS->value])]
private DuelStatus $status = DuelStatus::IN_PROGRESS;

The problem was that AbstractEnumType::convertToDatabaseValue() was called with the string value of DuelStatus. So in your implementation, this would throw.

It happens because BasicEntityPersister calls getValues() function which converts enums to strings. However it still internally tracks the type of the field as the AbstractEnumType, so it does eventually call convertToDatabaseValue.

I am quite sure this will result in an exception being thrown in your code - https://github.com/Elao/PhpEnums/blob/2.x/src/Bridge/Doctrine/DBAL/Types/AbstractEnumType.php#L55

I am too busy to check now, just posting here as a TODO. If somebody can please confirm this or rule out this is an issue. I may get some time to look into this later in Feb.

FYI I fixed this in my code by adding this on top of the convertToDatabaseValue function:

        if ($value !== null && !($value instanceof BackedEnum)) {
            /** @var DBALSQLEnumTypeInterface $class */
            $class = static::getEnumClass();
            $value = $class::tryFrom($value);
        }

Duplicate of #199 ?

yes