, (*1)
php-enumeration
This small package can represent a enumeration field. For example in a database or an api., (*2)
Featureslist:
* inspired and mostly used for MySQL enum-fields or API enum-fields
* it is a simple string representation
* no other values are allow besides the defined in the class
* simple usage and easy to read
* no features a enum do not have to deal with
* with a default fallback value which will be used if no matching value exists in const“s
* you can harden this object by throwing an exception in the getDefault-method, (*3)
Install
Basic install via composer, (*4)
composer require freshp/php-enumeration
Usage
Take a look in tests/fixtures to see a executable example., (*5)
Create a new object with:
1. public const“s which represent strings
2. implement the getDefault-method, (*6)
Create an enumeration object
use FreshP\PhpEnumeration\Enum;
class EnumExample extends Enum
{
public const TEST_CONSTANT = 'constant';
public const TEST_DEFAULT = 'default';
protected function getDefault(): string
{
return self::TEST_DEFAULT;
}
}
use annotations for better ide support, (*7)
use FreshP\PhpEnumeration\Enum;
/**
* @method static self TEST_CONSTANT()
* @method static self TEST_DEFAULT()
*/
class EnumExample extends Enum
...
make the data of the parent toArray-method public if you need to iterate over all options, (*8)
class EnumExample extends Enum
{
...
public static function listAllOptions(): array
{
return self::toArray();
}
...
Use the enumeration object
-
create the object by static call, (*9)
$enum = EnumExample::TEST_CONSTANT();
-
create the object by normal initialization, (*10)
$enum = new EnumExample(EnumExample::TEST_CONSTANT);
-
create a default object (the value from the getDefault-method will be called), (*11)
$enum = new EnumExample();
-
compare the object by using the __toString-method, (*12)
$enum->__toString() === EnumExample::TEST_CONSTANT
or, (*13)
$enum->isEqual(EnumExample::TEST_CONSTANT())
Checks
Run each command in the project root directory., (*14)
run all check with composer script, (*15)
composer quickcheck
Execute PHPUnit tests
./vendor/bin/phpunit.phar --testdox
Execute fix PHPCS problems
./vendor/bin/phpcbf.phar
Execute PHPCS checks
./vendor/bin/phpcs.phar
Execute PHPSTAN checks
./vendor/bin/phpstan.phar analyse -l max ./src