Skip to content

Simple Backed Enums implementation for PHP <8.1

License

Notifications You must be signed in to change notification settings

heheheheheehyqo/enum

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

hyqo/enum implementation

Packagist Version Packagist PHP Version Support GitHub Workflow Status

Simple Backed Enums implementation for PHP <8.1

Install

composer require hyqo/enum

This is very similar to real PHP 8.1 Backed Enums: https://www.php.net/manual/en/language.enumerations.backed.php

  • static method from($case): self will take a scalar and return the corresponding Enum Case. If one is not found, it will throw an exception
  • static method tryFrom($case): ?self will take a scalar and return the corresponding Enum Case. If one is not found, it will return null
  • static method cases(): array returns a packed array of all defined Cases
  • read-only property value is the value specified in the definition
  • read-only property name is the case-sensitive name of the case itself
  • Enums may contain methods

But these are not real Enums, so Cases must be defined via public constants

Usage

use \Hyqo\Enum\Enum;

class Suit extends Enum
{
    public const Hearts = 'H';
    public const Diamonds = 'D';
    public const Clubs = 'C';
    public const Spades = 'S';

    public function color(): string
    {
        switch ($this->value) {
            case self::Hearts:
            case self::Diamonds:
                return 'red';
            case self::Clubs:
            case self::Spades:
                return 'black';
        }
    }
}

Suit::from(Suit::Hearts)->value; //H
Suit::from(Suit::Hearts)->name; //Hearts
Suit::from(Suit::Hearts)->color(); //red

Suit::Spades()->value; //S
Suit::Spades()->name; //Spades
Suit::Spades()->color(); //black

Suit::tryFrom('foo'); //null
Suit::from('foo'); //throw \Hyqo\Enum\InvalidValueException

Suit::from(Suit::Hearts)->foo; //throw \RuntimeException
Suit::from(Suit::Hearts)->value = 'foo'; //throw \RuntimeException