richard-ejem / enum
Ultralightweight enum type for PHP
Installs: 3 538
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: >=7
Requires (Dev)
This package is not auto-updated.
Last update: 2024-12-22 04:48:03 UTC
README
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)]);