• Stars
    star
    335
  • Rank 125,555 (Top 3 %)
  • Language
    PHP
  • License
    BSD 2-Clause "Sim...
  • Created almost 7 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHP 7.1 enum implementation

PHP 7.1 enums

Build Status Coverage Status Latest Stable Version Total Downloads License

It is a well known fact that PHP is missing a basic enum type, ignoring the rather incomplete SplEnum implementation which is only available as a PECL extension. There are also quite a few other userland enum implementations around, but all of them have one or another compromise. This library tries to close that gap as far as PHP allows it to.

Usage

Basics

At its core, there is the DASPRiD\Enum\AbstractEnum class, which by default will work with constants like any other enum implementation you might know. The first clear difference is that you should define all the constants as protected (so nobody outside your class can read them but the AbstractEnum can still do so). The other even mightier difference is that, for simple enums, the value of the constant doesn't matter at all. Let's have a look at a simple example:

use DASPRiD\Enum\AbstractEnum;

/**
 * @method static self MONDAY()
 * @method static self TUESDAY()
 * @method static self WEDNESDAY()
 * @method static self THURSDAY()
 * @method static self FRIDAY()
 * @method static self SATURDAY()
 * @method static self SUNDAY()
 */
final class WeekDay extends AbstractEnum
{
    protected const MONDAY = null;
    protected const TUESDAY = null;
    protected const WEDNESDAY = null;
    protected const THURSDAY = null;
    protected const FRIDAY = null;
    protected const SATURDAY = null;
    protected const SUNDAY = null;
}

If you need to provide constants for either internal use or public use, you can mark them as either private or public, in which case they will be ignored by the enum, which only considers protected constants as valid values. As you can see, we specifically defined the generated magic methods in a class level doc block, so anyone using this class will automatically have proper auto-completion in their IDE. Now since you have defined the enum, you can simply use it like that:

function tellItLikeItIs(WeekDay $weekDay)
{
    switch ($weekDay) {
        case WeekDay::MONDAY():
            echo 'Mondays are bad.';
            break;

        case WeekDay::FRIDAY():
            echo 'Fridays are better.';
            break;

        case WeekDay::SATURDAY():
        case WeekDay::SUNDAY():
            echo 'Weekends are best.';
            break;

        default:
            echo 'Midweek days are so-so.';
    }
}

tellItLikeItIs(WeekDay::MONDAY());
tellItLikeItIs(WeekDay::WEDNESDAY());
tellItLikeItIs(WeekDay::FRIDAY());
tellItLikeItIs(WeekDay::SATURDAY());
tellItLikeItIs(WeekDay::SUNDAY());

More complex example

Of course, all enums are singletons, which are not cloneable or serializable. Thus you can be sure that there is always just one instance of the same type. Of course, the values of constants are not completely useless, let's have a look at a more complex example:

use DASPRiD\Enum\AbstractEnum;

/**
 * @method static self MERCURY()
 * @method static self VENUS()
 * @method static self EARTH()
 * @method static self MARS()
 * @method static self JUPITER()
 * @method static self SATURN()
 * @method static self URANUS()
 * @method static self NEPTUNE()
 */
final class Planet extends AbstractEnum
{
    protected const MERCURY = [3.303e+23, 2.4397e6];
    protected const VENUS = [4.869e+24, 6.0518e6];
    protected const EARTH = [5.976e+24, 6.37814e6];
    protected const MARS = [6.421e+23, 3.3972e6];
    protected const JUPITER = [1.9e+27, 7.1492e7];
    protected const SATURN = [5.688e+26, 6.0268e7];
    protected const URANUS = [8.686e+25, 2.5559e7];
    protected const NEPTUNE = [1.024e+26, 2.4746e7];

    /**
     * Universal gravitational constant.
     *
     * @var float
     */
    private const G = 6.67300E-11;

    /**
     * Mass in kilograms.
     *
     * @var float
     */
    private $mass;

    /**
     * Radius in meters.
     *
     * @var float
     */
    private $radius;

    protected function __construct(float $mass, float $radius)
    {
        $this->mass = $mass;
        $this->radius = $radius;
    }

    public function mass() : float
    {
        return $this->mass;
    }

    public function radius() : float
    {
        return $this->radius;
    }

