PHP code example of everlutionsk / enum-bundle

1. Go to this page and download the library: Download everlutionsk/enum-bundle 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/ */

    

everlutionsk / enum-bundle example snippets


$bundles = [
    new Everlution\EnumBundle\EnumBundle(),
]


// always use final
final class Gender extends Enum
{
    const MALE = 1;
    const FEMALE = 2;
    const OTHER = 3;
    public static function getChoices(): array
    {
        // 'string represtation' => self::constant
        return [
            'gender.male' => self::MALE,
            'gender.female' => self::FEMALE,
            'gender.other' => self::OTHER,
        ];
    }

    // following is optional
    public function isMale(): bool
    {
        return $this->isValue(self::MALE);
    }

    public function isFemale(): bool
    {
        return $this->isValue(self::FEMALE);
    }
}


$male = new Gender(Gender::MALE);
var_dump($male->isMale()); // bool(true)
var_dump($male->isSameAs(new Gender(Gender::FEMALE))); // bool(false)
var_dump($male->isValue(Gender::FEMALE)); // bool(false)
echo $male->getValue(); // Gender::MALE
echo $male->getLabel(); // 'gender.male'
echo $male; // 'gender.male' (has __toString() implemented)


/**
 * Class EnumDBMap.
 *
 * @author Richard Popelis <[email protected]>
 */
class EnumDBMap implements EnumDBMapInterface
{
    public function getMap(): array
    {
        return [
            'enum_gender' => Gender::class,
            // 'enum_visibility' => Visibility::class, // and so on
        ];
    }
}

class User
{
    /**
     * @var Gender
     * @ORM\Column(type="enum_gender")
     */
    private $gender;

    /**
     * @return Gender
     */
    public function getGender(): ?Gender
    {
        return $this->gender;
    }

    /**
     * @param Gender $gender
     * @return User
     */
    public function setGender(?Gender $gender): self
    {
        $this->gender = $gender;

        return $this;
    }
}

## usage
$user = new User;
$user->setGender(new Gender(Gender::MALE));

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('gender', EnumChoiceType::class, [
            'enum_class' => Gender::class,
            // optional blacklisting: remove OTHER from form field choices
            'enum_blacklist' => [Gender::OTHER],
            // optional whitelisting: show only specified values
            'enum_whitelist' => [Gender::MALE, Gender::FEMALE],
        ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}