Last active
December 28, 2021 22:39
-
-
Save ismail1432/f2c21b505541a12138bdf5298c62a5cf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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