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

Dms Filter Laravel Package

dms/dms-filter

Filter and sanitize object properties via PHP attributes. Annotate fields with rules like Trim, StripTags, and StripNewlines, then run a Filter service to clean entity values automatically—ideal alongside Symfony Validator and for consistent input normalization.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require dms/dms-filter
    
  2. Basic Entity Filtering: Define filters using annotations (PHP 8 attributes) on your entity properties:
    use DMS\Filter\Rules as Filter;
    
    class User {
        #[Filter\Trim]
        public string $name;
    }
    
  3. First Use Case: Apply filters via the FilterService:
    $filterService = new \DMS\Filter\FilterService();
    $user = new User();
    $user->name = "  <script>alert('xss')</script>  ";
    $filtered = $filterService->filter($user);
    // Output: "alert('xss')" (stripped of whitespace and HTML tags if using StripTags)
    

Where to Look First

  • README.md for core concepts and examples.
  • Tests for edge cases and real-world usage patterns.
  • Rules to explore available filters (e.g., StripTags, Trim, Sanitize).

Implementation Patterns

Common Workflows

  1. Input Sanitization:

    #[Filter\StripTags]
    #[Filter\Sanitize]
    public string $bio;
    
    • Useful for user-generated content (e.g., blog posts, comments).
  2. Data Normalization:

    #[Filter\Trim]
    #[Filter\Lowercase]
    public string $username;
    
    • Ensures consistent data formats (e.g., usernames, slugs).
  3. Conditional Filtering: Dynamically apply filters based on context:

    $filterService = new FilterService();
    $filters = [
        'name' => [new \DMS\Filter\Rules\Trim(), new \DMS\Filter\Rules\StripTags()],
        'email' => [new \DMS\Filter\Rules\Sanitize()]
    ];
    $filtered = $filterService->filter($user, $filters);
    

Integration Tips

  • Laravel Request Filtering: Bind the FilterService to a service provider and inject it into controllers:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->bind(\DMS\Filter\FilterService::class, function ($app) {
            return new \DMS\Filter\FilterService();
        });
    }
    

    Then use it in controllers:

    public function store(Request $request) {
        $user = new User();
        $user->name = $request->input('name');
        $filteredUser = app(\DMS\Filter\FilterService::class)->filter($user);
    }
    
  • Form Request Validation + Filtering: Combine with Laravel’s FormRequest for validation + filtering:

    public function rules() {
        return ['name' => 'required|string'];
    }
    
    public function withValidator($validator) {
        $validator->after(function ($validator) {
            $filtered = app(\DMS\Filter\FilterService::class)->filter($this);
            $this->merge($filtered);
        });
    }
    
  • API Response Filtering: Filter sensitive data before JSON serialization:

    $response = response()->json($filterService->filter($user));
    
  • Batch Processing: Filter collections of entities:

    $users = User::all();
    $filteredUsers = collect($users)->map(function ($user) {
        return $filterService->filter($user);
    });
    

Gotchas and Tips

Pitfalls

  1. Attribute Loading Issues:

    • If filters aren’t applied, ensure your PHP version supports attributes (PHP 8+).
    • For PHP 7.x, use the legacy annotation syntax (e.g., @Filter\Trim).
  2. Performance Overhead:

    • Avoid over-filtering large datasets. Cache filtered results if reused:
      $cacheKey = 'filtered_user_' . $user->id;
      $filtered = cache()->remember($cacheKey, now()->addHours(1), function () use ($user) {
          return $filterService->filter($user);
      });
      
  3. Custom Rules Conflicts:

    • If extending the package, ensure your custom rules don’t clash with existing ones. Prefix namespaces:
      namespace App\Filters;
      class CustomRule extends \DMS\Filter\Rules\AbstractRule { ... }
      
  4. Recursive Filtering:

    • By default, the package doesn’t recursively filter nested objects. Use FilterService::filterRecursive() for deep filtering:
      $filterService->filterRecursive($user);
      

Debugging

  • Verify Filters Are Applied: Check if annotations are parsed correctly by inspecting the FilterService internals or enabling debug mode:

    $filterService->setDebug(true); // Logs applied filters
    
  • Handle Exceptions: Wrap filtering in try-catch blocks for edge cases (e.g., malformed data):

    try {
        $filtered = $filterService->filter($user);
    } catch (\DMS\Filter\Exception\FilterException $e) {
        Log::error($e->getMessage());
        $filtered = $user; // Fallback
    }
    

Configuration Quirks

  1. Custom Filter Rules: Register custom rules via the FilterService:

    $filterService->addRule('custom_rule', new \App\Filters\CustomRule());
    
  2. Disable Specific Filters: Override default filters for specific properties:

    $filters = [
        'name' => [new \DMS\Filter\Rules\Trim()] // Exclude StripTags
    ];
    $filterService->filter($user, $filters);
    
  3. Attribute Reflection: If using legacy annotations (PHP < 8), ensure the dms/annotation package is installed:

    composer require dms/annotation
    

Extension Points

  1. Create Custom Rules: Extend AbstractRule to build domain-specific filters:

    namespace App\Filters;
    
    use DMS\Filter\Rules\AbstractRule;
    
    class Slugify extends AbstractRule {
        public function apply($value) {
            return Str::slug($value);
        }
    }
    
  2. Modify Filter Order: Use setRuleOrder() to prioritize rules:

    $filterService->setRuleOrder([
        \DMS\Filter\Rules\Trim::class,
        \DMS\Filter\Rules\StripTags::class
    ]);
    
  3. Integrate with Laravel Events: Trigger filtering on model events (e.g., saving):

    // app/Models/User.php
    protected static function boot() {
        static::saving(function ($user) {
            $user->setAttributes(app(\DMS\Filter\FilterService::class)->filter($user));
        });
    }
    
  4. Conditional Filtering Logic: Use closures for dynamic rules:

    $filterService->addRule('conditional', function ($value, $property) {
        return $property === 'email' ? strtolower($value) : $value;
    });
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor