Skip to content

Instantly share code, notes, and snippets.

@ismail1432
Last active December 28, 2021 22:39
Show Gist options
  • Select an option

  • Save ismail1432/f2c21b505541a12138bdf5298c62a5cf to your computer and use it in GitHub Desktop.

Select an option

Save ismail1432/f2c21b505541a12138bdf5298c62a5cf to your computer and use it in GitHub Desktop.
<?php
namespace App\DoctrineType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;
abstract class AbstractEnumType extends Type
{
abstract public static function getEnumsClass(): string;
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return 'TEXT';
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if ($value instanceof \BackedEnum) {
return $value->value;
}
return null;
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if (false === enum_exists($this->getEnumsClass(), true)) {
throw new \LogicException("This class should be an enum");
}
// 🔥 https://www.php.net/manual/en/backedenum.tryfrom.php
return $this::getEnumsClass()::tryFrom($value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment