Skip to content

Instantly share code, notes, and snippets.

@ninsuo
Created January 3, 2023 10:08
Show Gist options
  • Save ninsuo/a472c6f7c8f271597d5e9ac32ddb9e61 to your computer and use it in GitHub Desktop.
Save ninsuo/a472c6f7c8f271597d5e9ac32ddb9e61 to your computer and use it in GitHub Desktop.
A Doctrine enum type that supports PHP 8 native enums
<?php
namespace App\Doctrine\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;
class EnumType extends Type
{
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
$enumType = $fieldDeclaration['enumType'] ?? null;
if (!\is_subclass_of($enumType, \BackedEnum::class)) {
throw new \LogicException('Doctrine "enum" type requires a native PHP 8 backed enum class in the "enumType" column mapping property.');
}
return \sprintf(
'ENUM(%s)',
\implode(',', \array_map(fn($e) => \sprintf("'%s'", $e->value), $enumType::cases()))
);
}
public function getName(): string
{
return 'enum';
}
public function requiresSQLCommentHint(AbstractPlatform $platform): bool
{
return true;
}
}
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\Repository\OrderRepository;
#[ORM\Entity(repositoryClass: OrderRepository::class)]
class Order
{
// ...
#[ORM\Column(type: 'enum', enumType: OrderStatus::class)]
private OrderStatus $orderStatus = OrderStatus::PENDING;
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment