Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Doctrine/AbstractEnumType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand All @@ -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();
}
}
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<?php

namespace App\Enum;

use MyCLabs\Enum\Enum;

class Status extends Enum {
public const SUCCESS = 1;
public const ERROR = 2;

public static function castValueIn($value) {
return (int) $value;
}
}
```

[myclabs-enum-homepage]: https://github.com/myclabs/php-enum
[jms-serializer-homepage]: http://jmsyst.com/libs/serializer
[symfony-forms-homepage]: http://symfony.com/doc/current/book/forms.html
Expand Down