freshp / php-enumeration
This small package can represent a enumeration field. For example in a database or an api.
Installs: 30 189
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: ^7.4|^8.0
Requires (Dev)
- tm/tooly-composer-script: ^1.4
README
php-enumeration
This small package can represent a enumeration field. For example in a database or an api.
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
- you can harden this object by throwing an exception in the
Install
Basic install via composer
composer require freshp/php-enumeration
Usage
Take a look in tests/fixtures
to see a executable example.
Create a new object with:
- public const´s which represent strings
- implement the
getDefault
-method
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
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
class EnumExample extends Enum { ... public static function listAllOptions(): array { return self::toArray(); } ...
Use the enumeration object
-
create the object by static call
$enum = EnumExample::TEST_CONSTANT();
-
create the object by normal initialization
$enum = new EnumExample(EnumExample::TEST_CONSTANT);
-
create a default object (the value from the
getDefault
-method will be called)$enum = new EnumExample();
-
compare the object by using the
__toString
-method$enum->__toString() === EnumExample::TEST_CONSTANT
or
$enum->isEqual(EnumExample::TEST_CONSTANT())
Checks
Run each command in the project root directory.
run all check with composer script
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