wscore / enum
Enumerated class.
Installs: 24
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 2
pkg:composer/wscore/enum
This package is not auto-updated.
Last update: 2025-10-26 11:34:11 UTC
README
Enum and list implementation
Licence
MIT License
Installation
composer require "wscore/enum: ^1.0"
Sample Code
create a EnumList class
The intended way of creating a enumerated class is,
- define constants,
- define static
$choicesarray.
as in the example below.
use WScore\Enum\AbstractEnum; class EnumList extends AbstractEnum { const ENUM = 'enum'; const VALUE = 'value'; protected static $choices = [ self::ENUM => 'enumerated', self::VALUE => 'value', ]; }
The $choices variable defines available values
along side with labels (i.e. human readable string).
get enumerated object
static function, enum, returns an instantiated enumerated
object, which is EnumInterface
$enum = EnumList::enum(EnumList::ENUM); (string) $enum; // enum $enum->label(); // enumerated $enum->is(EnumList::ENUM); // true
enum list and keys
Use static methods such as, choices(), keys(), or flipped(),
to get the list of available enum values and keys, that may be
used for validating inputs.
$list = EnumList::choices(); // returns list of keys and labels. $keys = EnumList::keys(); // returns keys of enumerated list. $flip = EnumList::flipped(); // returns array of key/value flipped.
subset of choices
In some use cases, you may need to restrict the selectable values.
For instance, the ActiveList class below, has 3 statuses
but may want to restrict to only 2 options for the end-user,
as defined in in userChoice.
class ActiveList extends AbstractEnum { const ACTIVE = 'active'; const CANCEL = 'cancel'; const HOLD = 'hold'; protected static $choices = [ self::ACTIVE => 'activated', self::CANCEL => 'canceled', self::HOLD => 'hold-on', ]; /** * @return array */ public static function userChoice() { return [ self::ACTIVE => 'activated', self::CANCEL => 'canceled', ]; } }
To get the available choices,
$list = ActiveList::userChoice(); $keys = ActiveList::keys('userChoice'); $flip = ActiveList::flipped('userChoice');
really restricting use of list
To really limit choices to the subset of
the original static::$choices...
use WScore\Enum\AbstractEnum; class EnumList extends AbstractEnum { const ENUM = 'enum'; const VALUE = 'value'; protected static $choices = [ self::ENUM => 'enumerated', self::VALUE => 'value', ]; /** * @param string $value * @return EnumList */ public static function getUserEnum($value) { $choices = self::$choices; unset($choices[self::VALUE]); return new EnumList($value, $choices); } }
then, the following code will throw an \InvalidArgumentException.
$enum = EnumList::getUserEnum(EnumList::VALUE);