Skip to content

Commit

Permalink
Support enums as default values
Browse files Browse the repository at this point in the history
  • Loading branch information
derrabus committed Mar 28, 2022
1 parent 05f8fcf commit 6563423
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/Doctrine/ORM/Tools/SchemaTool.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Doctrine\ORM\Tools;

use BackedEnum;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\AbstractAsset;
Expand Down Expand Up @@ -787,6 +788,10 @@ private function gatherColumnOptions(array $mapping): array
$mappingOptions['enumType'] = $mapping['enumType'];
}

if (($mappingOptions['default'] ?? null) instanceof BackedEnum) {
$mappingOptions['default'] = $mappingOptions['default']->value;
}

if (empty($mappingOptions)) {
return [];
}
Expand Down
23 changes: 23 additions & 0 deletions tests/Doctrine/Tests/Models/Enums/CardWithDefault.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace Doctrine\Tests\Models\Enums;

use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;

#[Entity]
class CardWithDefault
{
#[Id, GeneratedValue, Column]
public int $id;

#[Column(options: ['default' => Suit::Hearts])]
public Suit $suit;

#[Column]
public string $name;
}
15 changes: 15 additions & 0 deletions tests/Doctrine/Tests/ORM/Functional/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Doctrine\ORM\Mapping\MappingException;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\Tests\Models\Enums\Card;
use Doctrine\Tests\Models\Enums\CardWithDefault;
use Doctrine\Tests\Models\Enums\Product;
use Doctrine\Tests\Models\Enums\Quantity;
use Doctrine\Tests\Models\Enums\Suit;
Expand Down Expand Up @@ -159,4 +160,18 @@ public function testEnumMappingWithEmbeddable(): void
$this->assertInstanceOf(Unit::class, $fetchedProduct->quantity->unit);
$this->assertEquals(Unit::Gram, $fetchedProduct->quantity->unit);
}

public function testEnumWithDefault(): void
{
$this->setUpEntitySchema([CardWithDefault::class]);

$table = $this->_em->getClassMetadata(CardWithDefault::class)->getTableName();

$this->_em->getConnection()->insert($table, ['name' => 'My Card']);
$cardId = $this->_em->getConnection()->lastInsertId();

$card = $this->_em->find(CardWithDefault::class, $cardId);

self::assertSame(Suit::Hearts, $card->suit);
}
}

0 comments on commit 6563423

Please sign in to comment.