tailflow / enum
PHP Enums
Installs: 4 355
Dependents: 0
Suggesters: 0
Security: 0
Stars: 9
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: ^7.5
README
Introduction
The 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.
Installation
You can install the package via composer:
composer require tailflow/enum
Usage
Here is how enums are defined:
use Tailflow\Enum\Enum; class Status extends Enum { public const Inactive = 0; public const Active = 1; public const OnHold = 3; }
This is how they are used:
$class->setStatus(Status::Inactive);
Custom enum labels
By default, enum labels are derived from the constant names. To get enum label, you can use ::getLabel
method on enum class:
// $label will be equal to "OnHold" - the name of the constant $label = Status::getLabel(Status::OnHold);
Optionally, you can provide a different label for any given enum value:
use Tailflow\Enum\Enum; class Status extends Enum { public const Inactive = 0; public const Active = 1; public const OnHold = 3; public static function labels(): array { return [ self::OnHold => 'waiting' ]; } } // $label will be equal to "waiting" - the custom label defined in "labels" method $label = Status::getLabel(Status::OnHold);
Listing all enum labels
To get a list of all labels of the enum, you can use ::getLabels
method:
// $labels will contain the array - ['Inactive', 'Active', 'waiting'] $labels = Status::getLabels();
Listing all enum values
To get a list of all values of the enum, you can use ::getValues
method:
// $labels will contain the array - [0, 1, 3] $labels = Status::getValues();
License
The Laravel Orion is open-source software licensed under the MIT license.