|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Application\Extensions\Doctrine; |
| 6 | + |
| 7 | +use BackedEnum; |
| 8 | +use Doctrine\DBAL\Platforms\AbstractPlatform; |
| 9 | +use Doctrine\DBAL\Types\Type; |
| 10 | + |
| 11 | +use function call_user_func; |
| 12 | + |
| 13 | +/** |
| 14 | + * Custom mapping type for Doctrine DBAL to directly support enums in a database without having to use a native type. |
| 15 | + * |
| 16 | + * It is necessary to use this custom mapping type due to an apparent bug in the value conversion layer in DBAL when |
| 17 | + * using trying to construct our (Sub)Decisions in specific scenarios (e.g. seeding the database). |
| 18 | + * |
| 19 | + * Due to the `final` marking of the constructor we cannot initialise {@link BackedEnumType::$enumClass} and |
| 20 | + * {@link BackedEnumType::$name}. As such, we need to override these when creating specific mapping types. |
| 21 | + * |
| 22 | + * @template T of BackedEnum |
| 23 | + */ |
| 24 | +abstract class BackedEnumType extends Type |
| 25 | +{ |
| 26 | + /** |
| 27 | + * @var class-string<T> $enumClass |
| 28 | + * @required |
| 29 | + */ |
| 30 | + public string $enumClass; |
| 31 | + |
| 32 | + /** |
| 33 | + * @required |
| 34 | + */ |
| 35 | + public const string NAME = ''; |
| 36 | + |
| 37 | + /** |
| 38 | + * {@inheritDoc} |
| 39 | + * |
| 40 | + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingTraversableTypeHintSpecification |
| 41 | + */ |
| 42 | + public function getSQLDeclaration( |
| 43 | + array $column, |
| 44 | + AbstractPlatform $platform, |
| 45 | + ): string { |
| 46 | + return $platform->getStringTypeDeclarationSQL($column); |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * @return T|null |
| 51 | + */ |
| 52 | + public function convertToPHPValue( |
| 53 | + mixed $value, |
| 54 | + AbstractPlatform $platform, |
| 55 | + ) { |
| 56 | + if (empty($value)) { |
| 57 | + return null; |
| 58 | + } |
| 59 | + |
| 60 | + return call_user_func([$this->enumClass, 'from'], $value); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingAnyTypeHint |
| 65 | + */ |
| 66 | + public function convertToDatabaseValue( |
| 67 | + mixed $value, |
| 68 | + AbstractPlatform $platform, |
| 69 | + ) { |
| 70 | + return $value instanceof $this->enumClass ? $value->value : $value; |
| 71 | + } |
| 72 | +} |
0 commit comments