davidianbonner/enumerated

Enums represent a set of predefined values. Useful for ensuring data consistency.

v7.0.0 2024-05-16 13:38 UTC

This package is auto-updated.

Last update: 2024-11-16 14:40:15 UTC


README

Author Build Status Quality Score Software License Packagist Version Coverage Status

An enumerated type (Enum) is a data type that consists of a set of predefined values. This can be useful for ensuring data consistency. The Enumerated package provides a simple base class for creating enumerated types allowing the devloper to define values statically.

Install

Via Composer

$ composer require davidianbonner/enumerated

Usage

Most applications require some form of an enumerated type. PHP does not have native Enum support (yet: https://wiki.php.net/rfc/enum). To get past this, we tend to pack groups of predefined values into config or settings files as arrays. This doesn't represent the data or it's type in a straightforward manner.

Before

<?php

return [
    'language' => [
        'php' => 'php',
        'javascript' => 'js',
        'css' => 'css',
        'go' => 'go',
    ],
];

Used like so:

$codebase->language = config('language.php');

// or

foreach (config('language') as $language) {
    echo '<option value="'.$language.'">'.$language.'</option>';
}

After

An enum would be a better fit for this set of values.

<?php

use DavidIanBonner\Enumerated\Enum;

class Language extends Enum
{
    const PHP = 'php';
    const JAVASCRIPT = 'js';
    const GO = 'go';
    const CSS = 'css';
}

Used like so:

$codebase->language = Language::PHP;

// or

$type = Language::PHP;
$codebase->language = Language::ofType($type)->value();

// or

foreach (Language::allValues() as $language) {
    echo '<option value="'.$language.'">'.$language.'</option>';
}

Validate a value

A value can be validated against the predefined values:

if (Language::isValid($value)) {
    // Is valid
}

Laravel Collection instance

This package requires the Laravel Support package in order to return a collection of the available values:

// Returns an instance of Illuminate\Support\Collection
Language::collect();

Return keys

The allValues and collect method will accept a boolean argument to return the keys/constant names:

$values = Language::allValues(true);

// Returns
[
    'PHP' => 'php',
    'JAVASCRIPT' => 'js',
    'CSS' => 'css',
    'GO' => 'go',
]

Change log

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

Testing

$ phpunit test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email davidianbonner@gmail.com instead of using the issue tracker.

Credits

License

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