An open API service indexing awesome lists of open source software.

https://github.com/marc-mabe/php-enum-cl

Compatibility layer for emulating enumerations in PHP < 8.1 and use native enumerations in PHP >= 8.1
https://github.com/marc-mabe/php-enum-cl

compatibility enum php polyfill

Last synced: 8 months ago
JSON representation

Compatibility layer for emulating enumerations in PHP < 8.1 and use native enumerations in PHP >= 8.1

Awesome Lists containing this project

README

          

# Compatibility layer for emulating enumerations in PHP \< 8.1 but native enumerations in PHP \>= 8.1

[![Build Status](https://github.com/marc-mabe/php-enum-cl/workflows/Test/badge.svg?branch=main)](https://github.com/marc-mabe/php-enum-cl/actions?query=workflow%3ATest%20branch%3Amain)
[![Code Coverage](https://codecov.io/github/marc-mabe/php-enum-cl/coverage.svg?branch=main)](https://codecov.io/gh/marc-mabe/php-enum-cl/branch/main/)

## How-to create

**Vendor\MyEnum.php**
```php
enum ENUMNAME {
use \Mabe\Enum\Cl\EnumBc;
case CASENAME;
// ...
} |

final class ENUMNAME extends \Mabe\Enum\Cl\EmulatedUnitEnum {
protected const CASENAME = null;
// ...
}
|
| Integer backed enum |
enum ENUMNAME:int {
use \Mabe\Enum\Cl\EnumBc;
case CASENAME = CASEVALUE;
// ...
}
|
final class ENUMNAME extends \Mabe\Enum\Cl\EmulatedIntEnum {
protected const CASENAME = CASEVALUE;
// ...
}
|
| String backed enum |
enum ENUMNAME:string {
use \Mabe\Enum\Cl\EnumBc;
case CASENAME = 'CASEVALUE';
// ...
}
|
final class ENUMNAME extends \Mabe\Enum\Cl\EmulatedStringEnum {
protected const CASENAME = 'CASEVALUE';
// ...
}
|

For IDE and static code analyzers I recommend adding the following docblock:

```php
/**
* @method static self CASENAME()
*/
```

## How-to use

The following will work the same on PHP<8.1 (using emulated enums)
and on PHP>=8.1 (using native enums):

```php
value; // 0
$zero->name; // ZERO

$zero instanceof \UnitEnum; // true
$zero instanceof \BackedEnum; // true

MyEnum::ZERO() === MyEnum::from(0); // true
MyEnum::from(0) === MyEnum::tryFrom(0); // true

enum_exists(MyEnum::class); // true
enum_exists('stdClass'); // false
```

**Warning:** The following will **not** behave the same on all PHP versions:
```php
=8.1: enum(MyEnum::ZERO)

serialize(MyEnum::ZERO()); // PHP<8.1: Error: Trying to serialize a non serializable emulated enum case of MyEnum
// PHP>=8.1: "E:11:"MyEnum:ZERO"
```

## Additional Notes

### PHPStan

By default PHPStan will complain about unused constants
as it can't automatically detect the special use via reflection in this case.

To avoid this you need to add the following to your `phpstan.neon[.dist]`:

```
services:
-
class: Mabe\Enum\Cl\PHPStan\ConstantExtension
tags:
- phpstan.constants.alwaysUsedClassConstantsExtension
```

For more information please read https://phpstan.org/developing-extensions/always-used-class-constants

### Included Polyfills

This library includes the following polyfills (if not already present):

* `get_debug_type`