{"id":17495433,"url":"https://github.com/elao/phpenums","last_synced_at":"2025-05-14T13:04:12.723Z","repository":{"id":12770955,"uuid":"72760938","full_name":"Elao/PhpEnums","owner":"Elao","description":":nut_and_bolt: Extended PHP 8.1+ enums features \u0026 specific integrations with frameworks and libraries","archived":false,"fork":false,"pushed_at":"2025-01-21T08:51:17.000Z","size":863,"stargazers_count":327,"open_issues_count":18,"forks_count":27,"subscribers_count":19,"default_branch":"2.x","last_synced_at":"2025-04-11T06:00:06.778Z","etag":null,"topics":["enum","enumeration","hacktoberfest","php","symfony"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Elao.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["ogizanagi"]}},"created_at":"2016-11-03T15:45:37.000Z","updated_at":"2025-02-26T14:07:20.000Z","dependencies_parsed_at":"2024-01-24T14:28:39.062Z","dependency_job_id":"7f4cf684-8aab-42b4-a419-a29e9964bd90","html_url":"https://github.com/Elao/PhpEnums","commit_stats":{"total_commits":295,"total_committers":34,"mean_commits":8.676470588235293,"dds":0.5322033898305085,"last_synced_commit":"25382e9a114872148f34f549d028378bc357ffac"},"previous_names":[],"tags_count":55,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Elao%2FPhpEnums","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Elao%2FPhpEnums/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Elao%2FPhpEnums/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Elao%2FPhpEnums/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Elao","download_url":"https://codeload.github.com/Elao/PhpEnums/tar.gz/refs/heads/2.x","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254149944,"owners_count":22022851,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["enum","enumeration","hacktoberfest","php","symfony"],"created_at":"2024-10-19T14:06:06.355Z","updated_at":"2025-05-14T13:04:12.686Z","avatar_url":"https://github.com/Elao.png","language":"PHP","readme":"Elao Enumerations\n=================\n[![Latest Version](https://poser.pugx.org/elao/enum/v?format=flat-square)](https://packagist.org/packages/elao/enum)\n[![Total Downloads](https://poser.pugx.org/elao/enum/downloads?format=flat-square)](https://packagist.org/packages/elao/enum)\n[![Monthly Downloads](https://poser.pugx.org/elao/enum/d/monthly?format=flat-square)](https://packagist.org/packages/elao/enum)\n[![Tests](https://github.com/Elao/PhpEnums/actions/workflows/ci.yml/badge.svg)](https://github.com/Elao/PhpEnums/actions/workflows/ci.yml)\n[![Coveralls](https://img.shields.io/coveralls/Elao/PhpEnums.svg?style=flat-square)](https://coveralls.io/github/Elao/PhpEnums)\n[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/Elao/PhpEnums.svg?style=flat-square)](https://scrutinizer-ci.com/g/Elao/PhpEnums/?branch=2.x)\n[![php](https://img.shields.io/badge/PHP-8.1-green.svg?style=flat-square \"Available for PHP 8.1+\")](http://php.net)\n\n_Provides additional, opinionated features to the [PHP 8.1+ native enums](https://php.watch/versions/8.1/enums) as well\nas specific integrations with frameworks and libraries._\n\n```php\n#[ReadableEnum(prefix: 'suit.')]\nenum Suit: string implements ReadableEnumInterface\n{\n    use ReadableEnumTrait;\n\n    case Hearts = '♥︎';\n    case Diamonds = '♦︎';\n    case Clubs = '♣︎';\n    case Spades = '︎♠︎';\n}\n```\n\n---\n\n\u003cp align=\"center\"\u003e\n    \u003cstrong\u003e📢  This project used to emulate enumerations before PHP 8.1.\u003c/strong\u003e\u003cbr/\u003e\n    For the 1.x documentation, \u003ca href=\"https://github.com/Elao/PhpEnums/tree/1.x\"\u003eclick here\u003c/a\u003e\n    \u003cbr/\u003e\u003cbr/\u003e\n    You can also consult \u003ca href=\"https://github.com/Elao/PhpEnums/issues/124\"\u003ethis issue\u003c/a\u003e to follow objectives \u0026 progress for the V2 of this lib.\n\u003c/p\u003e\n\n---\n\n- Features\n  - [Readable enums](#readable-enums)\n  - [Flag enums](#flag-enums)\n  - [Extra values](#extra-values)\n- [Integrations](#integrations)\n  - [Symfony Forms](#symfony-form)\n  - [Symfony Controller Argument Resolver](#symfony-httpkernel)\n  - Symfony VarDumper\n  - [Symfony Translation](#symfony-translation)\n  - [Doctrine ORM](#doctrine)\n  - [Doctrine ODM](#doctrine-odm)\n  - [Faker](#faker)\n\n## Installation\n\n```bash\ncomposer require \"elao/enum:^2.0\"\n```\n\nOr, in order to help and test latest changes:\n\n```bash\ncomposer require \"elao/enum:^2.x-dev\"\n```\n\n## Readable enums\n\nReadable enums provide a way to expose human-readable labels for your enum cases, by adding a\nnew `ReadableEnumInterface` contract to your enums.\n\nThe easiest way to implement this interface is by using the [`ReadableEnumTrait`](src/ReadableEnumTrait.php) and\nthe [`EnumCase`](src/Attribute/EnumCase.php) attribute:\n\n```php\nnamespace App\\Enum;\n\nuse Elao\\Enum\\ReadableEnumInterface;\nuse Elao\\Enum\\ReadableEnumTrait;\nuse Elao\\Enum\\Attribute\\EnumCase;\n\nenum Suit: string implements ReadableEnumInterface\n{\n    use ReadableEnumTrait;\n\n    #[EnumCase('suit.hearts')]\n    case Hearts = '♥︎';\n\n    #[EnumCase('suit.diamonds')]\n    case Diamonds = '♦︎';\n\n    #[EnumCase('suit.clubs')]\n    case Clubs = '♣︎';\n\n    #[EnumCase('suit.spades')]\n    case Spades = '︎♠︎';\n}\n```\n\nThe following snippet shows how to get the human-readable value of an enum:\n\n```php\nSuit::Hearts-\u003egetReadable(); // returns 'suit.hearts'\n```\n\nIt defines a proper contract to expose an enum case label instead of using the enum case internal name. Which is\nespecially useful if the locale to expose labels to your users differs from the one you're writing your code, as well as\nfor creating integrations with libraries requiring to expose such labels.\n\nIt's also especially useful in conjunction with a translation library\nlike [Symfony's Translation component](https://symfony.com/doc/current/translation.html), by using translation keys.\n\nGiven the following translation file:\n\n```yaml\n# translations/messages.fr.yaml\nsuit.hearts: 'Coeurs'\nsuit.diamonds: 'Carreaux'\nsuit.clubs: 'Piques'\nsuit.spades: 'Trèfles'\n```\n\n```php\n$enum = Suit::Hearts;\n$translator-\u003etrans($enum-\u003egetReadable(), locale: 'fr'); // returns 'Coeurs'\n```\n\n### Configure suffix/prefix \u0026 default value\n\nAs a shorcut, you can also use the [`ReadableEnum`](src/Attribute/ReadableEnum.php) attribute to define the\ncommon `suffix` and `prefix` to use, as well as defaulting on the enum case name or value, if not provided explicitly:\n\n```php\n#[ReadableEnum(prefix: 'suit.')]\nenum Suit: string implements ReadableEnumInterface\n{\n    use ReadableEnumTrait;\n\n    #[EnumCase('hearts︎')]\n    case Hearts = '♥︎';\n    case Diamonds = '♦︎';\n    case Clubs = '♣︎';\n    case Spades = '︎♠︎';\n}\n\nSuit::Hearts-\u003egetReadable(); // returns 'suit.hearts'\nSuit::Clubs-\u003egetReadable(); // returns 'suit.Clubs'\n```\n\nusing the case value (only for string backed enums):\n\n```php\n#[ReadableEnum(prefix: 'suit.', useValueAsDefault: true)]\nenum Suit: string implements ReadableEnumInterface\n{\n    use ReadableEnumTrait;\n\n    case Hearts = 'hearts';\n    case Diamonds = 'diamonds';\n    case Clubs = 'clubs︎';\n    case Spades = '︎spades';\n}\n\nSuit::Hearts-\u003egetReadable(); // returns 'suit.hearts'\nSuit::Clubs-\u003egetReadable(); // returns 'suit.clubs'\n```\n\n## Extra values\n\nThe `EnumCase` attributes also provides you a way to configure some extra attributes on your cases and access these easily with the `ExtrasTrait`:\n\n```php\nnamespace App\\Enum;\n\nuse Elao\\Enum\\ReadableEnumInterface;\nuse Elao\\Enum\\ExtrasTrait;\nuse Elao\\Enum\\Attribute\\EnumCase;\n\nenum Suit implements ReadableEnumInterface\n{\n    use ExtrasTrait;\n\n    #[EnumCase(extras: ['icon' =\u003e 'fa-heart', 'color' =\u003e 'red'])]\n    case Hearts;\n\n    #[EnumCase(extras: ['icon' =\u003e 'fa-diamond', 'color' =\u003e 'red'])]\n    case Diamonds;\n\n    #[EnumCase(extras: ['icon' =\u003e 'fa-club', 'color' =\u003e 'black'])]\n    case Clubs;\n\n    #[EnumCase(extras: ['icon' =\u003e 'fa-spade', 'color' =\u003e 'black'])]\n    case Spades;\n}\n```\n\nAccess these infos using `ExtrasTrait::getExtra(string $key, bool $throwOnMissingExtra = false): mixed`:\n\n```php\nSuit::Hearts-\u003egetExtra('color'); // 'red'\nSuit::Spades-\u003egetExtra('icon'); // 'fa-spade'\nSuit::Spades-\u003egetExtra('missing-key'); // null\nSuit::Spades-\u003egetExtra('missing-key', true); // throws\n```\n\nor create your own interfaces/traits:\n\n```php\ninterface RenderableEnumInterface \n{\n    public function getColor(): string;\n    public function getIcon(): string;\n}\n\nuse Elao\\Enum\\ExtrasTrait;\n\ntrait RenderableEnumTrait\n{\n    use ExtrasTrait;\n\n    public function getColor(): string\n    {\n        $this-\u003egetExtra('color', true);\n    }\n    \n    public function getIcon(): string\n    {\n        $this-\u003egetExtra('icon', true);\n    }\n}\n\nuse Elao\\Enum\\Attribute\\EnumCase;\n\nenum Suit implements RenderableEnumInterface\n{\n    use RenderableEnumTrait;\n\n    #[EnumCase(extras: ['icon' =\u003e 'fa-heart', 'color' =\u003e 'red'])]\n    case Hearts;\n    \n    // […]\n}\n\nSuit::Hearts-\u003egetColor(); // 'red'\n```\n\n## Flag enums\n\nFlagged enumerations are used for bitwise operations.\n\n```php\nnamespace App\\Enum;\n\nenum Permissions: int\n{\n    case Execute = 1 \u003c\u003c 0;\n    case Write = 1 \u003c\u003c 1;\n    case Read = 1 \u003c\u003c 2;\n}\n```\n\nEach enumerated case is a bit flag and can be combined with other cases into a bitmask and manipulated \nusing a [`FlagBag`](src/FlagBag.php) object:\n\n```php\nuse App\\Enum\\Permissions;\nuse Elao\\Enum\\FlagBag;\n\n$permissions = FlagBag::from(Permissions::Execute, Permissions::Write, Permissions::Read);\n// same as:\n$permissions = new FlagBag(Permissions::class, 7); \n// where 7 is the \"encoded\" bits value for:\nPermissions::Execute-\u003evalue | Permissions::Write-\u003evalue | Permissions::Read-\u003evalue // 7\n// or initiate a bag with all its possible values using:\n$permissions = FlagBag::fromAll(Permissions::class);\n\n$permissions = $permissions-\u003ewithoutFlags(Permissions::Execute); // Returns an instance without \"execute\" flag\n\n$permissions-\u003egetValue(); // Returns 6, i.e: the encoded bits value\n$permissions-\u003egetBits(); // Returns [2, 4], i.e: the decoded bits\n$permissions-\u003egetFlags(); // Returns [Permissions::Write, Permissions::Read]\n\n$permissions = $permissions-\u003ewithoutFlags(Permissions::Read, Permissions::Write); // Returns an instance without \"read\" and \"write\" flags\n$permissions-\u003egetBits(); // Returns []\n$permissions-\u003egetFlags(); // Returns []\n\n$permissions = new FlagBag(Permissions::class, FlagBag::NONE); // Returns an empty bag\n\n$permissions = $permissions-\u003ewithFlags(Permissions::Read, Permissions::Execute); // Returns an instance with \"read\" and \"execute\" flags\n\n$permissions-\u003ehasFlags(Permissions::Read); // True\n$permissions-\u003ehasFlags(Permissions::Read, Permissions::Execute); // True\n$permissions-\u003ehasFlags(Permissions::Write); // False\n```\n\nHence, using `FlagBag::getValue()` you can get an encoded value for any combination of flags from your enum, \nand use it for storage or communication between your processes.\n\n## Integrations\n\n### Symfony Form\n\nSymfony already provides an [EnumType](https://symfony.com/doc/current/reference/forms/types/enum.html)\nfor allowing the user to choose one or more options defined in a PHP enumeration.  \nIt extends the ChoiceType field and defines the same options.\n\nHowever, it uses the enum case name as label, which might not be convenient.  \nSince this library specifically supports readable enums, it ships its\nown [EnumType](src/Bridge/Symfony/Form/Type/EnumType.php), extending Symfony's one and using the human representation of\neach case instead of their names.\n\nUse it instead of Symfony's one:\n\n```php\nnamespace App\\Form\\Type;\n\nuse App\\Enum\\Suit;\nuse Symfony\\Component\\Form\\AbstractType;\nuse Elao\\Enum\\Bridge\\Symfony\\Form\\Type\\EnumType;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\SubmitType;\nuse Symfony\\Component\\Form\\FormBuilderInterface;\n\nclass CardType extends AbstractType\n{\n    public function buildForm(FormBuilderInterface $builder, array $options): void\n    {\n        $builder\n            -\u003eadd('suit', EnumType::class, [\n                'class' =\u003e Suit::class, \n                'expanded' =\u003e true,\n            ])\n        ;\n    }\n\n    // ...\n}\n```\n#### FlagBag Form Type\n\nIf you want to use `FlagBag` in Symfony Forms, use the [FlagBagType](src/Bridge/Symfony/Form/Type/FlagBagType.php). This\ntype also extends Symfony [EnumType](https://symfony.com/doc/current/reference/forms/types/enum.html), but it transforms\nform values to and from `FlagBag` instances.\n\n```php\nnamespace App\\Form\\Type;\n\nuse App\\Enum\\Permissions;\nuse Symfony\\Component\\Form\\AbstractType;\nuse Elao\\Enum\\Bridge\\Symfony\\Form\\Type\\FlagBagType;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\SubmitType;\nuse Symfony\\Component\\Form\\FormBuilderInterface;\n\nclass AuthenticationType extends AbstractType\n{\n    public function buildForm(FormBuilderInterface $builder, array $options): void\n    {\n        $builder\n            -\u003eadd('permission', FlagBagType::class, [\n                'class' =\u003e Permissions::class, \n            ])\n        ;\n    }\n\n    // ...\n}\n```\n\n### Symfony HttpKernel\n\n#### Resolve controller arguments from route path\n\nAs of Symfony 6.1+, [backed enum cases will be resolved](https://github.com/symfony/symfony/pull/44831) from route path parameters:\n\n```php\nclass CardController\n{\n    #[Route('/cards/{suit}')]\n    public function list(Suit $suit): Response\n    {\n        // [...]\n    }\n}\n```\n\n➜ A call to `/cards/H` will resolve the `$suit` argument as the `Suit::Hearts` enum case.\n\nIf you're not yet using Symfony HttpKernel 6.1+, this library will still make this working by registering its own\nresolver.\n\n#### Resolve controller arguments from query or body\n\nYou can also resolve from query params or from the request body:\n\n```php\nuse Elao\\Enum\\Bridge\\Symfony\\HttpKernel\\Controller\\ArgumentResolver\\Attributes\\BackedEnumFromQuery;\n\nclass DefaultController\n{\n    #[Route('/cards')]\n    public function list(\n        #[BackedEnumFromQuery]\n        ?Suit $suit = null,\n    ): Response\n    {\n        // [...]\n    }\n}\n```\n\n➜ A call to `/cards?suit=H` will resolve the `$suit` argument as the `Suit::Hearts` enum case.\n\nUse `BackedEnumFromBody` to resolve from the request body (`$_POST`).\n\nIt also supports variadics:\n\n```php\nuse Elao\\Enum\\Bridge\\Symfony\\HttpKernel\\Controller\\ArgumentResolver\\Attributes\\BackedEnumFromQuery;\n\nclass DefaultController\n{\n    #[Route('/cards')]\n    public function list(\n        #[BackedEnumFromQuery]\n        ?Suit ...$suits = null,\n    ): Response\n    {\n        // [...]\n    }\n}\n```\n\n➜ A call to `/cards?suits[]=H\u0026suits[]=S` will resolve the `$suits` argument as `[Suit::Hearts, Suit::Spades]`.\n\n### Symfony Translation\n\nBecause the `ReadableEnumInterface` can be translated within the `TranslatorInterface`, it is easy to use `TranslatableInterface` to enums.\n\nTo translate readable enums is just matter to have a call:\n\n```php\npublic function trans(TranslatorInterface $translator, string $locale = null): string\n{\n    return $translator-\u003etrans($this-\u003egetReadable(), [], $locale);\n}\n```\n\nAn interface and a trait have been added for that purpose.\n\n```php\nuse Elao\\Enum\\Bridge\\Symfony\\Translation\\TranslatableEnumInterface;\nuse Elao\\Enum\\Bridge\\Symfony\\Translation\\TranslatableEnumTrait;\n\nenum Card: string implements TranslatableEnumInterface\n{\n    use TranslatableEnumTrait;\n    \n    #[EnumCase('suit.hearts')]\n    case Hearts = '♥︎';    \n    // ...\n}\n```\n\nWe then use in **PHP**:\n\n```php\n$translated = Card::Hearts-\u003etrans($this-\u003etranslator)\n```\n\nOr in **Twig**:\n\n```twig\n{{ game.card|trans }}\n```\n\n### Doctrine\n\nAs of `doctrine/orm` 2.11, PHP 8.1 enum types [are supported natively](https://twitter.com/ogizanagi/status/1480456881265012736?s=20):\n\n```php\n#[Entity]\nclass Card\n{\n    #[Column(type: 'string', enumType: Suit::class)]\n    public $suit;\n}\n```\n\n\u003e **Note**: Unless you have specific needs for a DBAL type as described below, \n\u003e we recommend using the official ORM integration for backed enums.\n\nPhpEnums however also provides some base classes to save your PHP backed enumerations in your database.\nCustom DBAL classes for use-cases specific to this library,\nsuch as storing a [flag bag](#flag-enums) or a collection of backed enum cases, are or will also be available.\n\n#### In a Symfony app\n\nThis configuration is equivalent to the following sections explaining how to create a custom Doctrine DBAL type:\n\n```yaml\nelao_enum:\n  doctrine:\n    types:\n      App\\Enum\\Suit: ~ # Defaults to `{ class: App\\Enum\\Suit, default: null, type: single }`\n      permissions: { class: App\\Enum\\Permission } # You can set a name different from the enum FQCN\n      permissions_bag: { class: App\\Enum\\Permissions, type: flagbag } # values are stored as an int and retrieved as FlagBag object\n      App\\Enum\\RequestStatus: { default: 200 } # Default value from enum cases, in case the db value is NULL\n```\n\nIt'll actually generate \u0026 register the types classes for you, saving you from writing this boilerplate code.\n\n#### Manually\n\nRead the\n[Doctrine DBAL docs](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/custom-mapping-types.html)\nfirst.\n\nExtend the [AbstractEnumType](src/Bridge/Doctrine/DBAL/Types/AbstractEnumType.php):\n\n```php\nnamespace App\\Doctrine\\DBAL\\Type;\n\nuse Elao\\Enum\\Bridge\\Doctrine\\DBAL\\Types\\AbstractEnumType;\nuse App\\Enum\\Suit;\n\nclass SuitType extends AbstractEnumType\n{\n    protected function getEnumClass(): string\n    {\n        return Suit::class; // By default, the enum FQCN is used as the DBAL type name as well\n    }\n}\n```\n\nIn your application bootstrapping code:\n\n```php\nuse App\\Doctrine\\DBAL\\Type\\SuitType;\nuse Doctrine\\DBAL\\Types\\Type;\n\nType::addType(Suit::class, SuitType::class);\n```\n\nTo convert the underlying database type of your new \"Suit\" type directly into an instance of `Suit` when performing\nschema operations, the type has to be registered with the database platform as well:\n\n```php\n$conn = $em-\u003egetConnection();\n$conn-\u003egetDatabasePlatform()-\u003eregisterDoctrineTypeMapping(Suit::class, SuitType::class);\n```\n\nThen, use it as a column type:\n\n```php\nuse App\\Enum\\Suit;\nuse Doctrine\\ORM\\Mapping as ORM;\n\n#[ORM\\Entity]\nclass Card\n{\n    #[ORM\\Column(Suit::class, nullable: false)]\n    private Suit $field;\n}\n```\n\n### Troubleshooting\n\n#### Using enum instances with a QueryBuilder\n\nWhen using enum instance as parameters in a query made with `Doctrine\\ORM\\QueryBuilder` \nand generated DBAL types from the bundle, parameter type might not be inferred correctly.\n\nEither explicitly use enum value instead of an instance,\nor pass the registered DBAL type as the 3rd parameter in `setParameter()`\nto allow the query builder to cast the object to the database value correctly.\n\nI.E, given:\n\n```php\n#[ORM\\Entity]\nclass Card\n{\n    #[ORM\\Column(Suit::class, nullable: true)\n    protected ?Suit $suit = null;\n}\n```\n\nUse one of the following methods:\n\n```php\nprivate function findByType(?Suit $suit = null): array \n{\n    $qb = $em-\u003ecreateQueryBuilder()\n      -\u003eselect('c')\n      -\u003efrom('Card', 'c')\n      -\u003ewhere('c.suit = :suit');\n      \n    // use a value from constants:\n    $qb-\u003esetParameter('param1', Suit::SPADES-\u003evalue);\n    \n    // or from instances:\n    $qb-\u003esetParameter('suit', $suit-\u003evalue);  \n    // Use the 3rd parameter to set the DBAL type\n    $qb-\u003esetParameter('suit', $suit, Suit::class);\n    \n    // […]\n}   \n```\n\n### Doctrine ODM\n\nYou can store enumeration values as string or integer in your MongoDB database and manipulate them as objects thanks to custom mapping types included in this library.\n\nIn a near future, custom ODM classes for use-cases specific to this library,\nsuch as storing a flag bag or a collection of backed enum cases, would also be provided.\n\n#### In a Symfony app\n\nThis configuration is equivalent to the following sections explaining how to create a custom Doctrine ODM type:\n\n```yaml\nelao_enum:\n  doctrine_mongodb:\n    types:\n      App\\Enum\\Suit: ~ # Defaults to `{ class: App\\Enum\\Suit, type: single }`\n      permissions: { class: App\\Enum\\Permission } # You can set a name different from the enum FQCN\n      another: { class: App\\Enum\\AnotherEnum, type: collection } # values are stored as an array of integers or strings\n      App\\Enum\\RequestStatus: { default: 200 } # Default value from enum cases, in case the db value is NULL\n```\n\nIt'll actually generate \u0026 register the types classes for you, saving you from writing this boilerplate code.\n\n#### Manually\n\nRead the\n[Doctrine ODM docs](https://www.doctrine-project.org/projects/doctrine-mongodb-bundle/en/current/config.html#custom-types)\nfirst.\n\nExtend the [AbstractEnumType](src/Bridge/Doctrine/ODM/Types/AbstractEnumType.php) or [AbstractCollectionEnumType](src/Bridge/Doctrine/ODM/Types/AbstractCollectionEnumType.php):\n\n```php\nnamespace App\\Doctrine\\ODM\\Type;\n\nuse Elao\\Enum\\Bridge\\Doctrine\\ODM\\Types\\AbstractEnumType;\nuse App\\Enum\\Suit;\n\nclass SuitType extends AbstractEnumType\n{\n    protected function getEnumClass(): string\n    {\n        return Suit::class; // By default, the enum FQCN is used as the DBAL type name as well\n    }\n}\n```\n\nIn your application bootstrapping code:\n\n```php\nuse App\\Doctrine\\ODM\\Type\\SuitType;\nuse Doctrine\\ODM\\MongoDB\\Types\\Type;\n\nType::addType(Suit::class, SuitType::class);\n```\n\n#### Mapping\n\nNow the new type can be used when mapping fields:\n\n```php\nuse App\\Enum\\Suit;\nuse Doctrine\\ODM\\MongoDB\\Mapping\\Annotations as MongoDB;\n\n#[MongoDB\\Document]\nclass Card\n{\n    #[MongoDB\\Field(Suit::class)]\n    private Suit $field;\n}\n```\n\n### Faker\n\nThe PhpEnums library provides a faker `EnumProvider` allowing to select random enum cases:\n\n```php\nuse \\Elao\\Enum\\Bridge\\Faker\\Provider\\EnumProvider;\n \n$faker = new Faker\\Generator();\n$faker-\u003eaddProvider(new EnumProvider());\n\n$faker-\u003erandomEnum(Suit::class) // Select one of the Suit cases, e.g: `Suit::Hearts`\n$faker-\u003erandomEnums(Suit::class, 2, min: 1) // Select between 1 and 2 enums cases, e.g: `[Suit::Hearts, Suit::Spades]`\n$faker-\u003erandomEnums(Suit::class, 3, exact: true) // Select exactly 3 enums cases\n```\n\nIts constructor receives a mapping of enum types aliases as first argument:\n\n```php\nnew EnumProvider([\n    'Civility' =\u003e App\\Enum\\Civility::class,\n    'Suit' =\u003e App\\Enum\\Suit::class,\n]);\n```\n\nThis is especially useful when using this provider with Nelmio Alice's DSL (_see next section_)\n\n### Usage with Alice\n\nIf you're using the [nelmio/alice](https://github.com/nelmio/alice) package and its bundle in order to generate fixtures, \nyou can register the Faker provider by using the `nelmio_alice.faker.generator`:\n\n```yml\n# config/services.yaml\nservices:\n    Elao\\Enum\\Bridge\\Faker\\Provider\\EnumProvider:\n        arguments:\n            - Civility: App\\Enum\\Civility\n              Suit: App\\Enum\\Suit\n        tags: ['nelmio_alice.faker.provider']\n```\n\nThe following example shows how to use the provider within a [PHP fixture file](https://github.com/nelmio/alice/blob/master/doc/complete-reference.md#php):\n\n```php\nreturn [\n    MyEntity::class =\u003e [\n        'entity1' =\u003e [\n            'civility' =\u003e Civility::MISTER // Select a specific case, using PHP directly\n            'suit' =\u003e '\u003crandomEnum(App\\Enum\\Suit)\u003e' // Select a random case\n            'suit' =\u003e '\u003crandomEnum(Suit)\u003e' // Select a random case, using the FQCN alias\n            'permissions' =\u003e '\u003crandomEnums(Permissions, 3, false, 1)\u003e' // Select between 1 and 2 enums cases\n            'permissions' =\u003e '\u003crandomEnums(Permissions, 3, true)\u003e' // Select exactly 3 enums cases\n        ]\n    ]\n]\n```\n","funding_links":["https://github.com/sponsors/ogizanagi"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felao%2Fphpenums","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Felao%2Fphpenums","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Felao%2Fphpenums/lists"}