diff --git a/Doctrine/AbstractEnumType.php b/Doctrine/AbstractEnumType.php index 97900f2..c68b936 100644 --- a/Doctrine/AbstractEnumType.php +++ b/Doctrine/AbstractEnumType.php @@ -22,6 +22,13 @@ public function convertToPHPValue($value, AbstractPlatform $platform) $enumClass = $this->getEnumClass(); + // If the enumeration provides a casting method, apply it + if (method_exists($enumClass, 'castValueIn')) { + /** @var callable $castValueIn */ + $castValueIn = [$enumClass, 'castValueIn']; + $value = $castValueIn($value); + } + return new $enumClass($value); } @@ -31,6 +38,15 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) return null; } + $enumClass = $this->getEnumClass(); + + // If the enumeration provides a casting method, apply it + if (method_exists($enumClass, 'castValueOut')) { + /** @var callable $castValueOut */ + $castValueOut = [$enumClass, 'castValueOut']; + return $castValueOut($value->getValue()); + } + return $value->getValue(); } } diff --git a/README.md b/README.md index 44c319f..e3fd140 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,27 @@ The form type looks by default for the translation of the enum values in the `en // ... } +### Customize value casting + +In case the values of your enumeration are not strings, you can use the two magic function `castValueIn` and `castValueOut` to support non-string values: + +```php +