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

Filter Bundle Laravel Package

bukashk0zzz/filter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bukashk0zzz/filter-bundle
    

    For Symfony Flex projects, ensure allow-contrib is enabled:

    composer config extra.symfony.allow-contrib true
    

    Register the bundle in config/bundles.php (Symfony 4.3+):

    Bukashk0zzz\FilterBundle\FilterBundle::class => ['all' => true],
    
  2. First Use Case: Filtering an Entity Annotate a property in your entity (e.g., User.php) with @Filter:

    use Bukashk0zzz\FilterBundle\Annotation\Filter;
    
    /**
     * @Filter("StringTrim")
     */
    private $name;
    

    Inject the filter_service into a controller/service:

    use Bukashk0zzz\FilterBundle\Service\FilterService;
    
    public function __construct(private FilterService $filterService) {}
    
    public function applyFilter(User $user): void
    {
        $this->filterService->filter($user);
    }
    
  3. Key Configuration Enable form auto-filtering in config/packages/bukashk0zzz_filter.yaml:

    bukashk0zzz_filter:
        auto_filter_forms: true
    

Implementation Patterns

Core Workflows

  1. Entity Filtering

    • Dynamic Filtering: Use the filter() method to apply filters to entities:
      $filteredEntity = $this->filterService->filter($entity);
      
    • Bulk Filtering: Pass an array of entities:
      $filteredEntities = $this->filterService->filter($entities);
      
  2. Form Integration

    • Auto-Filtering: Enable auto_filter_forms to filter entities before validation (e.g., trimming whitespace from form data).
    • Manual Filtering: Filter form data explicitly:
      $formData = $this->filterService->filter($formData);
      $form->submit($formData);
      
  3. Custom Filters

    • Register Filters: Extend Laminas\Filter\FilterInterface and bind them in services:
      # config/services.yaml
      services:
          App\Filter\CustomFilter:
              tags: ['bukashk0zzz.filter.filter']
      
    • Use in Annotations:
      /**
       * @Filter("custom_filter_name")
       */
      private $customField;
      
  4. Conditional Filtering

    • Skip Filters: Use @Filter(skip=true) to disable filtering for a property:
      /**
       * @Filter("StringTrim", skip=true)
       */
      private $skipTrimming;
      
    • Conditional Logic: Implement Bukashk0zzz\FilterBundle\Filter\ConditionalFilterInterface for dynamic rules.

Integration Tips

  1. Event Listeners

    • Hook into kernel.request to filter input data globally:
      public function onKernelRequest(GetResponseEvent $event)
      {
          $request = $event->getRequest();
          $data = $request->request->all();
          $filteredData = $this->filterService->filter($data);
          $request->request->replace($filteredData);
      }
      
  2. Doctrine Integration

    • Filter entities before persisting:
      $entityManager->persist($this->filterService->filter($entity));
      
  3. API Requests

    • Filter DTOs or request payloads:
      $dto = $this->filterService->filter($request->getContent());
      
  4. Testing

    • Mock FilterService in tests to isolate filtering logic:
      $this->filterService->expects($this->once())
          ->method('filter')
          ->with($entity);
      

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Issue: Annotating every property may slow down filtering.
    • Fix: Use @Filter selectively or disable auto_filter_forms for non-critical forms.
  2. Circular References

    • Issue: Filtering entities with circular references (e.g., UserProfile) may cause infinite loops.
    • Fix: Use @Filter(skip=true) for circularly referenced properties or implement depth limits.
  3. Form Validation Conflicts

    • Issue: Filters may alter data in ways that conflict with validation rules (e.g., trimming a required field to empty).
    • Fix: Apply filters after validation or use @Assert\NotBlank with @Filter("StringTrim") cautiously.
  4. Filter Order

    • Issue: Filters are applied in the order they are defined in the annotation (no built-in priority system).
    • Fix: Group related filters (e.g., @Filter({"StringTrim", "StringToUpper"})).
  5. Deprecated Laminas Filters

    • Issue: Some ZendFilter names (e.g., Zend\Filter\StringTrim) may not work; use Laminas equivalents (e.g., StringTrim).
    • Fix: Check Laminas Filter docs for updated names.

Debugging Tips

  1. Enable Debug Mode

    • Set debug: true in config/packages/bukashk0zzz_filter.yaml to log filtered properties:
      bukashk0zzz_filter:
          debug: true
      
  2. Inspect Filtered Data

    • Use var_dump($this->filterService->getFilteredProperties($entity)) to see which properties were modified.
  3. Common Errors

    • FilterNotFoundException: Ensure the filter name matches a registered Laminas filter or a custom service tagged with bukashk0zzz.filter.filter.
    • InvalidArgumentException: Verify the annotated property exists in the entity class.

Extension Points

  1. Custom Filter Providers

    • Implement Bukashk0zzz\FilterBundle\Filter\FilterProviderInterface to dynamically register filters based on runtime conditions.
  2. Annotation Overrides

    • Override annotations via configuration:
      bukashk0zzz_filter:
          overrides:
              App\Entity\User:
                  name: ["StringTrim", "StringToUpper"]
      
  3. Event-Driven Filtering

    • Dispatch events before/after filtering:
      $this->filterService->filter($entity, new FilterEvent($entity));
      
  4. Batch Processing

    • Extend FilterService to support chunked filtering for large datasets:
      $this->filterService->filterBatch($entities, 100);
      
  5. Non-Entity Filtering

    • Use the filter() method with arrays or objects without annotations:
      $data = [
          'name' => '  Alice  ',
          'age' => '30',
      ];
      $filtered = $this->filterService->filter($data, [
          'name' => ['StringTrim'],
          'age' => ['Int'],
      ]);
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui