{"id":19218941,"url":"https://github.com/marc-mabe/php-enum","last_synced_at":"2025-05-14T04:07:33.569Z","repository":{"id":4325810,"uuid":"5460593","full_name":"marc-mabe/php-enum","owner":"marc-mabe","description":"Simple and fast implementation of enumerations with native PHP","archived":false,"fork":false,"pushed_at":"2024-11-28T12:12:54.000Z","size":554,"stargazers_count":469,"open_issues_count":1,"forks_count":36,"subscribers_count":15,"default_branch":"master","last_synced_at":"2025-04-13T17:46:35.761Z","etag":null,"topics":["enum","enumeration","enumerator","enummap","enumset","map","php","php-enum","set"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/marc-mabe.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","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":"2012-08-18T05:52:49.000Z","updated_at":"2025-04-11T09:45:19.000Z","dependencies_parsed_at":"2024-06-18T10:57:33.239Z","dependency_job_id":"90aa7fe6-d7f7-40e1-97b8-89c31e83f8f5","html_url":"https://github.com/marc-mabe/php-enum","commit_stats":{"total_commits":385,"total_committers":20,"mean_commits":19.25,"dds":"0.17142857142857137","last_synced_commit":"7159809e5cfa041dca28e61f7f7ae58063aae8ed"},"previous_names":[],"tags_count":38,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marc-mabe%2Fphp-enum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marc-mabe%2Fphp-enum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marc-mabe%2Fphp-enum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marc-mabe%2Fphp-enum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/marc-mabe","download_url":"https://codeload.github.com/marc-mabe/php-enum/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254069216,"owners_count":22009511,"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","enumerator","enummap","enumset","map","php","php-enum","set"],"created_at":"2024-11-09T14:28:49.389Z","updated_at":"2025-05-14T04:07:33.490Z","avatar_url":"https://github.com/marc-mabe.png","language":"PHP","readme":"# php-enum\n[![Build Status](https://github.com/marc-mabe/php-enum/workflows/Test/badge.svg?branch=master)](https://github.com/marc-mabe/php-enum/actions?query=workflow%3ATest%20branch%3Amaster)\n[![Code Coverage](https://codecov.io/github/marc-mabe/php-enum/coverage.svg?branch=master)](https://codecov.io/gh/marc-mabe/php-enum/branch/master/)\n[![License](https://poser.pugx.org/marc-mabe/php-enum/license)](https://github.com/marc-mabe/php-enum/blob/master/LICENSE.txt)\n[![Latest Stable](https://poser.pugx.org/marc-mabe/php-enum/v/stable.png)](https://packagist.org/packages/marc-mabe/php-enum)\n[![Total Downloads](https://poser.pugx.org/marc-mabe/php-enum/downloads.png)](https://packagist.org/packages/marc-mabe/php-enum)\n[![Monthly Downloads](https://poser.pugx.org/marc-mabe/php-enum/d/monthly)](https://packagist.org/packages/marc-mabe/php-enum)\n[![Dependents](https://poser.pugx.org/marc-mabe/php-enum/dependents)](https://packagist.org/packages/marc-mabe/php-enum/dependents?order_by=downloads)\n\nThis is a native PHP implementation to add enumeration support to PHP.\nIt's an abstract class that needs to be extended to use it.\n\n\n# What is an Enumeration?\n\n[Wikipedia](http://wikipedia.org/wiki/Enumerated_type)\n\u003e In computer programming, an enumerated type (also called enumeration or enum)\n\u003e is a data type consisting of a set of named values called elements, members\n\u003e or enumerators of the type. The enumerator names are usually identifiers that\n\u003e behave as constants in the language. A variable that has been declared as\n\u003e having an enumerated type can be assigned any of the enumerators as a value.\n\u003e In other words, an enumerated type has values that are different from each\n\u003e other, and that can be compared and assigned, but which do not have any\n\u003e particular concrete representation in the computer's memory; compilers and\n\u003e interpreters can represent them arbitrarily.\n\n\n# Usage\n\n## Basics\n\n```php\nuse MabeEnum\\Enum;\n\n// define an own enumeration class\nclass UserStatus extends Enum\n{\n    const INACTIVE = 'i';\n    const ACTIVE   = 'a';\n    const DELETED  = 'd';\n\n    // all scalar data types and arrays are supported as enumerator values\n    const NIL     = null;\n    const BOOLEAN = true;\n    const INT     = 1234;\n    const STR     = 'string';\n    const FLOAT   = 0.123;\n    const ARR     = ['this', 'is', ['an', 'array']];\n\n    // Enumerators will be generated from public constants only\n    public    const PUBLIC_CONST    = 'public constant';    // this will be an enumerator\n    protected const PROTECTED_CONST = 'protected constant'; // this will NOT be an enumerator\n    private   const PRIVATE_CONST   = 'private constant';   // this will NOT be an enumerator\n\n    // works since PHP-7.0 - see https://wiki.php.net/rfc/context_sensitive_lexer\n    const TRUE      = 'true';\n    const FALSE     = 'false';\n    const NULL      = 'null';\n    const PUBLIC    = 'public';\n    const PRIVATE   = 'private';\n    const PROTECTED = 'protected';\n    const FUNCTION  = 'function';\n    const TRAIT     = 'trait';\n    const INTERFACE = 'interface';\n\n    // Doesn't work - see https://wiki.php.net/rfc/class_name_scalars\n    // const CLASS = 'class';\n}\n\n// ways to instantiate an enumerator\n$status = UserStatus::get(UserStatus::ACTIVE); // by value or instance\n$status = UserStatus::ACTIVE();                // by name as callable\n$status = UserStatus::byValue('a');            // by value\n$status = UserStatus::byName('ACTIVE');        // by name\n$status = UserStatus::byOrdinal(1);            // by ordinal number\n\n// basic methods of an instantiated enumerator\n$status-\u003egetValue();   // returns the selected constant value\n$status-\u003egetName();    // returns the selected constant name\n$status-\u003egetOrdinal(); // returns the ordinal number of the selected constant\n\n// basic methods to list defined enumerators\nUserStatus::getEnumerators();  // returns a list of enumerator instances\nUserStatus::getValues();       // returns a list of enumerator values\nUserStatus::getNames();        // returns a list of enumerator names\nUserStatus::getOrdinals();     // returns a list of ordinal numbers\nUserStatus::getConstants();    // returns an associative array of enumerator names to enumerator values\n\n// same enumerators (of the same enumeration class) holds the same instance\nUserStatus::get(UserStatus::ACTIVE) === UserStatus::ACTIVE()\nUserStatus::get(UserStatus::DELETED) != UserStatus::INACTIVE()\n\n// simplified way to compare two enumerators\n$status = UserStatus::ACTIVE();\n$status-\u003eis(UserStatus::ACTIVE);     // true\n$status-\u003eis(UserStatus::ACTIVE());   // true\n$status-\u003eis(UserStatus::DELETED);    // false\n$status-\u003eis(UserStatus::DELETED());  // false\n```\n\n## Type-Hint\n\n```php\nuse MabeEnum\\Enum;\n\nclass User\n{\n    protected $status;\n\n    public function setStatus(UserStatus $status)\n    {\n        $this-\u003estatus = $status;\n    }\n\n    public function getStatus()\n    {\n        if (!$this-\u003estatus) {\n            // initialize default\n            $this-\u003estatus = UserStatus::INACTIVE();\n        }\n        return $this-\u003estatus;\n    }\n}\n```\n\n### Type-Hint issue\n\nBecause in normal OOP the above example allows `UserStatus` and types inherited from it.\n\nPlease think about the following example:\n\n```php\nclass ExtendedUserStatus extends UserStatus\n{\n    const EXTENDED = 'extended';\n}\n\n$user = new User();\n$user-\u003esetStatus(ExtendedUserStatus::EXTENDED());\n```\n\nNow the setter receives a status it doesn't know about but allows it.\n\n#### Solution 1: Finalize the enumeration\n\n```php\nfinal class UserStatus extends Enum\n{\n    // ...\n}\n\nclass User\n{\n    protected $status;\n\n    public function setStatus(UserStatus $status)\n    {\n        $this-\u003estatus = $status;\n    }\n}\n````\n\n* Nice and obvious solution\n\n* Resulting behaviour matches native enumeration implementation of most other languages (like Java)\n\nBut as this library emulates enumerations it has a few downsides:\n\n* Enumerator values can not be used directly\n  * `$user-\u003esetStatus(UserStatus::ACTIVE)` fails\n  * `$user-\u003esetStatus(UserStatus::ACTIVE())` works\n\n* Does not help if the enumeration was defined in an external library\n\n\n#### Solution 2: Using `Enum::get()`\n\n```php\nclass User\n{\n    public function setStatus($status)\n    {\n        $this-\u003estatus = UserStatus::get($status);\n    }\n}\n```\n\n* Makes sure the resulting enumerator exactly matches an enumeration. (Inherited enumerators are not allowed).\n\n* Allows enumerator values directly\n  * `$user-\u003esetStatus(UserStatus::ACTIVE)` works\n  * `$user-\u003esetStatus(UserStatus::ACTIVE())` works\n\n* Also works for enumerations defined in external libraries\n\nBut of course this solution has downsides, too:\n\n* Looses declarative type-hint\n\n* A bit slower\n\n\n## EnumSet\n\nAn `EnumSet` is a specialized Set implementation for use with enumeration types.\nAll of the enumerators in an `EnumSet` must come from a single enumeration type that is specified, when the set is\ncreated.\n\nEnum sets are represented internally as bit vectors. The bit vector is either an integer type or a binary string type\ndepending on how many enumerators are defined in the enumeration type. This representation is extremely compact and\nefficient. Bulk operations will run very quickly. Enumerators of an `EnumSet` are unique and ordered based on its\nordinal number by design.\n\nIt implements `IteratorAggregate` and `Countable` to be directly iterable with `foreach` and countable with `count()`.\n\nThe `EnumSet` has a mutable and an immutable interface.\nMutable methods start with `set`, `add` or `remove` while immutable methods start with `with`.\n\n```php\nuse MabeEnum\\EnumSet;\n\n// create a new EnumSet and initialize with the given enumerators\n$enumSet = new EnumSet('UserStatus', [UserStatus::ACTIVE()]);\n\n// modify an EnumSet (mutable interface)\n\n// add enumerators (by value or by instance)\n$enumSet-\u003eaddIterable([UserStatus::INACTIVE, UserStatus::DELETED()]);\n// or\n$enumSet-\u003eadd(UserStatus::INACTIVE);\n$enumSet-\u003eadd(UserStatus::DELETED());\n\n// remove enumerators (by value or by instance)\n$enumSet-\u003eremoveIterable([UserStatus::INACTIVE, UserStatus::DELETED()]);\n// or\n$enumSet-\u003eremove(UserStatus::INACTIVE);\n$enumSet-\u003eremove(UserStatus::DELETED());\n\n\n// The immutable interface will create a new EnumSet for each modification \n\n// add enumerators (by value or by instance)\n$enumSet = $enumSet-\u003ewithIterable([UserStatus::INACTIVE, UserStatus::DELETED()]);\n// or\n$enumSet = $enumSet-\u003ewith(UserStatus::INACTIVE);\n$enumSet = $enumSet-\u003ewith(UserStatus::DELETED());\n\n// remove enumerators (by value or by instance)\n$enumSet-\u003ewithoutIterable([UserStatus::INACTIVE, UserStatus::DELETED()]);\n// or\n$enumSet = $enumSet-\u003ewithout(UserStatus::INACTIVE);\n$enumSet = $enumSet-\u003ewithout(UserStatus::DELETED());\n\n\n// Test if an enumerator exists (by value or by instance)\n$enumSet-\u003ehas(UserStatus::INACTIVE); // bool\n\n\n// count the number of enumerators\n$enumSet-\u003ecount();\ncount($enumSet);\n\n// test for elements\n$enumSet-\u003eisEmpty();\n\n// convert to array\n$enumSet-\u003egetValues();      // List of enumerator values\n$enumSet-\u003egetEnumerators(); // List of enumerator instances\n$enumSet-\u003egetNames();       // List of enumerator names\n$enumSet-\u003egetOrdinals();    // List of ordinal numbers\n\n\n// iterating over the set\nforeach ($enumSet as $ordinal =\u003e $enum) {\n    gettype($ordinal);  // int (the ordinal number of the enumerator)\n    get_class($enum);   // UserStatus (enumerator object)\n}\n\n\n// compare two EnumSets\n$enumSet-\u003eisEqual($other);    // Check if the EnumSet is the same as other\n$enumSet-\u003eisSubset($other);   // Check if the EnumSet is a subset of other\n$enumSet-\u003eisSuperset($other); // Check if the EnumSet is a superset of other\n\n\n// union, intersect, difference and symmetric difference\n\n// ... the mutable interface will modify the set\n$enumSet-\u003esetUnion($other);     // Enumerators from both this and other (this | other)\n$enumSet-\u003esetIntersect($other); // Enumerators common to both this and other (this \u0026 other)\n$enumSet-\u003esetDiff($other);      // Enumerators in this but not in other (this - other)\n$enumSet-\u003esetSymDiff($other);   // Enumerators in either this and other but not in both (this ^ other)\n\n// ... the immutable interface will produce a new set\n$enumSet = $enumSet-\u003ewithUnion($other);     // Enumerators from both this and other (this | other)\n$enumSet = $enumSet-\u003ewithIntersect($other); // Enumerators common to both this and other (this \u0026 other)\n$enumSet = $enumSet-\u003ewithDiff($other);      // Enumerators in this but not in other (this - other)\n$enumSet = $enumSet-\u003ewithSymDiff($other);   // Enumerators in either this and other but not in both (this ^ other)\n```\n\n\n## EnumMap\n\nAn `EnumMap` maps enumerators of the same type to data assigned to.\n\nIt implements `ArrayAccess`, `Countable` and `IteratorAggregate`\nso elements can be accessed, iterated and counted like a normal array\nusing `$enumMap[$key]`, `foreach` and `count()`.\n\n```php\nuse MabeEnum\\EnumMap;\n\n// create a new EnumMap\n$enumMap = new EnumMap('UserStatus');\n\n\n// read and write key-value-pairs like an array\n$enumMap[UserStatus::INACTIVE] = 'inaktiv';\n$enumMap[UserStatus::ACTIVE]   = 'aktiv';\n$enumMap[UserStatus::DELETED]  = 'gelöscht';\n$enumMap[UserStatus::INACTIVE]; // 'inaktiv';\n$enumMap[UserStatus::ACTIVE];   // 'aktiv';\n$enumMap[UserStatus::DELETED];  // 'gelöscht';\n\nisset($enumMap[UserStatus::DELETED]); // true\nunset($enumMap[UserStatus::DELETED]);\nisset($enumMap[UserStatus::DELETED]); // false\n\n// ... no matter if you use enumerator values or enumerator objects\n$enumMap[UserStatus::INACTIVE()] = 'inaktiv';\n$enumMap[UserStatus::ACTIVE()]   = 'aktiv';\n$enumMap[UserStatus::DELETED()]  = 'gelöscht';\n$enumMap[UserStatus::INACTIVE()]; // 'inaktiv';\n$enumMap[UserStatus::ACTIVE()];   // 'aktiv';\n$enumMap[UserStatus::DELETED()];  // 'gelöscht';\n\nisset($enumMap[UserStatus::DELETED()]); // true\nunset($enumMap[UserStatus::DELETED()]);\nisset($enumMap[UserStatus::DELETED()]); // false\n\n\n// count number of attached elements\n$enumMap-\u003ecount();\ncount($enumMap);\n\n// test for elements\n$enumMap-\u003eisEmpty();\n\n// support for null aware exists check\n$enumMap[UserStatus::NULL] = null;\nisset($enumMap[UserStatus::NULL]); // false\n$enumMap-\u003ehas(UserStatus::NULL);   // true\n\n\n// iterating over the map\nforeach ($enumMap as $enum =\u003e $value) {\n    get_class($enum);  // UserStatus (enumerator object)\n    gettype($value);   // mixed (the value the enumerators maps to)\n}\n\n// get a list of keys (= a list of enumerator objects)\n$enumMap-\u003egetKeys();\n\n// get a list of values (= a list of values the enumerator maps to)\n$enumMap-\u003egetValues();\n```\n\n\n## Serializing\n\nBecause this enumeration implementation is based on a singleton pattern and in PHP\nit's currently impossible to unserialize a singleton without creating a new instance\nthis feature isn't supported without any additional work.\n\nAs of it's an often requested feature there is a trait that can be added to your\nenumeration definition. The trait adds serialization functionallity and injects\nthe unserialized enumeration instance in case it's the first one.\nThis reduces singleton behavior breakage but still it beaks if it's not the first\ninstance and you could result in two different instance of the same enumeration.\n\n**Use it with caution!**\n\nPS: `EnumSet` and `EnumMap` are serializable by default as long as you don't set other non-serializable values.\n\n\n### Example of using EnumSerializableTrait\n\n```php\nuse MabeEnum\\Enum;\nuse MabeEnum\\EnumSerializableTrait;\nuse Serializable;\n\nclass CardinalDirection extends Enum implements Serializable\n{\n    use EnumSerializableTrait;\n\n    const NORTH = 'n';\n    const EAST  = 'e';\n    const WEST  = 'w';\n    const SOUTH = 's';\n}\n\n$north1 = CardinalDirection::NORTH();\n$north2 = unserialize(serialize($north1));\n\nvar_dump($north1 === $north2);  // returns FALSE as described above\nvar_dump($north1-\u003eis($north2)); // returns TRUE - this way the two instances are treated equal\nvar_dump($north2-\u003eis($north1)); // returns TRUE - equality works in both directions\n```\n\n\n# Generics and Static Code Analyzer\n\nWith version 4.3 we have added support for generics and added better type support.\n\n* `EnumSet\u003cT of Enum\u003e`\n* `EnumMap\u003cT of Enum\u003e`\n\nGeneric types will be detected by [PHPStan](https://phpstan.org/) and [Psalm](https://psalm.dev/).\n\nAdditionally, we have developed an [extension for PHPStan](https://github.com/marc-mabe/php-enum-phpstan/)\nto make enumerator accessor methods known.\n\n\n# Why not `SplEnum`\n\n* `SplEnum` is not built-in into PHP and requires pecl extension installed.\n* Instances of the same value of an `SplEnum` are not the same instance.\n* No support for `EnumMap` or `EnumSet`.\n\n\n# Changelog\n\nChanges are documented in the [release page](https://github.com/marc-mabe/php-enum/releases).\n\n\n# Install\n\n## Composer\n\nAdd `marc-mabe/php-enum` to the project's composer.json dependencies and run\n`php composer.phar install`\n\n## GIT\n\n`git clone git://github.com/marc-mabe/php-enum.git`\n\n## ZIP / TAR\n\nDownload the last version from [Github](https://github.com/marc-mabe/php-enum/tags)\nand extract it.\n\n\n# Versioning and Releases\n\nThis project follows [SemVer](https://semver.org/) specification. \n\nThere are **no** [LTS](https://en.wikipedia.org/wiki/Long-term_support) releases\nand we don't have (fixed) time based release windows.\nInstead releases happen as necessary.\n\nWe do support at least all maintained PHP versions.\n\nBug fixes will be backported to the latest maintained minor release.\n\nCritical bug fixes and security relates fixes can also be backported to older releases.\n\n| Release | Status      | PHP-Version     |\n|---------|-------------|-----------------|\n| 1.x     | EOL         | \\\u003e=5.3          |\n| 2.x     | EOL         | \\\u003e=5.3 \u0026 HHVM\u003c4 |\n| 3.x     | EOL         | \\\u003e=5.6 \u0026 HHVM\u003c4 |\n| 4.x     | active      | \\\u003e=7.1          |\n\n\n# New BSD License\n\nThe files in this archive are released under the New BSD License.\nYou can find a copy of this license in LICENSE.txt file.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarc-mabe%2Fphp-enum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmarc-mabe%2Fphp-enum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarc-mabe%2Fphp-enum/lists"}