    public function surfaceGravity() : float
    {
        return self::G * $this->mass / ($this->radius * $this->radius);
    }

    public function surfaceWeight(float $otherMass) : float
    {
        return $otherMass * $this->surfaceGravity();
    }
}

$myMass = 80;

foreach (Planet::values() as $planet) {
    printf("Your weight on %s is %f\n", $planet, $planet->surfaceWeight($myMass));
}

More Repositories

1

container-interop-doctrine

Doctrine factories for container-interop
PHP
107
star
2

Flitch

PHP Coding Standard Validator
PHP
58
star
3

ZFCS

Zend Framework 2 Coding Standard
PHP
31
star
4

Helios

PSR-7 authentication middleware
PHP
30
star
5

vnstat-php

PHP frontend for vnStat
PHP
29
star
6

Dash

Flexible PSR-7 compliant HTTP router
PHP
29
star
7

Formidable

PHP 7 form library for handling user input
PHP
27
star
8

Ajasta

Ajasta is a simple invoicing application built with the latest technologies on the market.
PHP
26
star
9

Torrent-to-Web

Allows to send torrent files to web clients.
TypeScript
22
star
10

gimp-telegram-sticker

Makes a telegram sticker out of the current image
Python
21
star
11

Bacon

ZF2 module for common code across projects
PHP
21
star
12

gnome-shell-extension-area-screenshot

Extension to make screenshots of a selected area.
JavaScript
17
star
13

AssetLoader

AssetLoader module for ZF2
PHP
13
star
14

localized-address-format

Zero-dependency address formatting library.
TypeScript
13
star
15

DASBiT

Python based IRC bot
Python
9
star
16

Bootstrap-DatePicker

A simple datepicker for Bootstrap 3
8
star
17

gnome-screenshot-uploader

Upload wrapper for GNOME Screenshot
Python
5
star
18

DASBiT-PHP

PHP-based IRC bot
PHP
5
star
19

timetrap-to-jira

A simple utility to transfer your hours from timetrap to JIRA
PHP
5
star
20

jsonapi-zod-query

JSON:API Query Helpers utilizing Zod
TypeScript
5
star
21

Cbor

A PHP implementation of Concise Binary Object Representation (CBOR)
PHP
4
star
22

mui-rhf-integration

React Hook Form integration for MUI with strict TypeScript handling based on form context.
TypeScript
4
star
23

react-confirm-hook

Programmatically ask for user confirmation with custom confirm dialogs.
TypeScript
4
star
24

TreeReader

Structured array tree reader
PHP
3
star
25

RouterBenchmark

PHP
3
star
26

vrc-osc-manager

OSC client for managing VRChat accessories
Rust
3
star
27

google-form-telegram-bot-notifications

HTML
3
star
28

karlsfurs-registration

Registration system for the karlsfurs suitwalk
PHP
3
star
29

zod-joda

JS-Joda integration for Zod validation library
TypeScript
2
star
30

jsTyrian

JavaScript port of OpenTyrian
JavaScript
2
star
31

bitbucket-code-pipeline-integration

A simple Serverless project to assist in integrating on-premise Bitbucket with AWS CodePipeline.
TypeScript
2
star
32

eslint-config-dasprid

Strict ESLint configuration for TypeScript projects
JavaScript
2
star
33

SplBitArray

C++
2
star
34

shoutirc-php-client

Client for the ShoutIRC socket server
PHP
2
star
35

Pikkuleipa

PSR-7 JWT cookie handler
PHP
1
star
36

MyBackupr

CLI backup tool for Flickr
Python
1
star
37

CSRF-Guard

CSRF guard for middleware based applications
PHP
1
star
38

phpapidoc

PSR-5 compliant API doc generator
PHP
1
star
39

dasprids.de

My personal website and blog
PHP
1
star
40

dash-expressive

Bridge between Dash and Zend-Expressive
PHP
1
star
41

osc-watch-linux

OSC Linux client for the OSC Watch VRChat accessory
Rust
1
star
42

timetrap-to-harvest

A simple utility to transfer your hours from timetrap to Harvest
PHP
1
star
43

aw2013

Rust Driver for the AW2013 3-Channel LED Controller.
Rust
1
star