Skip to content
forked from greg0ire/enum

A workaround for the missing php enum type

License

Notifications You must be signed in to change notification settings

therealmikz/enum

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Enums

This package holds a simple class that may be use as an ancestor for your enum classes.

Installation

composer require greg0ire/enum

Usage

Extend the Greg0ire\Enum\BaseEnum, define your enum key values as constants, and Bob's your uncle. You can make the class abstract or final, as you see fit.

use Greg0ire\Enum\BaseEnum;

final class DaysOfWeek extends BasicEnum {
    const Sunday = 0;
    const Monday = 1;
    const Tuesday = 2;
    const Wednesday = 3;
    const Thursday = 4;
    const Friday = 5;
    const Saturday = 6;
}

Then, you may use the DaysOfWeek class for input validation:

DaysOfWeek::isValidName('Humpday');                  // false
DaysOfWeek::isValidName('Monday');                   // true
DaysOfWeek::isValidName('monday');                   // true
DaysOfWeek::isValidName('monday', $strict = true);   // false
DaysOfWeek::isValidName(0);                          // false

DaysOfWeek::isValidValue(0);                         // true
DaysOfWeek::isValidValue(5);                         // true
DaysOfWeek::isValidValue(7);                         // false
DaysOfWeek::isValidValue('Friday');                  // false

Additionally, you may get all the constants in your class as a hash:

DaysOfWeek::getConstants()

Contributing

see CONTRIBUTING.md

Credits

This is a shameless rip-off of this Stack Overflow answer, with one modification: the getConstants method has been made public so that it is available for building choice widgets, for instance.

About

A workaround for the missing php enum type

Resources

License

Stars

Watchers

Forks

Packages

No packages published