paillechat/php-enum

Enum implementation for PHP 7

2.1 2018-07-10 09:57 UTC

This package is not auto-updated.

Last update: 2024-04-19 15:39:03 UTC


README

Build Status Scrutinizer Code Quality Code Coverage Latest Stable Version Total Downloads

A PHP 7+ enumeration library.

Why?

To create perfect enums for PHP library

Installation

composer require "paillechat/php-enum:^2.0"

Usage

Declare enum class by extending basic Enum and filling it with constants. Constant value does not matter. You can fill it with any payload you can utilize as general constant, but we suggest you to keep constants as protected as possible

<?php

use Paillechat\Enum\Enum;

/**
 * These docs are used only to help IDE
 * 
 * @method static static ONE
 * @method static static TWO
 */
class IssueType extends Enum 
{
    protected const ONE = 1;
    protected const TWO = 2;
} 

# Now you can create enum via named static call
/** @var Enum $one */
$one = IssueType::ONE();

# Enums keeps strict equality
$one1 = IssueType::ONE();
$one2 = IssueType::ONE();
$two = IssueType::TWO();

$one1 === $one2;
$one !== $two;

# Enums plays well with built-in functions
\in_array(IssueType::ONE(), [$one, $two], true);

# Enums plays well with signature type checks
function moveIssue(IssueType $type) {
    if ($type === IssueType::ONE()) {
        throw new \LogicException();
    }
    
    // ....
}

# You can convert enum to name and back
$name = $one->getName();
$new = IssueType::$name();