PHP code example of markbaker / enumhelper

1. Go to this page and download the library: Download markbaker/enumhelper 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/ */

    

markbaker / enumhelper example snippets


enum Suit: string {
    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

$suit = Suit::Diamonds;

$value = $suit->value;      // Returns 'D' 

$newSuit = Suit::from($value);

enum Suit: string {
    use EnumHelper\EnumRestorableFromName;

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

$suit = Suit::Diamonds;

$suitName = $suit->name;      // Returns 'Diamonds' 

$newSuit = Suit::fromName($suitName);

enum Suit: string {
    use EnumHelper\EnumValidatableCase;

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

$suit = Suit::Diamonds;

$validCaseName = Suit::Hearts;
$isCaseNameValid = Suit::isValidCase($validCaseName);      // Returns boolean true

$invalidCaseName = 'HeArTs';
$isCaseNameValid = Suit::isValidCase($invalidCaseName);    // Returns boolean false

enum Suit: string {
    use EnumHelper\EnumValidatableCase;

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

var_dump(Suit::cases());

enum Suit: string {
    use EnumHelper\CasesIndexedByName;

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';
}

var_dump(Suit::casesIndexedByName());

enum Suit: string {
    use EnumHelper\CasesIndexedByName;

    public const RED = 'Red';
    public const BLACK = 'Black';

    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';

    public function color(): string {
        return match($this) {
            self::Hearts, self::Diamonds => self::RED,
            self::Clubs, self::Spades => self::BLACK,
        };
    }

    public static function red(): array {
        return array_filter(
            self::casesIndexedByName(),
            fn(self $suit) => $suit->color() === self::RED
        );
    }

    public static function black(): array {
        return array_filter(
            self::casesIndexedByName(),
            fn(self $suit) => $suit->color() === self::BLACK
        );
    }
}

var_dump(Suit::black());

array(2) {
  ["Clubs"]=>
  enum(Suit::Clubs)
  ["Spades"]=>
  enum(Suit::Spades)
}