PHP code example of elao / enum

1. Go to this page and download the library: Download elao/enum library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

elao / enum example snippets


#[ReadableEnum(prefix: 'suit.')]
enum Suit: string implements ReadableEnumInterface
{
    use ReadableEnumTrait;

    case Hearts = '♥︎';
    case Diamonds = '♦︎';
    case Clubs = '♣︎';
    case Spades = '︎♠︎';
}

namespace App\Enum;

use Elao\Enum\ReadableEnumInterface;
use Elao\Enum\ReadableEnumTrait;
use Elao\Enum\Attribute\EnumCase;

enum Suit: string implements ReadableEnumInterface
{
    use ReadableEnumTrait;

    #[EnumCase('suit.hearts')]
    case Hearts = '♥︎';

    #[EnumCase('suit.diamonds')]
    case Diamonds = '♦︎';

    #[EnumCase('suit.clubs')]
    case Clubs = '♣︎';

    #[EnumCase('suit.spades')]
    case Spades = '︎♠︎';
}

Suit::Hearts->getReadable(); // returns 'suit.hearts'

$enum = Suit::Hearts;
$translator->trans($enum->getReadable(), locale: 'fr'); // returns 'Coeurs'

#[ReadableEnum(prefix: 'suit.')]
enum Suit: string implements ReadableEnumInterface
{
    use ReadableEnumTrait;

    #[EnumCase('hearts︎')]
    case Hearts = '♥︎';
    case Diamonds = '♦︎';
    case Clubs = '♣︎';
    case Spades = '︎♠︎';
}

Suit::Hearts->getReadable(); // returns 'suit.hearts'
Suit::Clubs->getReadable(); // returns 'suit.Clubs'

#[ReadableEnum(prefix: 'suit.', useValueAsDefault: true)]
enum Suit: string implements ReadableEnumInterface
{
    use ReadableEnumTrait;

    case Hearts = 'hearts';
    case Diamonds = 'diamonds';
    case Clubs = 'clubs︎';
    case Spades = '︎spades';
}

Suit::Hearts->getReadable(); // returns 'suit.hearts'
Suit::Clubs->getReadable(); // returns 'suit.clubs'

namespace App\Enum;

use Elao\Enum\ReadableEnumInterface;
use Elao\Enum\ExtrasTrait;
use Elao\Enum\Attribute\EnumCase;

enum Suit implements ReadableEnumInterface
{
    use ExtrasTrait;

    #[EnumCase(extras: ['icon' => 'fa-heart', 'color' => 'red'])]
    case Hearts;

    #[EnumCase(extras: ['icon' => 'fa-diamond', 'color' => 'red'])]
    case Diamonds;

    #[EnumCase(extras: ['icon' => 'fa-club', 'color' => 'black'])]
    case Clubs;

    #[EnumCase(extras: ['icon' => 'fa-spade', 'color' => 'black'])]
    case Spades;
}

Suit::Hearts->getExtra('color'); // 'red'
Suit::Spades->getExtra('icon'); // 'fa-spade'
Suit::Spades->getExtra('missing-key'); // null
Suit::Spades->getExtra('missing-key', true); // throws

interface RenderableEnumInterface 
{
    public function getColor(): string;
    public function getIcon(): string;
}

use Elao\Enum\ExtrasTrait;

trait RenderableEnumTrait
{
    use ExtrasTrait;

    public function getColor(): string
    {
        $this->getExtra('color', true);
    }
    
    public function getIcon(): string
    {
        $this->getExtra('icon', true);
    }
}

use Elao\Enum\Attribute\EnumCase;

enum Suit implements RenderableEnumInterface
{
    use RenderableEnumTrait;

    #[EnumCase(extras: ['icon' => 'fa-heart', 'color' => 'red'])]
    case Hearts;
    
    // […]
}

Suit::Hearts->getColor(); // 'red'

namespace App\Enum;

enum Permissions: int
{
    case Execute = 1 << 0;
    case Write = 1 << 1;
    case Read = 1 << 2;
}

use App\Enum\Permissions;
use Elao\Enum\FlagBag;

$permissions = FlagBag::from(Permissions::Execute, Permissions::Write, Permissions::Read);
// same as:
$permissions = new FlagBag(Permissions::class, 7); 
// where 7 is the "encoded" bits value for:
Permissions::Execute->value | Permissions::Write->value | Permissions::Read->value // 7
// or initiate a bag with all its possible values using:
$permissions = FlagBag::fromAll(Permissions::class);

$permissions = $permissions->withoutFlags(Permissions::Execute); // Returns an instance without "execute" flag

$permissions->getValue(); // Returns 6, i.e: the encoded bits value
$permissions->getBits(); // Returns [2, 4], i.e: the decoded bits
$permissions->getFlags(); // Returns [Permissions::Write, Permissions::Read]

$permissions = $permissions->withoutFlags(Permissions::Read, Permissions::Write); // Returns an instance without "read" and "write" flags
$permissions->getBits(); // Returns []
$permissions->getFlags(); // Returns []

$permissions = new FlagBag(Permissions::class, FlagBag::NONE); // Returns an empty bag

$permissions = $permissions->withFlags(Permissions::Read, Permissions::Execute); // Returns an instance with "read" and "execute" flags

$permissions->hasFlags(Permissions::Read); // True
$permissions->hasFlags(Permissions::Read, Permissions::Execute); // True
$permissions->hasFlags(Permissions::Write); // False

