{"id":18348791,"url":"https://github.com/cloudstek/php-enum","last_synced_at":"2025-04-06T09:31:51.558Z","repository":{"id":56954253,"uuid":"241196992","full_name":"Cloudstek/php-enum","owner":"Cloudstek","description":"Enumeration support for PHP","archived":false,"fork":false,"pushed_at":"2022-05-18T16:02:03.000Z","size":48,"stargazers_count":16,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-21T21:21:44.259Z","etag":null,"topics":["enum","enumeration","php","php-library"],"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/Cloudstek.png","metadata":{"files":{"readme":"README.md","changelog":null,"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-02-17T20:04:48.000Z","updated_at":"2025-01-25T06:56:41.000Z","dependencies_parsed_at":"2022-08-21T08:50:17.578Z","dependency_job_id":null,"html_url":"https://github.com/Cloudstek/php-enum","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cloudstek%2Fphp-enum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cloudstek%2Fphp-enum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cloudstek%2Fphp-enum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cloudstek%2Fphp-enum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Cloudstek","download_url":"https://codeload.github.com/Cloudstek/php-enum/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247463745,"owners_count":20942935,"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","php","php-library"],"created_at":"2024-11-05T21:19:17.233Z","updated_at":"2025-04-06T09:31:51.173Z","avatar_url":"https://github.com/Cloudstek.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PHP Enum\n\n\u003e Enumeration support for PHP.\n\n[![Build Status](https://img.shields.io/github/workflow/status/Cloudstek/php-enum/php)](https://github.com/Cloudstek/php-enum/actions) [![Coverage Status](https://coveralls.io/repos/github/Cloudstek/php-enum/badge.svg)](https://coveralls.io/github/Cloudstek/php-enum) ![GitHub tag (latest SemVer)](https://img.shields.io/github/v/tag/Cloudstek/php-enum?label=latest) ![Downloads](https://img.shields.io/packagist/dt/cloudstek/php-enum) ![GitHub](https://img.shields.io/github/license/Cloudstek/php-enum) ![GitHub stars](https://img.shields.io/github/stars/Cloudstek/php-enum)\n\nThis package adds support for [enumerations](https://en.wikipedia.org/wiki/Enumerated_type) to PHP, ~~which are unfortunately not supported natively~~.\n\n⚠️ Since PHP 8.1 there is finally native support for enums in PHP. Please consider upgrading to PHP 8.1+ and migrating away from this package if you require enums in your application.\n\nUsing a simple class with constants alone doesn't allow you to use type hints meaning you still have to do extensive checks whether the value is expected. This package allows you to define enumerations the same way but allows for type hinting for example your method parameter. This way you can always be sure it holds a concrete set of members and values.\n\n## Requirements\n\n- PHP 7.1+\n- Composer*\n\n*\\* Installation without composer is possible as the package consists of a single class, but is obviously not recommended.*\n\n## Installation\n\nInstall the package through composer:\n\n```bash\ncomposer require cloudstek/php-enum\n```\n\n## Usage\n\n### Definition\n\nThe `Cloudstek\\Enum\\Enum` base class takes care of all the work behind the scenes so all you have to do is extend your enum class from that and define your members using either properties, constants, methods or a mix of those.\n\nTake for example this `TaskStatus` enum with three members: `TODO`, `IN_PROGRESS` and `DONE`. Each has a string value in this example but you're free to assign any kind of value you like.\n\n```php\nuse Cloudstek\\Enum\\Enum;\n\n/**\n * @method static self TODO()\n * @method static self IN_PROGRESS()\n * @method static self DONE()\n */\nclass TaskStatus extends Enum\n{\n    private const TODO = 'todo';\n    private const IN_PROGRESS = 'in_progress';\n    private const DONE = 'done';\n}\n```\n\n*The doctype is only required for autocompletion in IDEs, not for the enum to function.*\n\nMake sure you define your members as either `private` or `protected` to avoid confusion leading to direct access to a member's value instead of an instance, causing exceptions when your code expects an instance and not the value (such as the example below).\n\n```php\nTaskStatus::TODO !== TaskStatus::TODO()\n```\n\n```php\nclass Task\n{\n    /** @var TaskStatus */\n    private $status;\n\n    /**\n     * Set status\n     *\n     * @param TaskStatus $status\n     */\n    public function setStatus(TaskStatus $status)\n    {\n        $this-\u003estatus = $status;\n    }\n\n    // ..\n}\n```\n\nOr if you need to be more flexible, the `get` method will intelligently return the member by name or if an object is given, check that it's the correct type.\n\n```php\nclass Task\n{\n    /** @var TaskStatus */\n    private $status;\n\n    /**\n     * Set status\n     *\n     * @param TaskStatus|string $status\n     * \n     * @throws \\UnexpectedValueException On unknown status.\n     */\n    public function setStatus($status)\n    {\n        $this-\u003estatus = TaskStatus::get($status);\n    }\n\n    // ..\n}\n```\n\nTo read more about ways to define your members and how to name them, please see [docs/definition.md](docs/definition.md).\n\n### Comparison\n\nWith enums you're always dealing with a single instance per member therefore you can compare them directly.\n\n```php\n// Compare by instance\nTaskStatus::TODO() === TaskStatus::TODO();                 // true\nTaskStatus::TODO() === TaskStatus::get('todo');            // true\nTaskStatus::get('TODO') === TaskStatus::get('todo');       // true\nTaskStatus::TODO() === TaskStatus::get(TaskStatus::TODO()) // true\n\nTaskStatus::TODO() === TaskStatus::DONE();                 // false\nTaskStatus::TODO() === TaskStatus::get('done');            // false\n\n// Compare by value\n(string) TaskStatus::TODO() === 'todo';                    // true\nTaskStatus::TODO()-\u003egetValue() === 'todo';                 // true\n```\n\n### Inheritance\n\nYou should always define your enums as `final` classes to prevent other classes from inheriting from it. If you want other classes inheriting it, consider making it `abstract` and write `final` concrete classes that inherit from it.\n\nWithout making it final, your code could accept inherited enums when all you expected was the base class. This could lead to nasty bugs.\n\nFor example consider these enums:\n\n```php\nuse Cloudstek\\Enum\\Enum;\n\nclass FooEnum extends Enum\n{\n    private const FOO = 'foo';\n}\n\nclass BarEnum extends FooEnum\n{\n    private const BAR = 'bar';\n}\n```\n\nWithout making `FooEnum` final, your code could unintentionally accept `BarEnum` as well even though it is expecting `FooEnum`.\n\n```php\nclass Foo\n{\n    public function doSomething(FooEnum $foo)\n    {\n        // Do something...\n    }\n}\n\n$foo = new Foo();\n$foo-\u003edoSomething(FooEnum::FOO()); // Allowed and OK, we were expecting FooEnum\n$foo-\u003edoSomething(BarEnum::BAR()); // Allowed but not OK, we got BarEnum!\n```\n\nTo prevent this and to make sure we always get `FooEnum` we should mark it final. Which doesn't mean it can't inherit anything else.\n\n```php\nuse Cloudstek\\Enum\\Enum;\n\nabstract class BaseEnum extends Enum\n{\n    private const HELLO = 'world';\n}\n\nfinal class FooEnum extends BaseEnum\n{\n    private const FOO = 'foo';\n}\n\nfinal class BarEnum extends BaseEnum\n{\n    private const BAR = 'bar';\n}\n```\n\nNow we're sure we only get instances of `FooEnum`.\n\n```php\nclass Foo\n{\n    public function doSomething(FooEnum $foo)\n    {\n      // Do something...\n    }\n}\n\n$foo = new Foo();\n$foo-\u003edoSomething(FooEnum::FOO()); // Allowed and OK, we were expecting FooEnum\n$foo-\u003edoSomething(BarEnum::BAR()); // Fatal error\n```\n\nBut in case we really don't care, as long as its base type is `BaseEnum`, we have to change the parameter type to `BaseEnum` explicitly like so:\n\n```php\nclass Foo\n{\n    public function doSomething(BaseEnum $foo)\n    {\n      // Do something...\n    }\n}\n\n$foo = new Foo();\n$foo-\u003edoSomething(FooEnum::FOO()); // OK\n$foo-\u003edoSomething(BarEnum::BAR()); // OK\n```\n\n### Storing data\n\nIf you store data containing an enum and you want to convert it back into an enum later, make sure to store the member name using `getName()` instead of storing its value. If you only care about the value, just store the value using `getValue()` or by casting it to a string (if possible).\n\n```php\n// Update task\n$status = TaskStatus::TODO();\n\n$db-\u003eupdate($task, [\n    'status' =\u003e $status-\u003egetName() // 'status' =\u003e 'todo'\n]);\n```\n\n```php\n// Fetch task\n$taskRow = $db-\u003etasks-\u003efetchOne(13); // [..., 'status' =\u003e 'todo', ...]\n\n$task = new Task();\n// ..\n$task-\u003esetStatus(TaskStatus::get($taskRow['status']));\n\n// or if you call TaskStatus::get() in Task::setStatus()\n$task-\u003esetStatus($taskRow['status']);\n```\n\n## Support\n\nYou can support this project by contributing to open issues, submitting pull requests, giving this project a :star: or telling your friends about it.\n\nIf you have any ideas or issues, please open up an issue!\n\n## Related projects\n\n* [spatie/enum](https://github.com/spatie/enum)\n* [myclabs/php-enum](https://github.com/myclabs/php-enum)\n* [eloquent/enumeration](https://github.com/eloquent/enumeration)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcloudstek%2Fphp-enum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcloudstek%2Fphp-enum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcloudstek%2Fphp-enum/lists"}