freshp/php-enumeration

This small package can represent a enumeration field. For example in a database or an api.

4.0.0 2021-08-11 12:10 UTC

This package is auto-updated.

Last update: 2024-03-25 14:36:11 UTC


README

Build Status Software License Latest Stable Version Total Downloads

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

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:

  1. public const´s which represent strings
  2. 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

  1. create the object by static call

    $enum = EnumExample::TEST_CONSTANT();
  2. create the object by normal initialization

    $enum = new EnumExample(EnumExample::TEST_CONSTANT);
  3. create a default object (the value from the getDefault-method will be called)

    $enum = new EnumExample();
  4. 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