PHP code example of marc-mabe / php-enum

1. Go to this page and download the library: Download marc-mabe/php-enum library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

marc-mabe / php-enum example snippets


use MabeEnum\Enum;

// define an own enumeration class
class UserStatus extends Enum
{
    const INACTIVE = 'i';
    const ACTIVE   = 'a';
    const DELETED  = 'd';

    // all scalar data types and arrays are supported as enumerator values
    const NIL     = null;
    const BOOLEAN = true;
    const INT     = 1234;
    const STR     = 'string';
    const FLOAT   = 0.123;
    const ARR     = ['this', 'is', ['an', 'array']];

    // Enumerators will be generated from public constants only
    public    const PUBLIC_CONST    = 'public constant';    // this will be an enumerator
    protected const PROTECTED_CONST = 'protected constant'; // this will NOT be an enumerator
    private   const PRIVATE_CONST   = 'private constant';   // this will NOT be an enumerator

    // works since PHP-7.0 - see https://wiki.php.net/rfc/context_sensitive_lexer
    const TRUE      = 'true';
    const FALSE     = 'false';
    const NULL      = 'null';
    const PUBLIC    = 'public';
    const PRIVATE   = 'private';
    const PROTECTED = 'protected';
    const FUNCTION  = 'function';
    const TRAIT     = 'trait';
    const INTERFACE = 'interface';

    // Doesn't work - see https://wiki.php.net/rfc/class_name_scalars
    // const CLASS = 'class';
}

// ways to instantiate an enumerator
$status = UserStatus::get(UserStatus::ACTIVE); // by value or instance
$status = UserStatus::ACTIVE();                // by name as callable
$status = UserStatus::byValue('a');            // by value
$status = UserStatus::byName('ACTIVE');        // by name
$status = UserStatus::byOrdinal(1);            // by ordinal number

// basic methods of an instantiated enumerator
$status->getValue();   // returns the selected constant value
$status->getName();    // returns the selected constant name
$status->getOrdinal(); // returns the ordinal number of the selected constant

// basic methods to list defined enumerators
UserStatus::getEnumerators();  // returns a list of enumerator instances
UserStatus::getValues();       // returns a list of enumerator values
UserStatus::getNames();        // returns a list of enumerator names
UserStatus::getOrdinals();     // returns a list of ordinal numbers
UserStatus::getConstants();    // returns an associative array of enumerator names to enumerator values

// same enumerators (of the same enumeration class) holds the same instance
UserStatus::get(UserStatus::ACTIVE) === UserStatus::ACTIVE()
UserStatus::get(UserStatus::DELETED) != UserStatus::INACTIVE()

// simplified way to compare two enumerators
$status = UserStatus::ACTIVE();
$status->is(UserStatus::ACTIVE);     // true
$status->is(UserStatus::ACTIVE());   // true
$status->is(UserStatus::DELETED);    // false
$status->is(UserStatus::DELETED());  // false

use MabeEnum\Enum;

class User
{
    protected $status;

    public function setStatus(UserStatus $status)
    {
        $this->status = $status;
    }

    public function getStatus()
    {
        if (!$this->status) {
            // initialize default
            $this->status = UserStatus::INACTIVE();
        }
        return $this->status;
    }
}

class ExtendedUserStatus extends UserStatus
{
    const EXTENDED = 'extended';
}

$user = new User();
$user->setStatus(ExtendedUserStatus::EXTENDED());

final class UserStatus extends Enum
{
    // ...
}

class User
{
    protected $status;

    public function setStatus(UserStatus $status)
    {
        $this->status = $status;
    }
}

class User
{
    public function setStatus($status)
    {
        $this->status = UserStatus::get($status);
    }
}

use MabeEnum\EnumSet;

// create a new EnumSet and initialize with the given enumerators
$enumSet = new EnumSet('UserStatus', [UserStatus::ACTIVE()]);

// modify an EnumSet (mutable interface)

// add enumerators (by value or by instance)
$enumSet->addIterable([UserStatus::INACTIVE, UserStatus::DELETED()]);
// or
$enumSet->add(UserStatus::INACTIVE);
$enumSet->add(UserStatus::DELETED());

// remove enumerators (by value or by instance)
$enumSet->removeIterable([UserStatus::INACTIVE, UserStatus::DELETED()]);
// or
$enumSet->remove(UserStatus::INACTIVE);
$enumSet->remove(UserStatus::DELETED());


// The immutable interface will create a new EnumSet for each modification 

// add enumerators (by value or by instance)
$enumSet = $enumSet->withIterable([UserStatus::INACTIVE, UserStatus::DELETED()]);
// or
$enumSet = $enumSet->with(UserStatus::INACTIVE);
$enumSet = $enumSet->with(UserStatus::DELETED());

