Ultralightweight enum type for PHP

1.0 2017-06-21 08:22 UTC

This package is not auto-updated.

Last update: 2024-12-22 04:48:03 UTC


README

Build Status Downloads this Month Latest stable

Simple trait to create enumeration classes.

Separate your enumerations into standalone classes and validate through your application that you are passing valid enumeration values.

Installation

Recommended to install using composer:

composer require richard-ejem/enum

Example

class UserRole
{
    use \Ejem\Enum\EnumTrait;
    
    const GUEST = 'guest';
    const USER = 'user';
    const ADMIN = 'admin';
}

class User
{
    /** @var string UserRole enum */
    private $role;
    
    /** @throws \Ejem\Enum\InvalidEnumValueException */
    public function __construct(string $role)
    {
        $this->setRole($role);
    }
    
    public function getRole(): string
    {
        return $this->role;
    }
    
    /** @throws \Ejem\Enum\InvalidEnumValueException */
    public function setRole(string $role): void
    {
        UserRole::assertValidValue($role);
        $this->role = $role;
    }
    
    // ... more user stuff
}

Other features

// Validate without throwing exception.
// imagine you are importing users from an old system,
// setting all unsupported roles to GUEST:

$role = UserRole::isValidValue($row['role']) ? $row['role'] : UserRole::GUEST;
    
// Retrieve all possible values.
// Assign random color to a shape

$values = Color::getPossibleValues();
$shape->setColor($values[mt_rand(0, count($values)-1)]);