Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Enum Property Bundle Laravel Package

adrenalinkin/enum-property-bundle

Symfony bundle integrating EnumMapper: adds Twig filters/functions to convert enum DB values to human labels and back, fetch full enum maps, and provides validation support for enum properties. Install via Composer and enable the bundle in AppKernel.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require adrenalinkin/enum-property-bundle
    

    Ensure your project uses Symfony 4+ (or 3.x with AppKernel.php).

  2. Enable the Bundle Add to config/bundles.php (Symfony 4+) or app/AppKernel.php (Symfony 3):

    Linkin\Bundle\EnumPropertyBundle\LinkinEnumPropertyBundle::class => ['all' => true],
    
  3. First Use Case Create a custom AbstractEnumMapper (e.g., src/Mapper/GenderMapper.php):

    namespace App\Mapper;
    
    use Linkin\Component\EnumMapper\Mapper\AbstractEnumMapper;
    
    class GenderMapper extends AbstractEnumMapper
    {
        const DB_UNDEFINED = 0;
        const DB_MALE = 1;
        const DB_FEMALE = 2;
    
        protected function getEnumMap(): array
        {
            return [
                self::DB_UNDEFINED => 'undefined',
                self::DB_MALE => 'male',
                self::DB_FEMALE => 'female',
            ];
        }
    }
    
  4. Register the Mapper Add to services.yaml:

    services:
        App\Mapper\GenderMapper:
            tags: ['linkin.enum_mapper']
    
  5. Use in Twig

    {{ dump(app.enum_mapper('App\Mapper\GenderMapper').map(1)) }}  {# Outputs: "male" #}
    

Implementation Patterns

Core Workflows

  1. Form Integration Use the EnumType form field for enum-backed properties:

    use Linkin\Bundle\EnumPropertyBundle\Form\Type\EnumType;
    
    $builder->add('gender', EnumType::class, [
        'mapper' => 'App\Mapper\GenderMapper',
        'choices_as_values' => true,
    ]);
    
  2. Validation Leverage the Enum constraint:

    use Linkin\Bundle\EnumPropertyBundle\Validator\Constraints\Enum;
    
    /**
     * @Assert\Constraint(Enum::class, mapper="App\Mapper\GenderMapper")
     */
    private $gender;
    
  3. Twig Filters Map values directly in templates:

    {{ 1 | enum_map('App\Mapper\GenderMapper') }}  {# "male" #}
    {{ 'male' | enum_unmap('App\Mapper\GenderMapper') }}  {# 1 #}
    
  4. Dependency Injection Inject the EnumMapperRegistry service for dynamic mapping:

    use Linkin\Component\EnumMapper\Registry\EnumMapperRegistry;
    
    public function __construct(private EnumMapperRegistry $registry) {}
    
    public function resolveGender(int $value): string {
        return $this->registry->get('App\Mapper\GenderMapper')->map($value);
    }
    

Integration Tips

  • Autowiring: Tag mappers with linkin.enum_mapper to auto-register them.
  • Configuration: Override default mapper paths in config/packages/linkin_enum_property.yaml:
    linkin_enum_property:
        mapper_paths: ['%kernel.project_dir%/src/Mapper']
    
  • Doctrine: Use EnumType in entities for database storage:
    use Linkin\Bundle\EnumPropertyBundle\Doctrine\Types\EnumType;
    
    /**
     * @ORM\Column(type="enum")
     */
    private $gender;
    

Gotchas and Tips

Pitfalls

  1. Mapper Registration

    • Issue: Mappers not found if not tagged or manually registered.
    • Fix: Ensure linkin.enum_mapper tag is applied or use EnumMapperRegistry::add().
  2. Circular Dependencies

    • Issue: Twig filters may fail if mappers depend on services not yet initialized.
    • Fix: Use lazy-loading or prioritize mapper registration in Kernel::boot().
  3. Case Sensitivity

    • Issue: enum_unmap() fails if enum keys differ in case (e.g., 'Male' vs 'male').
    • Fix: Normalize keys in getEnumMap():
      return array_change_key_case($this->getRawEnumMap(), CASE_LOWER);
      
  4. Doctrine Migrations

    • Issue: EnumType may not generate correct SQL for legacy databases.
    • Fix: Use raw SQL or extend EnumType for custom DDL.

Debugging

  • Check Registered Mappers:
    $this->registry->getAll();  // Debug available mappers
    
  • Twig Errors: Clear cache (php bin/console cache:clear) if filters fail post-install.
  • Validation: Use validator:validate to test constraints:
    php bin/console validator:validate App\Entity\User gender
    

Extension Points

  1. Custom Mappers Extend AbstractEnumMapper for complex logic:

    class StatusMapper extends AbstractEnumMapper {
        protected function getEnumMap(): array {
            return [
                self::DB_PENDING => new Status('pending', 'Pending Review'),
                // Use objects for rich data
            ];
        }
    }
    
  2. Override Twig Filters Extend the bundle’s TwigExtension to add custom filters:

    use Linkin\Bundle\EnumPropertyBundle\Twig\EnumPropertyExtension;
    
    class CustomEnumExtension extends EnumPropertyExtension {
        public function getFilters() {
            return array_merge(parent::getFilters(), [
                new \Twig\TwigFilter('custom_map', [$this, 'customMap']),
            ]);
        }
    }
    
  3. Validator Extensions Add custom validation logic:

    use Linkin\Bundle\EnumPropertyBundle\Validator\Constraints\Enum;
    
    class CustomEnum extends Enum {
        public function validatedBy() {
            return static::class . 'Validator';
        }
    }
    
  4. Performance

    • Cache mapper instances if used frequently:
      services:
          App\Mapper\GenderMapper:
              tags: ['linkin.enum_mapper']
              public: false
              synthetic: true
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php