// remove enumerators (by value or by instance)
$enumSet->withoutIterable([UserStatus::INACTIVE, UserStatus::DELETED()]);
// or
$enumSet = $enumSet->without(UserStatus::INACTIVE);
$enumSet = $enumSet->without(UserStatus::DELETED());


// Test if an enumerator exists (by value or by instance)
$enumSet->has(UserStatus::INACTIVE); // bool


// count the number of enumerators
$enumSet->count();
count($enumSet);

// test for elements
$enumSet->isEmpty();

// convert to array
$enumSet->getValues();      // List of enumerator values
$enumSet->getEnumerators(); // List of enumerator instances
$enumSet->getNames();       // List of enumerator names
$enumSet->getOrdinals();    // List of ordinal numbers


// iterating over the set
foreach ($enumSet as $ordinal => $enum) {
    gettype($ordinal);  // int (the ordinal number of the enumerator)
    get_class($enum);   // UserStatus (enumerator object)
}


// compare two EnumSets
$enumSet->isEqual($other);    // Check if the EnumSet is the same as other
$enumSet->isSubset($other);   // Check if the EnumSet is a subset of other
$enumSet->isSuperset($other); // Check if the EnumSet is a superset of other


// union, intersect, difference and symmetric difference

// ... the mutable interface will modify the set
$enumSet->setUnion($other);     // Enumerators from both this and other (this | other)
$enumSet->setIntersect($other); // Enumerators common to both this and other (this & other)
$enumSet->setDiff($other);      // Enumerators in this but not in other (this - other)
$enumSet->setSymDiff($other);   // Enumerators in either this and other but not in both (this ^ other)

// ... the immutable interface will produce a new set
$enumSet = $enumSet->withUnion($other);     // Enumerators from both this and other (this | other)
$enumSet = $enumSet->withIntersect($other); // Enumerators common to both this and other (this & other)
$enumSet = $enumSet->withDiff($other);      // Enumerators in this but not in other (this - other)
$enumSet = $enumSet->withSymDiff($other);   // Enumerators in either this and other but not in both (this ^ other)

use MabeEnum\EnumMap;

// create a new EnumMap
$enumMap = new EnumMap('UserStatus');


// read and write key-value-pairs like an array
$enumMap[UserStatus::INACTIVE] = 'inaktiv';
$enumMap[UserStatus::ACTIVE]   = 'aktiv';
$enumMap[UserStatus::DELETED]  = 'gelöscht';
$enumMap[UserStatus::INACTIVE]; // 'inaktiv';
$enumMap[UserStatus::ACTIVE];   // 'aktiv';
$enumMap[UserStatus::DELETED];  // 'gelöscht';

isset($enumMap[UserStatus::DELETED]); // true
unset($enumMap[UserStatus::DELETED]);
isset($enumMap[UserStatus::DELETED]); // false

// ... no matter if you use enumerator values or enumerator objects
$enumMap[UserStatus::INACTIVE()] = 'inaktiv';
$enumMap[UserStatus::ACTIVE()]   = 'aktiv';
$enumMap[UserStatus::DELETED()]  = 'gelöscht';
$enumMap[UserStatus::INACTIVE()]; // 'inaktiv';
$enumMap[UserStatus::ACTIVE()];   // 'aktiv';
$enumMap[UserStatus::DELETED()];  // 'gelöscht';

isset($enumMap[UserStatus::DELETED()]); // true
unset($enumMap[UserStatus::DELETED()]);
isset($enumMap[UserStatus::DELETED()]); // false


// count number of attached elements
$enumMap->count();
count($enumMap);

// test for elements
$enumMap->isEmpty();

// support for null aware exists check
$enumMap[UserStatus::NULL] = null;
isset($enumMap[UserStatus::NULL]); // false
$enumMap->has(UserStatus::NULL);   // true


// iterating over the map
foreach ($enumMap as $enum => $value) {
    get_class($enum);  // UserStatus (enumerator object)
    gettype($value);   // mixed (the value the enumerators maps to)
}

// get a list of keys (= a list of enumerator objects)
$enumMap->getKeys();

// get a list of values (= a list of values the enumerator maps to)
$enumMap->getValues();

use MabeEnum\Enum;
use MabeEnum\EnumSerializableTrait;
use Serializable;

class CardinalDirection extends Enum implements Serializable
{
    use EnumSerializableTrait;

    const NORTH = 'n';
    const EAST  = 'e';
    const WEST  = 'w';
    const SOUTH = 's';
}

$north1 = CardinalDirection::NORTH();
$north2 = unserialize(serialize($north1));

var_dump($north1 === $north2);  // returns FALSE as described above
var_dump($north1->is($north2)); // returns TRUE - this way the two instances are treated equal
var_dump($north2->is($north1)); // returns TRUE - equality works in both directions