{"id":13594080,"url":"https://github.com/spatie/enum","last_synced_at":"2025-05-13T19:14:13.311Z","repository":{"id":40725200,"uuid":"169538841","full_name":"spatie/enum","owner":"spatie","description":"Strongly typed enums in PHP supporting autocompletion and refactoring","archived":false,"fork":false,"pushed_at":"2025-05-12T07:50:30.000Z","size":1351,"stargazers_count":795,"open_issues_count":0,"forks_count":66,"subscribers_count":9,"default_branch":"main","last_synced_at":"2025-05-12T08:56:43.953Z","etag":null,"topics":["enum","php"],"latest_commit_sha":null,"homepage":"https://docs.spatie.be/enum/v3/introduction","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/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","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,"zenodo":null},"funding":{"github":"spatie","custom":"https://spatie.be/open-source/support-us"}},"created_at":"2019-02-07T08:13:21.000Z","updated_at":"2025-05-12T07:50:28.000Z","dependencies_parsed_at":"2023-02-16T05:01:20.224Z","dependency_job_id":"a39a6418-733a-499d-8e1d-a4c4226a44ba","html_url":"https://github.com/spatie/enum","commit_stats":{"total_commits":378,"total_committers":43,"mean_commits":8.790697674418604,"dds":0.5132275132275133,"last_synced_commit":"d29c18f9dfe078317a0a734b3898db381a7ab41f"},"previous_names":[],"tags_count":45,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fenum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fenum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fenum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fenum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/enum/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254010813,"owners_count":21998995,"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","php"],"created_at":"2024-08-01T16:01:28.469Z","updated_at":"2025-05-13T19:14:13.289Z","avatar_url":"https://github.com/spatie.png","language":"PHP","readme":"# Enum\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/enum.svg?style=flat-square)](https://packagist.org/packages/spatie/enum)\n[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/spatie/enum/run-tests.yml?branch=main\u0026label=tests\u0026style=flat-square)](https://github.com/spatie/enum/actions?query=workflow%3Arun-tests+branch%3Amain)\n[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/spatie/enum/php-cs-fixer.yml?branch=main\u0026label=code%20style\u0026style=flat-square)](https://github.com/spatie/enum/actions?query=workflow%3A\"Fix+PHP+code+style+issues\"+branch%3Amain)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/enum.svg?style=flat-square)](https://packagist.org/packages/spatie/enum)\n\n\u003e :warning: With the introduction of **Enums** in PHP 8.1, this package is now considered obsolete. For new projects, we recommend using **native enums** instead of this package. Learn more about native enums here: https://stitcher.io/blog/php-enums\n\n---\n\nThis package offers strongly typed enums in PHP. In this package, enums are always objects, never constant values on their own. This allows for proper static analysis and refactoring in IDEs.\n\nHere's how enums are created with this package:\n\n```php\nuse \\Spatie\\Enum\\Enum;\n\n/**\n * @method static self draft()\n * @method static self published()\n * @method static self archived()\n */\nclass StatusEnum extends Enum\n{\n}\n```\n\nAnd this is how they are used:\n\n```php\npublic function setStatus(StatusEnum $status): void\n{\n    $this-\u003estatus = $status;\n}\n\n// ...\n\n$class-\u003esetStatus(StatusEnum::draft());\n```\n\n## Support us\n\n[\u003cimg src=\"https://github-ads.s3.eu-central-1.amazonaws.com/enum.jpg?t=1\" width=\"419px\" /\u003e](https://spatie.be/github-ad-click/enum)\n\nWe invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).\n\nWe highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require spatie/enum\n```\n\n## Usage\n\nThis is how an enum can be defined.\n\n```php\n/**\n * @method static self draft()\n * @method static self published()\n * @method static self archived()\n */\nclass StatusEnum extends Enum\n{\n}\n```\n\nThis is how they are used:\n\n```php\npublic function setStatus(StatusEnum $status)\n{\n    $this-\u003estatus = $status;\n}\n\n// ...\n\n$class-\u003esetStatus(StatusEnum::draft());\n```\n\n| Autocompletion               | Refactoring              |\n| ---------------------------- | ------------------------ |\n| ![](./docs/autocomplete.gif) | ![](./docs/refactor.gif) |\n\n### Creating an enum from a value\n\n```php\n$status = StatusEnum::from('draft');\n```\n\nWhen an enum value doesn't exist, you'll get a `BadMethodCallException`. If you would prefer not catching an exception, you can use:\n\n```php\n$status = StatusEnum::tryFrom('draft');\n```\n\nWhen an enum value doesn't exist in this case, `$status` will be `null`.\n\nThe only time you want to construct an enum from a value is when unserializing them from eg. a database.\n\nIf you want to get the value of an enum to store it, you can do this:\n\n```php\n$status-\u003evalue;\n```\n\nNote that `value` is a read-only property, it cannot be changed.\n\n### Enum values\n\nBy default, the enum value is its method name. You can however override it, for example if you want to store enums as integers in a database, instead of using their method name.\n\n```php\n/**\n * @method static self draft()\n * @method static self published()\n * @method static self archived()\n */\nclass StatusEnum extends Enum\n{\n    protected static function values(): array\n    {\n        return [\n            'draft' =\u003e 1,\n            'published' =\u003e 2,\n            'archived' =\u003e 3,\n        ];\n    }\n}\n```\n\nAn enum value doesn't have to be a `string`, as you can see in the example it can also be an `int`.\n\nNote that you don't need to override all values. Rather, you only need to override the ones that you want to be different from the default.\n\nIf you have a logic that should be applied to all method names to get the value, like lowercase them, you can return a `Closure`.\n\n```php\n/**\n * @method static self DRAFT()\n * @method static self PUBLISHED()\n * @method static self ARCHIVED()\n */\nclass StatusEnum extends Enum\n{\n    protected static function values(): Closure\n    {\n        return function(string $name): string|int {\n            return mb_strtolower($name);\n        };\n    }\n}\n```\n\n### Enum labels\n\nEnums can be given a label, you can do this by overriding the `labels` method.\n\n```php\n/**\n * @method static self draft()\n * @method static self published()\n * @method static self archived()\n */\nclass StatusEnum extends Enum\n{\n    protected static function labels(): array\n    {\n        return [\n            'draft' =\u003e 'my draft label',\n        ];\n    }\n}\n```\n\nNote that you don't need to override all labels, the default label will be the enum's value.\n\nIf you have a logic that should be applied to all method names to get the label, like lowercase them, you can return a `Closure` as in the value example.\n\nYou can access an enum's label like so:\n\n```php\n$status-\u003elabel;\n```\n\nNote that `label` is a read-only property, it cannot be changed.\n\n### Comparing enums\n\nEnums can be compared using the `equals` method:\n\n```php\n$status-\u003eequals(StatusEnum::draft());\n```\n\nYou can pass several enums to the `equals` method, it will return `true` if the current enum equals one of the given values.\n\n```php\n$status-\u003eequals(StatusEnum::draft(), StatusEnum::archived());\n```\n\n### Phpunit Assertions\n\nThis package provides an abstract class `Spatie\\Enum\\Phpunit\\EnumAssertions` with some basic/common assertions if you have to test enums.\n\n```php\nuse Spatie\\Enum\\Phpunit\\EnumAssertions;\n\nEnumAssertions::assertIsEnum($post-\u003estatus); // checks if actual extends Enum::class\nEnumAssertions::assertIsEnumValue(StatusEnum::class, 'draft'); // checks if actual is a value of given enum\nEnumAssertions::assertIsEnumLabel(StatusEnum::class, 'draft'); // checks if actual is a label of given enum\nEnumAssertions::assertEqualsEnum(StatusEnum::draft(), 'draft'); // checks if actual (transformed to enum) equals expected\nEnumAssertions::assertSameEnum(StatusEnum::draft(), $post-\u003estatus); // checks if actual is same as expected\nEnumAssertions::assertSameEnumValue(StatusEnum::draft(), 1); // checks if actual is same value as expected\nEnumAssertions::assertSameEnumLabel(StatusEnum::draft(), 'draft'); // checks if actual is same label as expected\n```\n\n### Faker Provider\n\nPossibly you are using [faker](https://github.com/FakerPHP/Faker) and want to generate random enums.\nBecause doing so with default faker is a lot of copy'n'paste we've got you covered with a faker provider `Spatie\\Enum\\Faker\\FakerEnumProvider`.\n\n```php\nuse Spatie\\Enum\\Faker\\FakerEnumProvider;\nuse Faker\\Generator as Faker;\n\n/** @var Faker|FakerEnumProvider $faker */\n$faker = new Faker();\n$faker-\u003eaddProvider(new FakerEnumProvider($faker));\n\n$enum = $faker-\u003erandomEnum(StatusEnum::class);\n$value = $faker-\u003erandomEnumValue(StatusEnum::class);\n$label = $faker-\u003erandomEnumLabel(StatusEnum::class);\n```\n\n## Testing\n\n```bash\ncomposer test\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.\n\n### Security\n\nIf you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker.\n\n## Postcardware\n\nYou're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.\n\nOur address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.\n\nWe publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).\n\n## Credits\n\n- [Brent Roose](https://github.com/brendt)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","funding_links":["https://github.com/sponsors/spatie","https://spatie.be/open-source/support-us"],"categories":["PHP"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Fenum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Fenum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Fenum/lists"}