Consistence Enum types for Doctrine.

v1.0.0 2020-03-30 15:56 UTC


Build Status Coverage Status Downloads this Month Latest stable


Via Composer:

$ composer require nepada/consistence-doctrine


Define Doctrine type for the enum

 * @phpstan-extends \Nepada\ConsistenceDoctrine\StringEnumType<\FooEnum>
class FooEnumType extends \Nepada\ConsistenceDoctrine\StringEnumType

    protected function getEnumClassName(): string
        return \FooEnum::class;


You can choose to inherit from StringEnumType, IntegerEnumType, FloatEnumType or BooleanEnumType depending on the enum values.

Register the created type in Doctrine

\Doctrine\DBAL\Types\Type::addType(\FooEnum::class, \FooEnumType::class);

In Nette with nettrine/dbal integration, you can register the types in your configuration:

            FooEnum: FooEnumType

Use the type in entity

use Doctrine\ORM\Mapping as ORM;

 * @ORM\Entity
class SomeEntity

    /** @ORM\Column(type=\FooEnum::class, nullable=false) */
    private \FooEnum $foo;

    // ...


Use enum in query builder

$result = $repository->createQueryBuilder('bar')
    ->select('') // FooEnum instances are created during hydratation
    ->where(' = :fooEnum')
    ->setParameter('fooEnum', \FooEnum::get(\FooEnum::VALUE), \FooEnum::class) // enum instance gets serialized

PHPStan support (via phpstan/phpstan-doctrine)

The abstract enum type classes are anotated as PHPStan generics and define proper typehints for their convert* methods. This means you can teach PHPStan your custom enum types via ReflectionDescriptor:

        factory: PHPStan\Type\Doctrine\Descriptors\ReflectionDescriptor(FooEnumType)
        tags: [phpstan.doctrine.typeDescriptor]

Differences from the official consistence/consistence-doctrine

The official integration consistence/consistence-doctrine uses postload entity event to convert data stored in database to enum instances.

The main advantage of that approach is that you don't need to create and register new doctrine type for every enum.

The disadvantages are:

  • You can't use native property typehints for entity enum attributes.
  • When you're not hydrating entites, you will get enum values instead of enum instances.
  • There is no easy way how to make PHPStan understand and check doctrine and PHP types of your enum fields.