phpgears/enum

0.3 2020-03-07 11:35 UTC

This package is auto-updated.

Last update: 2024-12-21 03:49:38 UTC


README

PHP version Latest Version License

Build Status Style Check Code Quality Code Coverage

Total Downloads Monthly Downloads

Enum

Immutable Enum objects for PHP

Other languages have the concept of Enum and while there is an extension in PHP for enums it's not available by default or widely spread

The implementation of an Enum class is not so difficult, but it should cover value validation and be immutable so its value cannot be changed

Installation

Composer

composer require phpgears/enum

Usage

Require composer autoload file

require './vendor/autoload.php';

By extending Gears\Enum\AbstractEnum you can easily have Enum classes

use Gears\Enum\AbstractEnum;

/**
 * @method static self DAILY()
 * @method static self WEEKLY()
 * @method static self BIWEEKLY()
 * @method static self MONTHLY()
 * @method static self YEARLY()
 */
final class DatePeriod extends AbstractEnum
{
    public const DAILY = 'daily';
    public const WEEKLY = 'weekly';
    public const BIWEEKLY = 'biweekly';
    public const MONTHLY = 'monthly';
    public const YEARLY = 'yearly';
}

$period = new DatePeriod('daily');

$period->getValue() === DatePeriod::DAILY; // true
$period->isEqualTo(DatePeriod::DAILY()); // true
$period->isAnyOf([DatePeriod::DAILY(), DatePeriod::WEEKLY()]); // true

$period->getValue() === DatePeriod::YEARLY; // false
$period->isEqualTo(DatePeriod::MONTHLY()); // false
$period->isAnyOf([DatePeriod::MONTHLY(), DatePeriod::YEARLY()]); // false

$period->getValue(); // daily


$newPeriod = new DatePeriod($period);

$newPeriod->getValue() === DatePeriod::DAILY; // true
$newPeriod->getValue() === $period->getValue(); // true
$newPeriod->isEqualTo($period); // true

$newPeriod->getValue(); // daily

Enums must always be defined as final

It is advised to add @method annotation references on class docblock for your editor to be able to help you with auto-completion

Contributing

Found a bug or have a feature request? Please open a new issue. Have a look at existing issues before.

See file CONTRIBUTING.md

License

See file LICENSE included with the source code for a copy of the license terms.