sjorso/enum

An abstract class for making enums in Laravel

This package's canonical repository appears to be gone and the package has been frozen as a result.

1.2.1 2020-12-15 11:38 UTC

README

An abstract class for making enums in Laravel.

Install

composer require sjorso/enum

Creating enums

You can create an enum like this:

use SjorsO\Enum\Enum;

class UserRole extends Enum
{
    const USER = 'role_user';

    const ADMIN = 'role_admin';
}

Using enums

You can access the values of the enum in your code:

if ($user->role !== UserRole::ADMIN) {
    abort(401);
}

You can get all enum values as a Laravel collection by calling all(). A good use case for this is passing the enum values to a view, so they can be used in a select input:

return view('admin.user.edit', [
    'roles' => UserRole::values(),
]);

The Enum class offers two methods for generating validation rules:

$request->validate([
    'role' => UserRole::required(), // 'required|in:role_user,role_admin'    
    'role' => UserRole::optional(), // 'in:role_user,role_admin'    
]);

If you want to return an enum in an api response, you can do the following:

// returns an "Illuminate\Http\Resources\Json\JsonResource" containing the enum values
return UserRole::apiResource(); 

There are two methods for checking if an enum value is valid:

UserRole::has('role_user'); // true
UserRole::has('wrong_role'); // false

UserRole::assert('role_user'); // returns void
UserRole::assert('wrong_role'); // throws a RunTimeException

Enum arrays

This package also contains an abstract EnumArray class. The EnumArray class extends the Enum class. When using an enum array you can't access individual constants, but all the static methods still work.

You can create an enum array like this:

class Timezone extends EnumArray
{
    const VALUES = [
        'Africa/Abidjan',
        'Africa/Accra',
        'Africa/Addis_Ababa',
        'Africa/Algiers',
        'Africa/Asmara',
        'Africa/Bamako',
        // etc..
    ];
}

Ensuring all enum values are unique

Generally, all enum values should be unique. Adding a unit test for each of your enums can ensure that you haven't defined any duplicate values:

function test_all_enum_values_are_unique()
{
    $this->assertSame(
        UserRole::values()->toArray(),
        UserRole::values()->unique()->toArray()
    );
}

License

This project is open-sourced software licensed under the MIT license