{"id":16626727,"url":"https://github.com/greg0ire/enum","last_synced_at":"2026-03-09T06:31:27.825Z","repository":{"id":55970179,"uuid":"20924644","full_name":"greg0ire/enum","owner":"greg0ire","description":"A workaround for the missing php enum type","archived":false,"fork":false,"pushed_at":"2023-05-25T09:56:21.000Z","size":267,"stargazers_count":45,"open_issues_count":2,"forks_count":4,"subscribers_count":2,"default_branch":"stable","last_synced_at":"2025-12-06T15:59:18.274Z","etag":null,"topics":["enum","php","symfony","symfony-validator","twig"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/greg0ire.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"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}},"created_at":"2014-06-17T13:36:32.000Z","updated_at":"2024-11-04T22:46:49.000Z","dependencies_parsed_at":"2024-06-18T15:39:14.181Z","dependency_job_id":null,"html_url":"https://github.com/greg0ire/enum","commit_stats":{"total_commits":154,"total_committers":9,"mean_commits":17.11111111111111,"dds":0.5,"last_synced_commit":"9bb430d7d29a8fbeb29cbb11a8be0e0ee4940009"},"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"purl":"pkg:github/greg0ire/enum","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/greg0ire%2Fenum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/greg0ire%2Fenum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/greg0ire%2Fenum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/greg0ire%2Fenum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/greg0ire","download_url":"https://codeload.github.com/greg0ire/enum/tar.gz/refs/heads/stable","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/greg0ire%2Fenum/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30284774,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-09T02:57:19.223Z","status":"ssl_error","status_checked_at":"2026-03-09T02:56:26.373Z","response_time":61,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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","php","symfony","symfony-validator","twig"],"created_at":"2024-10-12T04:11:37.349Z","updated_at":"2026-03-09T06:31:27.799Z","avatar_url":"https://github.com/greg0ire.png","language":"PHP","readme":"# Enums\n\nThis package holds a simple class that may be used as an ancestor for your\nenum classes.\n\n[![Build Status][3]](https://travis-ci.org/greg0ire/enum)\n\n## Installation\n\n    composer require greg0ire/enum\n\n## Usage\n\n### Basic usage\n\nExtend the `Greg0ire\\Enum\\AbstractEnum`, define your enum key values as constants,\nand Bob's your uncle. You can make the class abstract or final, as you see fit.\n\n```php\nuse Greg0ire\\Enum\\AbstractEnum;\n\nfinal class DaysOfWeek extends AbstractEnum {\n    const Sunday = 0;\n    const Monday = 1;\n    const Tuesday = 2;\n    const Wednesday = 3;\n    const Thursday = 4;\n    const Friday = 5;\n    const Saturday = 6;\n}\n```\n\nThen, you may use the DaysOfWeek class for input validation:\n\n```php\nDaysOfWeek::isValidName('Humpday');                  // false\nDaysOfWeek::isValidName('Monday');                   // true\nDaysOfWeek::isValidName('monday');                   // false\nDaysOfWeek::isValidName(0);                          // false\n\nDaysOfWeek::isValidValue(0);                         // true\nDaysOfWeek::isValidValue(5);                         // true\nDaysOfWeek::isValidValue(7);                         // false\nDaysOfWeek::isValidValue('Friday');                  // false\n```\n\nBoth methods have an `assert*` counterpart that will throw a\n`Greg0ire\\Enum\\Exception\\InvalidEnumValue` exception:\n\n```\nDaysOfWeek::assertValidName(0);                      // InvalidEnumName\nDaysOfWeek::assertValidValue('Friday');              // InvalidEnumValue\n```\n\nAdditionally, you may get all the constants in your class as a hash:\n\n```php\nDaysOfWeek::getConstants();\nDaysOfWeek::getConstants('strtolower'); // Will combine your values with `DaysOfWeek::getKeys($callback)`.\nDaysOfWeek::getConstants('strtolower', true); // Values combine with `DaysOfWeek::getClassPrefixedKeys($callback)`.\nDaysOfWeek::getConstants('strtolower', true, '.'); // Same with `DaysOfWeek::getClassPrefixedKeys($callback, $separator)`.\n```\n\nYou may also get all the keys in your class as an array:\n\n```php\nDaysOfWeek::getKeys();\nDaysOfWeek::getKeys('strtolower'); // Will call `array_map` with the given callback.\n```\n\nOr the key with the enum class prefix:\n\n```php\nDaysOfWeek::getClassPrefixedKeys();\nDaysOfWeek::getClassPrefixedKeys('strtolower'); // Will call `array_map` with the given callback.\nDaysOfWeek::getClassPrefixedKeys('strtolower', '.'); // Replace the namespace separator ('_' by default).\n```\n\nIf you would like to get the keys from a value:\n\n```php\n$key = DaysOfWeek::getKeysFromValue(1); // Monday will be assigned to $key\n```\n\nIf you have many keys with the same value you will get an array, and a value otherwise.\n\n### Advanced usage\n\nIf you need to get the constants from a class you cannot modify, or from an\ninterface, or even from several classes / interfaces, you may override\n`AbstractEnum::getEnumTypes()`.\n\nFor example, if you have the following class and interface :\n\n\n```php\nnamespace Vendor\\Namespace;\n\nclass ClassFromAVendor\n{\n   const SOMETHING      = 'something';\n   const SOMETHING_ELSE = 'something_else';\n}\n```\n\n```php\nnamespace My\\Namespace;\n\ninterface SomeInterface\n{\n   const ANOTHER_CONST = 'another_const';\n}\n```\n\nYou can get all three constants by creating this Enum :\n\n```php\nuse Greg0ire\\Enum\\AbstractEnum;\nuse My\\Namespace\\SomeInterface;\nuse Vendor\\Namespace\\ClassFromAVendor;\n\nfinal class MyEnum extends AbstractEnum\n{\n    protected static function getEnumTypes()\n    {\n        return [ClassFromAVendor::class, SomeInterface::class];\n    }\n}\n```\n\nAlternatively, you can specify a prefix for each type to avoid getting FQCNs in\nthe hash keys.\n\n```php\nuse Greg0ire\\Enum\\AbstractEnum;\nuse My\\Namespace\\SomeInterface;\nuse Vendor\\Namespace\\ClassFromAVendor;\n\nfinal class MyEnum extends AbstractEnum\n{\n    protected static function getEnumTypes()\n    {\n        return [\n            'prefix1' =\u003e ClassFromAVendor::class,\n            'prefix2' =\u003e SomeInterface::class,\n        ];\n    }\n}\n```\n\n### Get label from a service\n\nIf you want to get the constant label behind an enum value, you can instantiate \nthe `GetLabel` class and invoke it.\n\n```php\nuse Greg0ire\\Enum\\Bridge\\Symfony\\Translator\\GetLabel;\n\n$label = new GetLabel();\n$label(Your\\Enum\\Class::VALUE, Your\\Enum\\Class::class);\n```\n\nTo enable translation, require the `symfony/translation` component\nand pass a `Symfony\\Contracts\\Translation\\TranslationInterface` instance on the \n`GetLabel` constructor\n\n```php\nuse Greg0ire\\Enum\\Bridge\\Symfony\\Translator\\GetLabel;\nuse Symfony\\Contracts\\Translation\\TranslationInterface;\n\n$label = new GetLabel($translator);\n$label(Your\\Enum\\Class::VALUE, Your\\Enum\\Class::class);\n```\n\nIf you're using Symfony, alias the service and simply inject it.\nIf translations are enabled, the `TranslatorInterface` will be automatically injected.\n\n```yaml\nservices:\n    # ...\n    Greg0ire\\Enum\\Bridge\\Symfony\\Translator\\GetLabel: \"@greg0ire_enum.symfony.translator.get_label\"\n```\n\n```php\npublic function index(GetLabel $label)\n{\n    $label(Your\\Enum\\Class::VALUE, Your\\Enum\\Class::class);\n    $label(Your\\Enum\\Class::VALUE, Your\\Enum\\Class::class, 'another_domain'); // Change the translation domain\n    $label(Your\\Enum\\Class::VALUE, Your\\Enum\\Class::class, false); // Disable translation. In this case the class prefix wont be added\n    $label(Your\\Enum\\Class::VALUE, Your\\Enum\\Class::class, false, true); // Disable translation but keep class prefix\n    $label(Your\\Enum\\Class::VALUE, Your\\Enum\\Class::class, false, true, '.'); // Disable translation but keep class prefix with a custom separator\n}\n```\n\n### Integration with other libraries\n\n`greg0ire/enum` integrates with other libraries. The list is available in the\n`suggest` section of the Composer dependency manifest.\n\n#### Symfony validator\n\nThis package provides a \"ready to use\" symfony validator.\nYou have to require the `symfony/validator` package to get it working.\n\n```php\nuse Greg0ire\\Enum\\Bridge\\Symfony\\Validator\\Constraint\\Enum;\nuse Symfony\\Component\\Validator\\Validation;\nuse Your\\Namespace\\EnumClass;\n\n$validator = Validation::createValidator();\n\n$violations = $validator-\u003evalidateValue(42, new Enum(EnumClass::class));\n// You can also show the constants keys on the error message:\n$violations = $validator-\u003evalidateValue(42, new Enum(['class' =\u003e EnumClass::class, 'showKeys' =\u003e true]));\n// Enum constraint inherits from Choice constraint. You can use inherited options too:\n$violations = $validator-\u003evalidateValue(42, new Enum(['class' =\u003e EnumClass::class, 'strict' =\u003e true]));\n```\n\nAnother example with annotations:\n\n```php\nuse Doctrine\\Common\\Annotations\\AnnotationRegistry;\nuse Greg0ire\\Enum\\Bridge\\Symfony\\Validator\\Constraint\\Enum as EnumAssert;\nuse Symfony\\Component\\Validator\\Validation;\n\nclass MyClass\n{\n    /**\n     * @EnumAssert(\"Your\\Namespace\\EnumClass\")\n     */\n    private $dummy;\n\n    public function __construct($dummy)\n    {\n        $this-\u003edummy = $dummy\n    }\n}\n\nAnnotationRegistry::registerLoader('class_exists');\n$validator = Validation::createValidatorBuilder()\n    -\u003eenableAnnotationMapping()\n    -\u003egetValidator();\n\n$object = new MyClass(42);\n\n$violations = $validator-\u003evalidate($object);\n```\n\nNote: You will have to get `doctrine/annotations` and `doctrine/cache` packages to get it working.\n\n#### Symfony form\n\nThis package provides a \"ready to use\" symfony form type.\nYou have to require the `symfony/form` package to get it working.\n\n```php\nuse Greg0ire\\Enum\\Bridge\\Symfony\\Form\\Type\\EnumType;\nuse Symfony\\Component\\Form\\Forms;\nuse Your\\Namespace\\EnumClass;\n\n$formFactory = Forms::createFormFactory();\n\n$view = $this-\u003efactory-\u003ecreate(EnumType::class, null, array(\n    'class' =\u003e EnumClass::class,\n))-\u003ecreateView();\n```\n\n#### Twig extension\n\nThis package comes with an `EnumExtension` Twig class. It contains a filter and some functions.\nYou have to require the `twig/twig` package to get it working.\n\n##### Filter\n\nThe `enum_label` filter will try to return the constant label corresponding to the given value.\n\nThis filter relies on the `Greg0ire\\Enum\\Bridge\\Symfony\\Translator\\GetLabel` service.\n\nIt will try to translate it if possible. To enable translation, require the `symfony/translation` component\nand pass a `Symfony\\Contracts\\Translation\\TranslationInterface` instance on the `GetLabel` constructor. \n`GetLabel` instance will be injected on the `EnumExtension` constructor.\n\nIf translation is not available, you will have the default label with class prefixing.\n\nUsage:\n\n```twig\n{{ value|enum_label('Your\\\\Enum\\\\Class') }}\n{{ value|enum_label('Your\\\\Enum\\\\Class', 'another_domain') }} {# Change the translation domain #}\n{{ value|enum_label('Your\\\\Enum\\\\Class', false) }} {# Disable translation. In this case the class prefix wont be added #}\n{{ value|enum_label('Your\\\\Enum\\\\Class', false, true) }} {# Disable translation but keep class prefix #}\n{{ value|enum_label('Your\\\\Enum\\\\Class', false, true, '.') }} {# Disable translation but keep class prefix with a custom separator #}\n```\n\n##### Functions\n\nThe 3 available twig functions are ports of some `AbstractEnum` methods that can be useful in a twig template:\n\n* `enum_get_constants` =\u003e `AbstractEnum::getConstants`\n* `enum_get_keys` =\u003e `AbstractEnum::getKeys`\n* `enum_get_class_prefixed_keys` =\u003e `AbstractEnum::getClassPrefixedKeys`\n\nThe arguments are exactly the same except you have to specify the targeted class first (as `enum_label` filter).\n\nHere is a concrete example with `enum_get_constants` function:\n\n```twig\n{% for enum_key, enum_value in enum_get_constants('Your\\\\Enum\\\\Class') %}\n    {{ enum_key }} -\u003e {{ enum_value }}\n{% endfor %}\n```\n\n##### Twig extension as a service\n\nOn Symfony projects, the extension can be autoloaded.\nFirst, you have to require the `symfony/framework-bundle` and `symfony/twig-bundle` packages, or use Symfony fullstack.\n\nThen, register the bundle in the kernel of your application:\n\n``` php\n// app/AppKernel.php\n\npublic function registerBundles()\n{\n    $bundles = [\n        // ...\n        new Greg0ire\\Enum\\Bridge\\Symfony\\Bundle\\Greg0ireEnumBundle(),\n    ];\n\n    // ...\n\n    return $bundles\n}\n```\n\nThat's all. You can now directly use the filter.\n\n## Contributing\n\nsee [CONTRIBUTING.md][1]\n\n## Credits\n\nThis is a shameless rip-off of [this Stack Overflow answer][0], with one\nmodification: the `getConstants` method has been made public so that it is\navailable for building choice widgets, for instance. If you want to give credit\nto someone for this, give it to [Brian Cline][2]\n\n[0]: http://stackoverflow.com/a/254543/353612\n[1]: ./CONTRIBUTING.md\n[2]: http://stackoverflow.com/users/32536/brian-cline\n[3]: https://travis-ci.org/greg0ire/enum.svg?branch=master\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgreg0ire%2Fenum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgreg0ire%2Fenum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgreg0ire%2Fenum/lists"}