Skip to content

bogordesaincom/laravel-enum

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

78 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Elegant Enum implementation for Laravel

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

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

For Laravel < 7 version - use 1.0 branch.

You can install the package via composer:

composer require mad-web/laravel-enum

Usage

Make new Enum class via artisan command:

php artisan make:enum PostStatusEnum

to populate Enum with your own values, pass it after name argument:

php artisan make:enum PostStatusEnum DRAFT=draft PENDING=pending PUBLISHED=published

Create instance of Enum class

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

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

Enums support native Custom Casts feature out of the box. Specify Enum class for attribute in $casts array:

class Post extends Model
{
    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()],
    ]);
}

If you want to validate an enum key instead of an enum value you can by specifying you want to validate against the key instead of the value.

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

    // OR

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

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

// resources/lang/en/validation.php
return [
    //...
    'enum' => 'Custom validation message form enum attribute :attribute',
];

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

// or check one of multiple values

$status->is([PostStatusEnum::DRAFT(), PostStatusEnum::PUBLISHED()]) // false

$status->is([PostStatusEnum::DRAFT(), PostStatusEnum::PENDING()]) // 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

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%