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.
Installs: 8 449
Dependents: 0
Suggesters: 0
Security: 0
Stars: 3
Watchers: 3
Forks: 0
Open Issues: 0
Requires
- php: ^7.2|^8.0
- illuminate/http: ~5.5.0|~5.6.0|~5.7.0|~5.8.0|^6.0|^7.0|^8.0
- illuminate/support: ~5.5.0|~5.6.0|~5.7.0|~5.8.0|^6.0|^7.0|^8.0
Requires (Dev)
- phpunit/phpunit: ^8.0|^9.0
This package is auto-updated.
Last update: 2024-01-30 09:53:34 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