Skip to content

Commit

Permalink
bug #215 Fix AbstractEnumType convertToDatabase function to support s…
Browse files Browse the repository at this point in the history
…tring|int (michnovka)

This PR was merged into the 2.x-dev branch.

Discussion
----------

Fix AbstractEnumType convertToDatabase function to support string|int

Fixes #199

Commits
-------

b41fa68 Fix AbstractEnumType convertToDatabase function to support string|int values
  • Loading branch information
ogizanagi committed Jan 3, 2024
2 parents 8b09a3a + b41fa68 commit a64a1fa
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions src/Bridge/Doctrine/DBAL/Types/AbstractEnumType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)) {
Expand Down

0 comments on commit a64a1fa

Please sign in to comment.