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

Form Theme Bundle Laravel Package

elao/form-theme-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require elao/form-theme-bundle
    

    Enable the bundle in config/bundles.php (Symfony) or config/app.php (Laravel via Symfony bridge):

    Elao\FormThemeBundle\ElaoFormThemeBundle::class => ['all' => true],
    
  2. First Use Case Generate a theme key for a form in a controller or service:

    use Elao\FormThemeBundle\Generator\ThemeKeyGenerator;
    
    $generator = new ThemeKeyGenerator();
    $themeKey = $generator->generate('my_form_type', ['field1', 'field2']);
    // Output: e.g., `my_form_type_field1_field2`
    
  3. Where to Look First

    • Generator Class: src/Generator/ThemeKeyGenerator.php – Core logic for key generation.
    • Tests: tests/ – Example use cases and edge cases.
    • README: Focus on the generate() method signature and parameters.

Implementation Patterns

Workflows

  1. Dynamic Form Theming Use the generator to dynamically create theme keys for forms based on user input or runtime conditions:

    $fields = request()->input('selected_fields', []);
    $themeKey = $generator->generate('user_profile', $fields);
    
  2. Integration with Symfony Forms If using Symfony forms (via Laravel Bridge), attach the theme key to form options:

    $form = $formFactory->createBuilder('user_profile', UserType::class)
        ->add('name', TextType::class)
        ->getForm();
    $form->add('theme_key', HiddenType::class, [
        'data' => $generator->generate('user_profile', ['name']),
    ]);
    
  3. Caching Theme Keys Cache generated keys to avoid recomputation (e.g., in Laravel’s cache layer):

    $cacheKey = "theme_key_{$formType}_{" . implode('_', $fields)}";
    $themeKey = Cache::remember($cacheKey, 3600, function() use ($generator, $formType, $fields) {
        return $generator->generate($formType, $fields);
    });
    

Integration Tips

  • Laravel-Specific: Wrap the generator in a Laravel service provider for dependency injection:
    $this->app->singleton(ThemeKeyGenerator::class, function ($app) {
        return new ThemeKeyGenerator();
    });
    
  • Form Builder Abstraction: Create a trait or helper to standardize theme key generation across forms:
    trait UsesFormThemeKeys {
        protected function getThemeKey(string $formType, array $fields): string {
            return app(ThemeKeyGenerator::class)->generate($formType, $fields);
        }
    }
    
  • Validation: Validate theme keys in middleware or form events to ensure consistency:
    $themeKey = $request->input('theme_key');
    $expectedKey = $this->getThemeKey('order_form', ['items']);
    if ($themeKey !== $expectedKey) {
        throw new \InvalidArgumentException("Invalid theme key.");
    }
    

Gotchas and Tips

Pitfalls

  1. Key Collisions

    • Issue: If $fields contains duplicate values (e.g., ['name', 'name']), the generator may produce unexpected keys.
    • Fix: Normalize fields (e.g., array_unique($fields)) before passing to generate().
  2. Case Sensitivity

    • Issue: The generator is case-sensitive. ['Name', 'name'] may not behave as expected.
    • Fix: Standardize field names (e.g., strtolower()) if case insensitivity is required.
  3. Empty Fields

    • Issue: Passing an empty array ([]) may not yield a useful key.
    • Fix: Add a default field or handle empty cases:
      $fields = $fields ?: ['default_field'];
      
  4. Performance

    • Issue: Generating keys for large field arrays may impact performance.
    • Fix: Cache aggressively or precompute keys during form initialization.

Debugging

  • Log Generation: Add debug logs to verify key generation:
    \Log::debug('Generated theme key', ['key' => $themeKey, 'form_type' => $formType, 'fields' => $fields]);
    
  • Unit Tests: Write tests for edge cases (e.g., special characters in field names):
    $this->assertEquals(
        'form_type_field_with+symbol',
        $generator->generate('form_type', ['field_with+symbol'])
    );
    

Extension Points

  1. Custom Separators

    • Override the default underscore (_) separator by extending ThemeKeyGenerator:
      class CustomThemeKeyGenerator extends ThemeKeyGenerator {
          protected function getSeparator(): string {
              return '-';
          }
      }
      
  2. Field Transformers

    • Preprocess fields before generation (e.g., sanitize or truncate):
      $fields = array_map('sanitize_field', $fields);
      $themeKey = $generator->generate($formType, $fields);
      
  3. Symfony Event Listeners

    • Integrate with Symfony form events (e.g., PRE_SET_DATA) to auto-generate theme keys:
      $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
          $data = $event->getData();
          $themeKey = $generator->generate($event->getForm()->getConfig()->getType()->getName(), array_keys($data));
          $event->getForm()->add('theme_key', HiddenType::class, ['data' => $themeKey]);
      });
      

Config Quirks

  • No Configuration: The bundle has no configurable options out of the box. All behavior is hardcoded in ThemeKeyGenerator.
  • Laravel-Symfony Bridge: If using Laravel’s Symfony bridge, ensure the bundle is loaded after the bridge is initialized to avoid autowiring conflicts.
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware