Skip to content

Elegant Enum implementation for Laravel. With make:enum command, ability to casting for Eloquent models and labels translations via lang files.

License

Notifications You must be signed in to change notification settings

hilltool/laravel-enum

Repository files navigation

Very short description of the package

Latest Version on Packagist Software License Build Status StyleCI Coverage Status Quality Score Total Downloads

Elegant Enum implementation for Laravel.

Based on MyCLabs PHP Enum and implements SplEnum interface.

You could find documentation for base features in PHP Enum Readme.

Features:

  • make:enum command
  • ability to cast enum fields for Eloquent models
  • labels translation via lang files
  • simple validation rule

Simple Enum Example

namespace App\Enums;

use MadWeb\Enum\Enum;

/**
 * @method static PostStatusEnum FOO()
 * @method static PostStatusEnum BAR()
 * @method static PostStatusEnum BAZ()
 */
final class PostStatusEnum extends Enum
{
    const __default = self::PENDING;

    const PUBLISHED = 'published';
    const PENDING = 'pending';
    const DRAFT = 'draft';
}

Installation

You can install the package via composer:

composer require mad-web/laravel-enum

If you use Laravel 5.4 version, add service provider into app.php config file

// config/app.php

'providers' => [
    ...
    \MadWeb\Enum\EnumServiceProvider::class,
],

Usage

Make new Enum class via artisan command

php artisan make:enum PostStatusEnum

Create instance of Enum class

$status = new PostStatusEnum(PostStatusEnum::PENDING);

// or just use magic static method
$status = PostStatusEnum::PENDING();

In order to use enum values with Eloquent models you could use EnumCastable trait.

class Post extends Model
{
    use EnumCastable;

    protected $fillable = ['title', 'status'];

    protected $casts = [
        'status' => PostStatusEnum::class,
    ];
}

after that you could get and set enum field using enum classes

$post = Post::first();

$status = $post->status; // PostStatusEnum

$post->status = PostStatusEnum::PENDING();

$post->save();

Enum values labels (Localization)

Create enums.php lang file and declare labels for enum values

// resources/lang/en/enums.php

return [
    PostStatusEnum::class => [
        PostStatusEnum::PENDING => 'Pending Label',
        PostStatusEnum::PUBLISHED => 'Published Label',
        PostStatusEnum::DRAFT => 'Draft Label',
    ],
];

and get a label

PostStatusEnum::PENDING()->label(); // Pending Label

To override default enum lang file path, publish laravel-enum config

php artisan vendor:publish --provider=MadWeb\\Enum\\EnumServiceProvider

and change lang_file_path option

// config/enum.php

return [
    'lang_file_path' => 'custom.path.to.enums',
];

Validation Rule

You may validate an enum value from a request by using the EnumRule class or Enum::rule() method.

public function store(Request $request)
{
    $this->validate($request, [
        'status' => ['required', new EnumRule(PostStatusEnum::class)],
    ]);

    // OR

    $this->validate($request, [
        'status' => ['required', PostStatusEnum::rule()],
    ]);
}

To customize validation message, add enum key to validation lang file

// resources/lang/en/validation.php
    ...
    'email' => 'The :attribute must be a valid email address.',
    'enum' => 'Custom validation message form enum attribute :attribute', // Custom message
    'exists' => 'The selected :attribute is invalid.',
    ...

Additional methods

getRandomKey(): string

Returns a random key from the enum.

PostStatusEnum::getRandomKey(); // Returns 'PUBLISHED` or `PENDING` or `DRAFT`

getRandomValue()

Returns a random value from the enum.

PostStatusEnum::getRandomValue(); // Returns 'published` or `pending` or `draft`

label(): string

Returns label for the enum value object

PostStatusEnum::PUBLISHED()->label(); // Returns 'published` or custom label declared in a lang file

labels(): array

Returns all labels for a enum

PostStatusEnum::labels(); // Returns ['published`, 'pending', 'draft'] or array of custom labels declared in a lang file

is($value): bool

Checks whether the current enum value is equal to a given enum

$status = PostStatusEnum::PENDING();


PostStatusEnum::PUBLISHED()->is($status); // false

PostStatusEnum::PENDING()->is($status); // true

// OR

PostStatusEnum::PUBLISHED()->is($status->getValue()); // false

PostStatusEnum::PENDING()->is($status->getValue()); // true

rule(): EnumRule

Returns instance of validation rule class for the Enum

PostStatusEnum::rule(); // new EnumRule(PostStatusEnum::class);

getConstList(bool $include_default = false): array

Returns all consts (possible values) as an array according to SplEnum::getConstList

Changelog

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

Testing

composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

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

About

Elegant Enum implementation for Laravel. With make:enum command, ability to casting for Eloquent models and labels translations via lang files.

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages