phpgears / enum
Enum for PHP
Requires
- php: ^7.1
- phpgears/immutability: ~0.2.2
Requires (Dev)
- brainmaestro/composer-git-hooks: ^2.8
- friendsofphp/php-cs-fixer: ^2.16
- infection/infection: ^0.13|^0.15
- overtrue/phplint: ^1.2
- phpmd/phpmd: ^2.8
- phpstan/extension-installer: ^1.0.3
- phpstan/phpstan: ^0.12
- phpstan/phpstan-deprecation-rules: ^0.12
- phpstan/phpstan-strict-rules: ^0.12
- phpunit/phpunit: ^7.5|^8.0
- povils/phpmnd: ^2.1
- roave/security-advisories: dev-master
- sebastian/phpcpd: ^4.0
- squizlabs/php_codesniffer: ^3.5
- thecodingmachine/phpstan-strict-rules: ^0.12
README
Enum
Immutable Enum objects for PHP
Other languages have the concept of Enum and while there is an extension in PHP for enums it's not available by default or widely spread
The implementation of an Enum class is not so difficult, but it should cover value validation and be immutable so its value cannot be changed
Installation
Composer
composer require phpgears/enum
Usage
Require composer autoload file
require './vendor/autoload.php';
By extending Gears\Enum\AbstractEnum
you can easily have Enum classes
use Gears\Enum\AbstractEnum; /** * @method static self DAILY() * @method static self WEEKLY() * @method static self BIWEEKLY() * @method static self MONTHLY() * @method static self YEARLY() */ final class DatePeriod extends AbstractEnum { public const DAILY = 'daily'; public const WEEKLY = 'weekly'; public const BIWEEKLY = 'biweekly'; public const MONTHLY = 'monthly'; public const YEARLY = 'yearly'; } $period = new DatePeriod('daily'); $period->getValue() === DatePeriod::DAILY; // true $period->isEqualTo(DatePeriod::DAILY()); // true $period->isAnyOf([DatePeriod::DAILY(), DatePeriod::WEEKLY()]); // true $period->getValue() === DatePeriod::YEARLY; // false $period->isEqualTo(DatePeriod::MONTHLY()); // false $period->isAnyOf([DatePeriod::MONTHLY(), DatePeriod::YEARLY()]); // false $period->getValue(); // daily $newPeriod = new DatePeriod($period); $newPeriod->getValue() === DatePeriod::DAILY; // true $newPeriod->getValue() === $period->getValue(); // true $newPeriod->isEqualTo($period); // true $newPeriod->getValue(); // daily
Enums must always be defined as final
It is advised to add @method
annotation references on class docblock for your editor to be able to help you with auto-completion
Contributing
Found a bug or have a feature request? Please open a new issue. Have a look at existing issues before.
See file CONTRIBUTING.md
License
See file LICENSE included with the source code for a copy of the license terms.