tailflow/enum

PHP Enums

1.1 2020-11-05 13:45 UTC

This package is auto-updated.

Last update: 2024-04-24 21:02:09 UTC


README

Latest Version on Packagist Build Status

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.