cable8mm/enum-getter

This package make Enums simple for making keys, values and combine array including translate function.

v1.3.0 2025-01-16 17:09 UTC

README

code-style run-tests Packagist Version Packagist Dependency Version Total Downloads Total Stars License

This package simplifies working with Enums by providing convenient functionality for handling keys, values, and combined arrays, including a translate function.

It is particularly useful for binding enums to select or multiselect tags in Laravel Nova, allowing you to manage and use translated values effortlessly.

Installation

You can install the package via composer:

composer require cable8mm/enum-getter

Usage

use Cable8mm\EnumGetter\EnumGetter;

enum Size: string
{
    use EnumGetter;

    case LARGE = 'large';
    case MIDDLE = 'middle';
    case SMALL = 'small';
}

print Size::LARGE->name
//=> 'LARGE'

print Size::LARGE->value
//=> 'large'

print Size::LARGE->value()
//=> 'large'

print Size::LARGE->name()
//=> 'LARGE'

print Size::names()
//=> ['LARGE', 'MIDDLE', 'SMALL']

print Size::values()
//=> ['large', 'middle', 'small']

print Size::array()
//=> ['LARGE'=>'large', 'MIDDLE'=>'middle', 'SMALL'=>'small']

print Size::getName('large')
//=> 'LARGE'

When overriding the value() method to support non-English values,

use Cable8mm\EnumGetter\EnumGetter;

enum Size2: string
{
    use EnumGetter;

    case LARGE = 'large';
    case MIDDLE = 'middle';
    case SMALL = 'small';

    public function value(): string
    {
        return match ($this) {
            self::LARGE => 'grand', // __('large') can use a translation module
            self::MIDDLE => 'milieu', // __('milieu') can use a translation module
            self::SMALL => 'petit(e)', // __('small') can use a translation module
        };
    }
}

print Size2::LARGE->name
//=> 'LARGE'

print Size::LARGE->value
//=> 'large'

print Size::LARGE->value()
//=> 'grand'

print Size2::LARGE->name()
//=> 'LARGE'

print Size2::names()
//=> ['LARGE', 'MIDDLE', 'SMALL']

print Size2::values()
//=> ['grand', 'milieu', 'petit(e)']

print Size2::array()
//=> ['LARGE'=>'grand', 'MIDDLE'=>'milieu', 'SMALL'=>'petit(e)']

print Size::getName('grand')
//=> 'LARGE'

Let me share you a example for Laravel Nova:

// In field of Nova resource
Select::make(__('Size'), 'size')
    ->options(Size2::array())
    ->displayUsingLabels(),

// In Nova factory file
public function definition(): array
{
    return [
        'size' => fake()->randomElement(Size2::names()),
    ];
}

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

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

Credits

License

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