Strongly typed enums in PHP supporting autocompletion and refactoring
Branch: master
Clone or download
brendt Merge pull request #7 from bramus/patch-1
Force colors when running `composer test`
Latest commit 7dceac2 Feb 19, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
docs Update README Feb 7, 2019
src Merge pull request #4 from b1rdex/patch-1 Feb 18, 2019
tests Add strict types Feb 18, 2019
.editorconfig Setup Feb 7, 2019
.gitattributes Setup Feb 7, 2019
.gitignore Update README Feb 7, 2019
.scrutinizer.yml Setup Feb 7, 2019
.styleci.yml Setup Feb 7, 2019
.travis.yml upgrade phpunit Feb 7, 2019
CHANGELOG.md Update CHANGELOG.md Feb 8, 2019
CONTRIBUTING.md Setup Feb 7, 2019
LICENSE.md Setup Feb 7, 2019
README.md Don't require name in static values Feb 8, 2019
composer.json Force colors when running `composer test` Feb 19, 2019
phpunit.xml.dist Setup Feb 7, 2019

README.md

PHP Enum

Latest Version on Packagist Build Status StyleCI Quality Score Total Downloads

This package offers strongly typed enums in PHP. We don't use a simple "value" representation, so you're always working with the enum object. This allows for proper autocompletion and refactoring in IDEs.

Here's how enums are created with this package:

/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
}

And this is how they are used:

public function setStatus(StatusEnum $status): void
{
    $this->status = $status;
}

//

$class->setStatus(StatusEnum::draft());

Installation

You can install the package via composer:

composer require spatie/enum

Usage

This is how an enum can be defined.

/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
}

This is how they are used:

public function setStatus(StatusEnum $status)
{
    $this->status = $status;
}

//

$class->setStatus(StatusEnum::draft());

Creating an enum from a value

$status = StatusEnum::from('draft');

// or

$status = new StatusEnum('published');

Override enum values

By default, the string value of an enum is simply the name of that method. In the previous example it would be draft.

You can override this value, by adding the $map property:

/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
    protected static $map = [
        'draft' => 1,
        'published' => 'other published value',
        'archived' => -10,
    ];
}

Mapping values is optional.

Comparing enums

Enums can be compared using the equals method:

$status->equals($otherStatus);

Enum specific methods

There might be a case where you want to have functionality depending on the concrete enum value.

There are several ways to do this:

  • Add a function in the enum class and using a switch statement or array mapping.
  • Use a separate class which contains this switch logic, something like enum extensions in C#.
  • Use enum specific methods, similar to Java.

This package also supports these enum specific methods. Here's how you can implement them:

abstract class MonthEnum extends Enum
{
    abstract public function getNumericIndex(): int;

    public static function january(): MonthEnum
    {
        return new class() extends MonthEnum
        {
            public function getNumericIndex(): int
            {
                return 1;
            }
        };
    }

    public static function february(): MonthEnum
    {
        return new class() extends MonthEnum
        {
            public function getNumericIndex(): int
            {
                return 2;
            }
        };
    }
    
    //
}

By declaring the enum class itself as abstract, and using static constructors instead of doc comments, you're able to return an anonymous class per enum, each of them implementing the required methods.

You can use this enum the same way as any other:

MonthEnum::january()->getNumericIndex()

Note that one drawback of this approach is that the value of the enum is always the name of the static function, there's no way of mapping it.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

Support us

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

Does your business depend on our contributions? Reach out and support us on Patreon. All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff.

License

The MIT License (MIT). Please see License File for more information.