yokai/enum-bundle

Simple enumeration system with Symfony integration

Installs: 35 831

Dependents: 0

Suggesters: 0

Security: 0

Stars: 9

Watchers: 4

Forks: 3

Open Issues: 2

Type:symfony-bundle

v3.0.0-alpha.2 2020-06-26 12:12 UTC

README

Latest Stable Version Latest Unstable Version Total Downloads License

This repository aims to provide simple enumeration implementation to Symfony.

Installation

Add the bundle as a dependency with Composer

$ composer require yokai/enum-bundle

Enable the bundle in the kernel

<?php
return [
    Yokai\EnumBundle\YokaiEnumBundle::class => ['all' => true],
];

Usage

Let's take an example : our application has some members and each member has a gender which can be "male" (m) or "female" (f).

We first need to create the classes that will handle our enums :

<?php

declare(strict_types=1);

namespace App\Enum;

use Yokai\EnumBundle\EnumInterface;
use Yokai\EnumBundle\EnumWithClassAsNameTrait;

class GenderEnum implements EnumInterface
{
    use EnumWithClassAsNameTrait;

    public function getChoices(): array
    {
        return ['m' => 'Male', 'f' => 'Female'];
    }
}

If you are using PSR-4 service discovery (or Symfony default services file), then your service is already registered.

That's it, now the bundle know your enum services. You can start using it.

Add validation to any model :

<?php

declare(strict_types=1);

namespace App\Model;

use App\Enum\GenderEnum;
use Yokai\EnumBundle\Validator\Constraints\Enum;

class Member
{
    /**
     * @Enum(GenderEnum::class)
     */
    public ?string $gender = null;
}

Add enumerated form fields to any form :

<?php

declare(strict_types=1);

namespace App\Form\Type;

use App\Model\Member;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class MemberType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            // The bundle will find out the form type for you (thanks to the Enum constraint we added to model)
            ->add('gender')
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefault('data_class', Member::class);
    }
}

Display label of any enum value within a Twig template :

{{ value|enum_label('App\\Enum\\GenderEnum') }}

Recipes

MIT License

License can be found here.

Authors

The bundle was originally created by Yann Eugoné. See the list of contributors.

Thank's to Prestaconcept for supporting this bundle.