namespace App\Form\Type;

use App\Enum\Suit;
use Symfony\Component\Form\AbstractType;
use Elao\Enum\Bridge\Symfony\Form\Type\EnumType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;

class CardType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('suit', EnumType::class, [
                'class' => Suit::class, 
                'expanded' => true,
            ])
        ;
    }

    // ...
}

namespace App\Form\Type;

use App\Enum\Permissions;
use Symfony\Component\Form\AbstractType;
use Elao\Enum\Bridge\Symfony\Form\Type\FlagBagType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;

class AuthenticationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('permission', FlagBagType::class, [
                'class' => Permissions::class, 
            ])
        ;
    }

    // ...
}

class CardController
{
    #[Route('/cards/{suit}')]
    public function list(Suit $suit): Response
    {
        // [...]
    }
}

use Elao\Enum\Bridge\Symfony\HttpKernel\Controller\ArgumentResolver\Attributes\BackedEnumFromQuery;

class DefaultController
{
    #[Route('/cards')]
    public function list(
        #[BackedEnumFromQuery]
        ?Suit $suit = null,
    ): Response
    {
        // [...]
    }
}

use Elao\Enum\Bridge\Symfony\HttpKernel\Controller\ArgumentResolver\Attributes\BackedEnumFromQuery;

class DefaultController
{
    #[Route('/cards')]
    public function list(
        #[BackedEnumFromQuery]
        ?Suit ...$suits = null,
    ): Response
    {
        // [...]
    }
}

public function trans(TranslatorInterface $translator, string $locale = null): string
{
    return $translator->trans($this->getReadable(), [], $locale);
}

use Elao\Enum\Bridge\Symfony\Translation\TranslatableEnumInterface;
use Elao\Enum\Bridge\Symfony\Translation\TranslatableEnumTrait;

enum Card: string implements TranslatableEnumInterface
{
    use TranslatableEnumTrait;
    
    #[EnumCase('suit.hearts')]
    case Hearts = '♥︎';    
    // ...
}

$translated = Card::Hearts->trans($this->translator)

#[Entity]
class Card
{
    #[Column(type: 'string', enumType: Suit::class)]
    public $suit;
}

namespace App\Doctrine\DBAL\Type;

use Elao\Enum\Bridge\Doctrine\DBAL\Types\AbstractEnumType;
use App\Enum\Suit;

class SuitType extends AbstractEnumType
{
    protected function getEnumClass(): string
    {
        return Suit::class; // By default, the enum FQCN is used as the DBAL type name as well
    }
}

use App\Doctrine\DBAL\Type\SuitType;
use Doctrine\DBAL\Types\Type;

Type::addType(Suit::class, SuitType::class);

$conn = $em->getConnection();
$conn->getDatabasePlatform()->registerDoctrineTypeMapping(Suit::class, SuitType::class);

use App\Enum\Suit;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class Card
{
    #[ORM\Column(Suit::class, nullable: false)]
    private Suit $field;
}

#[ORM\Entity]
class Card
{
    #[ORM\Column(Suit::class, nullable: true)
    protected ?Suit $suit = null;
}

private function findByType(?Suit $suit = null): array 
{
    $qb = $em->createQueryBuilder()
      ->select('c')
      ->from('Card', 'c')
      ->where('c.suit = :suit');
      
    // use a value from constants:
    $qb->setParameter('param1', Suit::SPADES->value);
    
    // or from instances:
    $qb->setParameter('suit', $suit->value);  
    // Use the 3rd parameter to set the DBAL type
    $qb->setParameter('suit', $suit, Suit::class);
    
    // […]
}   

namespace App\Doctrine\ODM\Type;

use Elao\Enum\Bridge\Doctrine\ODM\Types\AbstractEnumType;
use App\Enum\Suit;

class SuitType extends AbstractEnumType
{
    protected function getEnumClass(): string
    {
        return Suit::class; // By default, the enum FQCN is used as the DBAL type name as well
    }
}

use App\Doctrine\ODM\Type\SuitType;
use Doctrine\ODM\MongoDB\Types\Type;

Type::addType(Suit::class, SuitType::class);

use App\Enum\Suit;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

#[MongoDB\Document]
class Card
{
    #[MongoDB\Field(Suit::class)]
    private Suit $field;
}

use \Elao\Enum\Bridge\Faker\Provider\EnumProvider;
 
$faker = new Faker\Generator();
$faker->addProvider(new EnumProvider());

$faker->randomEnum(Suit::class) // Select one of the Suit cases, e.g: `Suit::Hearts`
$faker->randomEnums(Suit::class, 2, min: 1) // Select between 1 and 2 enums cases, e.g: `[Suit::Hearts, Suit::Spades]`
$faker->randomEnums(Suit::class, 3, exact: true) // Select exactly 3 enums cases

new EnumProvider([
    'Civility' => App\Enum\Civility::class,
    'Suit' => App\Enum\Suit::class,
]);

return [
    MyEntity::class => [
        'entity1' => [
            'civility' => Civility::MISTER // Select a specific case, using PHP directly
            'suit' => '<randomEnum(App\Enum\Suit)>' // Select a random case
            'suit' => '<randomEnum(Suit)>' // Select a random case, using the FQCN alias
            'permissions' => '<randomEnums(Permissions, 3, false, 1)>' // Select between 1 and 2 enums cases
            'permissions' => '<randomEnums(Permissions, 3, true)>' // Select exactly 3 enums cases
        ]
    ]
]