Enum

This package goal is to provide a complete solution to lack a long time php weakness : it do not have any enum support.
This will change with php 8 enums proposition. In the mean time we still a support for this allowing us to generate generic and extendable applications (instead of have singletons sql tables…).
You will be able to use enums in any project using a simple definition, take a look at example Basic or a more sophisticated Example
Installation
Via Composer
$ composer require kwaadpepper/enum
Usage
All enum have two properties : label and value, only value has to be unique. Each enum can have multiple options all written on class comment as static methods, these have to be unique !
- On Any project, take a look on examples to create an enum class.
-
Invoke an enum value
Days::mon()
-
Compare enums
Days::mon()->equals(Days::tue()) // false
Days::mon()->equals(Days::mon()) // true
Days::mon()->value === Days::tue()->value // false
Days::mon()->value === Days::mon()->value // true
-
Print an enum
echo Days::mon(); // 2
echo Days::tue(); // 4
echo Days::mon()->label; // Monday
As you can see enum implements the __toString method which you can override to display the label instead of the value.
This default behavior is set like this for a better behavior in laravel.
-
Serialise an enum
echo json_encode(Days::mon()); // {"label":"Monday","value":2}
Enums implement the JsonSerializable interface
- On a Laravel project you can use enums in multiple ways
-
As a property
// Add theses to your model
use CastsEnums;
protected $enumCasts = [
'day' => Days::class
];
This will allow you model to store an enum in database using its value, and then cast the property to an enum when accessing it
-
As a route parameter
Define a route like the following
Route::get('/days/{day}', function (Days $day) {
return response()->json([$day]);
})->middleware('bindings');
// OR
Route::get('/days/{day}', [DayController::class, 'getDay']);
Then on your controller for the DayController example
public function getDay(Request $request, Day $day) {
return response()->json([$day]);
}
-
As a request parameter using validation
Take a look at this request example.
new EnumIsValidRule(Days::class)
It use EnumIsValidRule to validate the parameter as being a valid enum value.
Note that you may still have to cast your parameter to int if your enum value is an int, as enum check is strict
-
As a model primary Key
Take a look at unit test using the Report enum class from tests
Change log
Please see the changelog for more information on what has changed recently.
Testing
$ composer test
Contributing
Please see contributing.md for details and a todolist.
Security
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
Credits
License
MIT. Please see the license file for more information.
评论