{"id":15296171,"url":"https://github.com/ekvedaras/php-enum","last_synced_at":"2025-04-13T19:41:21.308Z","repository":{"id":56976154,"uuid":"291245203","full_name":"ekvedaras/php-enum","owner":"ekvedaras","description":"🔠  PHP enum implementation","archived":false,"fork":false,"pushed_at":"2020-12-30T14:28:03.000Z","size":72,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-27T10:21:18.454Z","etag":null,"topics":["enum","enum-implementations","php","php-enum"],"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/ekvedaras.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG-1.x.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-08-29T09:58:05.000Z","updated_at":"2022-09-20T05:47:12.000Z","dependencies_parsed_at":"2022-08-21T10:20:55.011Z","dependency_job_id":null,"html_url":"https://github.com/ekvedaras/php-enum","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ekvedaras%2Fphp-enum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ekvedaras%2Fphp-enum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ekvedaras%2Fphp-enum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ekvedaras%2Fphp-enum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ekvedaras","download_url":"https://codeload.github.com/ekvedaras/php-enum/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248770455,"owners_count":21158982,"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","enum-implementations","php","php-enum"],"created_at":"2024-09-30T18:09:38.502Z","updated_at":"2025-04-13T19:41:21.283Z","avatar_url":"https://github.com/ekvedaras.png","language":"PHP","readme":"# PHP Enum\n\n![Tests](https://github.com/ekvedaras/php-enum/workflows/run-tests/badge.svg)\n[![Code Coverage](https://img.shields.io/codecov/c/gh/ekvedaras/php-enum/main?style=flat)](https://app.codecov.io/gh/ekvedaras/php-enum)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE)\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/ekvedaras/php-enum.svg?style=flat)](https://packagist.org/packages/ekvedaras/php-enum)\n[![Total Downloads](https://img.shields.io/packagist/dt/ekvedaras/php-enum.svg?style=flat)](https://packagist.org/packages/ekvedaras/php-enum)\n\n\u003cimg src=\"logo.svg\" width=\"192\" height=\"192\"/\u003e\n\n![Twitter Follow](https://img.shields.io/twitter/follow/ekvedaras?style=plastic)\n\nBig thanks [happy-types/enumerable-type](https://packagist.org/packages/happy-types/enumerable-type) for the original idea. Take a look if it suits your needs better.\n\nThis package adds `meta` field, provides a few more methods like `options`, `keys`, `json`, etc. \nand there are simple php array, `illuminate/collection`, `arrayy` and `doctrine` collection implementations to choose from. \n\n## Benefits\n\n* Enums in general allow to avoid [magic values](https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants)\n* By type hinting forces only allowed values to be passed to methods (or returned)\n* Easy way to list all possible values\n* More feature rich and flexible then other enum implementations\n* Works with strict (`===`) operator\n* IDE friendly, so auto complete, usage analysis and refactorings all work\n\n## Defining enums\n\nCreate enums by extending one of:\n\n * `EKvedaras\\PHPEnum\\PHPArray\\Enum`\n * `EKvedaras\\PHPEnum\\Illuminate\\Collection\\Enum`\n * `EKvedaras\\PHPEnum\\Arrayy\\Enum`\n * `EKvedaras\\PHPEnum\\Doctrine\\Enum`\n\n```php\nuse EKvedaras\\PHPEnum\\PHPArray\\Enum;\n\nclass PaymentStatus extends Enum \n{\n    /**\n     * @return static\n     */\n    final public static function pending(): self\n    {\n        return static::get('pending', 'Payment is pending');\n    }\n\n    /**\n     * @return static\n     */\n    final public static function completed(): self\n    {\n        return static::get('completed', 'Payment has been processed');\n    }\n    \n    /**\n     * @return static\n     */\n    final public static function failed(): self\n    {\n        return static::get('failed', 'Payment has failed');\n    }\n}\n```\n\nIntegers can be used as IDs instead of string values if you prefer.\n\n## Usage\n\n### Retrieving and comparing enum values\n\n```php\n// Retrieving value statically\n$status1 = PaymentStatus::completed();\n\n// Retrieving value dynamically from ID\n$status2 = PaymentStatus::from('completed');\n\n// Strict comparison is supported\nvar_dump($status1 === $status2); // true\n```\n\n### Accessing value properties\n\n```php\n$status = PaymentStatus::copmleted();\n\n$status-\u003eid();   // 'completed'\n$status-\u003ename(); // 'Payment has been processed'\n$status-\u003emeta(); // null\n```\n\n### Listing enum values\n\nThere are two implementations provided:\n\n#### PHP array\n\nTo use PHP array your enums should extend `EKvedaras\\PHPEnum\\PHPArray\\Enum` class\n\n```php\nvar_dump(PaymentStatus::enum());\n/*\narray(3) {\n  'pending' =\u003e\n  class PaymentStatus#12 (3) {\n    protected $id =\u003e\n    string(7) \"pending\"\n    protected $name =\u003e\n    string(18) \"Payment is pending\"\n    protected $meta =\u003e\n    NULL\n  }\n  'completed' =\u003e\n  class PaymentStatus#363 (3) {\n    protected $id =\u003e\n    string(9) \"completed\"\n    protected $name =\u003e\n    string(26) \"Payment has been processed\"\n    protected $meta =\u003e\n    NULL\n  }\n  'failed' =\u003e\n  class PaymentStatus#13 (3) {\n    protected $id =\u003e\n    string(6) \"failed\"\n    protected $name =\u003e\n    string(18) \"Payment has failed\"\n    protected $meta =\u003e\n    NULL\n  }\n}\n */\n```\n\n```php\nvar_dump(PaymentStatus::options());\n/*\narray(3) {\n  'pending' =\u003e\n  string(18) \"Payment is pending\"\n  'completed' =\u003e\n  string(26) \"Payment has been processed\"\n  'failed' =\u003e\n  string(18) \"Payment has failed\"\n}\n*/\n```\n\n```php\nvar_dump(PaymentStatus::keys());\n/*\narray(3) {\n  [0] =\u003e\n  string(7) \"pending\"\n  [1] =\u003e\n  string(9) \"completed\"\n  [2] =\u003e\n  string(6) \"failed\"\n}\n*/\n```\n\n```php\nvar_dump(PaymentStatus::json()); // Will include meta if defined\n```\n```json\n{\n    \"pending\": {\n        \"id\": \"pending\",\n        \"name\": \"Payment is pending\"\n    },\n    \"completed\": {\n        \"id\": \"completed\",\n        \"name\": \"Payment has been processed\"\n    },\n    \"failed\": {\n        \"id\": \"failed\",\n        \"name\": \"Payment has failed\"\n    }\n}\n```\n\n```php\nvar_dump(PaymentStatus::jsonOptions());\n```\n```json\n{\n    \"pending\": \"Payment is pending\",\n    \"completed\": \"Payment has been processed\",\n    \"failed\": \"Payment has failed\"\n}\n```\n\n#### Illuminate Collection\n\n**Either `illuminate/support` or `illuminate/collections` package is required which is not installed by default.**\n\nTo use Illuminate Collection your enums should extend `EKvedaras\\PHPEnum\\Illuminate\\Collection\\Enum` class.\n\nThe only difference is `enum`, `options` and `keys` methods will return `Collection` instances instead of arrays.\nThe rest works exactly the same.\n\n```php\nvar_dump(PaymentStatus::enum());\n/*\nclass Illuminate\\Support\\Collection#362 (1) {\n  protected $items =\u003e\n  array(3) {\n    'pending' =\u003e\n    class PaymentStatus#12 (3) {\n      protected $id =\u003e\n      string(7) \"pending\"\n      protected $name =\u003e\n      string(18) \"Payment is pending\"\n      protected $meta =\u003e\n      NULL\n    }\n    'completed' =\u003e\n    class PaymentStatus#363 (3) {\n      protected $id =\u003e\n      string(9) \"completed\"\n      protected $name =\u003e\n      string(26) \"Payment has been processed\"\n      protected $meta =\u003e\n      NULL\n    }\n    'failed' =\u003e\n    class PaymentStatus#13 (3) {\n      protected $id =\u003e\n      string(6) \"failed\"\n      protected $name =\u003e\n      string(18) \"Payment has failed\"\n      protected $meta =\u003e\n      NULL\n    }\n  }\n}\n */\n```\n\n```php\nvar_dump(PaymentStatus::options());\n/*\nclass Illuminate\\Support\\Collection#368 (1) {\n  protected $items =\u003e\n  array(3) {\n    'pending' =\u003e\n    string(18) \"Payment is pending\"\n    'completed' =\u003e\n    string(26) \"Payment has been processed\"\n    'failed' =\u003e\n    string(18) \"Payment has failed\"\n  }\n}\n*/\n```\n\n```php\nvar_dump(PaymentStatus::keys());\n/*\nclass Illuminate\\Support\\Collection#13 (1) {\n  protected $items =\u003e\n  array(3) {\n    [0] =\u003e\n    string(7) \"pending\"\n    [1] =\u003e\n    string(9) \"completed\"\n    [2] =\u003e\n    string(6) \"failed\"\n  }\n}\n*/\n```\n\n### Meta\n\nMeta field is intentionally left as mixed type as it could be used for various reasons.\nFor example linking enum options with a specific implementation:\n\n```php\nuse EKvedaras\\PHPEnum\\PHPArray\\Enum;\n\nclass PaymentMethod extends Enum\n{\n    final public static function payPal(): self\n    {\n        return static::get('paypal', 'PayPal', PayPalHandler::class);\n    }\n    \n    final public static function stripe(): self\n    {\n        return static::get('stripe', 'Stripe', StripeHandler::class);\n    }\n}\n```\n\nResolving payment handler in Laravel:\n\n```php\n$method = PaymentMethod::from($request['method_id']);\n\n$handler = app($method-\u003emeta());\n```\n\nMeta could also be used as a more in detail description of each option that could be displayed to users\nor some other object linking other classes, resources together.\n\nFurthermore, in some cases it is useful to resolve enum option from meta. That is also possible:\n\n```php\n$method = PaymentMethod::fromMeta(StripeHandler::class);\n```\n\n## Things to know\n\n### `final public static function`\n\nOnly methods marked as `final public static` will be considered as possible values of enum. Other methods are still there, but\nthey will not be returned in `enum` / `keys` / `options`, etc. results and won't be considered as valid values. However, this allows\nto extend enums and make them more useful. For example:\n\n```php\nuse EKvedaras\\PHPEnum\\Illuminate\\Collection\\Enum;\nuse Illuminate\\Support\\Collection;\n\nclass PaymentMethods extends Enum\n{\n    /**\n     * @return static\n     */\n    final public static function payPal(): self\n    {\n        return static::get('paypal', 'PayPal');\n    }\n    \n    /**\n     * @return static\n     */\n    final public static function stripe(): self\n    {\n        return static::get('stripe', 'Stripe');\n    }\n    \n    /**\n     * @return static\n     */\n    final public static function mollie(): self\n    {\n        return static::get('mollie', 'Mollie');\n    }\n    \n    /**\n     * Returns only enabled payment methods. Useful for validation or rendering payments UI\n     * @return Collection|static[]\n     */\n    public static function enabled(): Collection\n    {\n        return static::enum()-\u003eonly(config('payments.enabled'));\n    }\n}\n```\n\n### `from($id)` only allows valid IDs\n\nWell, this is expected. Calling `PaymentMethod::from('ideal')` will throw `OutOfBoundsException`. \n\n### No serialization\n\nEnum object instances cannot be serialized. Deserialized objects would get a different address in memory therefore, `===` would no longer work.\nCalling `serialize(PaymentMethod::stripe())` will throw a `RuntimeException`.\n\nAs a workaround it is better to store the ID instead of object itself. You still get the bonus of setters only accepting valid values.\n\n```php\nclass Payment \n{\n    /** @var string */\n    private $method;\n\n    public function setMethod(PaymentMethod $method)\n    {\n        $this-\u003emethod = $method-\u003eid();\n    }\n    \n    public function getMethod(): PaymentMethod\n    {\n        return PaymentMethod::from($this-\u003emethod);\n    }\n}\n```\n\n### Don't mix implementations\n\nEnum instances cache is stored in a static variable. Choose one implementation for your project\nand stick to it, otherwise you may unexpectedly get errors because types don't match.\n\nYou may create your own project enum class and extend your chosen implementation, so if it ever needs to be\nchanged it can be done in one place only (if storage APIs match).\n\n## Related packages\n\n* [ekvedaras/laravel-enum](https://packagist.org/packages/ekvedaras/laravel-enum)\n* [ekvedaras/doctrine-enum](https://packagist.org/packages/ekvedaras/doctrine-enum)\n\n## Changelog\n\nSee changes in changelog files:\n\n* [v1 changelog](CHANGELOG-1.x.md)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fekvedaras%2Fphp-enum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fekvedaras%2Fphp-enum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fekvedaras%2Fphp-enum/lists"}