davidianbonner / enumerated
Enums represent a set of predefined values. Useful for ensuring data consistency.
Installs: 35 073
Dependents: 2
Suggesters: 0
Security: 0
Stars: 1
Watchers: 2
Forks: 2
Open Issues: 1
Requires
- php: ^8.1
- illuminate/support: ^9.30|^10.0|^11.0
Requires (Dev)
- mockery/mockery: ^1.0
- orchestra/testbench: ^7.1
- phpunit/phpunit: ~9.5
- squizlabs/php_codesniffer: ^2.3
README
An enumerated type (Enum) is a data type that consists of a set of predefined values. This can be useful for ensuring data consistency. The Enumerated package provides a simple base class for creating enumerated types allowing the devloper to define values statically.
Install
Via Composer
$ composer require davidianbonner/enumerated
Usage
Most applications require some form of an enumerated type. PHP does not have native Enum support (yet: https://wiki.php.net/rfc/enum). To get past this, we tend to pack groups of predefined values into config or settings files as arrays. This doesn't represent the data or it's type in a straightforward manner.
Before
<?php return [ 'language' => [ 'php' => 'php', 'javascript' => 'js', 'css' => 'css', 'go' => 'go', ], ];
Used like so:
$codebase->language = config('language.php'); // or foreach (config('language') as $language) { echo '<option value="'.$language.'">'.$language.'</option>'; }
After
An enum would be a better fit for this set of values.
<?php use DavidIanBonner\Enumerated\Enum; class Language extends Enum { const PHP = 'php'; const JAVASCRIPT = 'js'; const GO = 'go'; const CSS = 'css'; }
Used like so:
$codebase->language = Language::PHP; // or $type = Language::PHP; $codebase->language = Language::ofType($type)->value(); // or foreach (Language::allValues() as $language) { echo '<option value="'.$language.'">'.$language.'</option>'; }
Validate a value
A value can be validated against the predefined values:
if (Language::isValid($value)) { // Is valid }
Laravel Collection instance
This package requires the Laravel Support package in order to return a collection of the available values:
// Returns an instance of Illuminate\Support\Collection Language::collect();
Return keys
The allValues
and collect
method will accept a boolean argument to return the keys/constant names:
$values = Language::allValues(true); // Returns [ 'PHP' => 'php', 'JAVASCRIPT' => 'js', 'CSS' => 'css', 'GO' => 'go', ]
Change log
Please see CHANGELOG for more information on what has changed recently.
Testing
$ phpunit test
Contributing
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
Security
If you discover any security related issues, please email davidianbonner@gmail.com instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.