diff --git a/src/Bridge/Doctrine/DBAL/Types/AbstractEnumType.php b/src/Bridge/Doctrine/DBAL/Types/AbstractEnumType.php index 10736f2..0f26c58 100644 --- a/src/Bridge/Doctrine/DBAL/Types/AbstractEnumType.php +++ b/src/Bridge/Doctrine/DBAL/Types/AbstractEnumType.php @@ -47,16 +47,26 @@ protected function onNullFromPhp(): int|string|null /** * {@inheritdoc} * - * @param \BackedEnum|null $value + * @param \BackedEnum|int|string|null $value */ public function convertToDatabaseValue($value, AbstractPlatform $platform): string|int|null { - if ($value !== null && !$value instanceof \BackedEnum) { - throw new InvalidArgumentException(sprintf( - 'Expected an instance of a %s. %s given.', - \BackedEnum::class, - get_debug_type($value), - )); + if ($value !== null && !is_a($value, $this->getEnumClass())) { + $throwException = true; + if ($this->checkIfValueMatchesBackedEnumType($value)) { + $value = $this->getEnumClass()::tryFrom($this->cast($value)); + if ($value !== null) { + $throwException = false; + } + } + + if ($throwException) { + throw new InvalidArgumentException(sprintf( + 'Expected an instance of a %s. %s given.', + $this->getEnumClass(), + get_debug_type($value), + )); + } } if (null === $value) { @@ -119,6 +129,11 @@ private function cast(int|string $value): int|string return $this->isIntBackedEnum() ? (int) $value : (string) $value; } + private function checkIfValueMatchesBackedEnumType(mixed $value): bool + { + return ($this->isIntBackedEnum() && \is_int($value)) || (!$this->isIntBackedEnum() && \is_string($value)); + } + private function isIntBackedEnum(): bool { if (!isset($this->isIntBackedEnum)) {