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 Laravel Package

joomla/filter

joomla/filter provides input and output filtering tools for PHP apps, helping sanitize content by allowing or blocking specific HTML tags and attributes. Includes OutputFilter helpers (e.g., URL-safe strings; optional Joomla\Language).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require joomla/filter "~3.0"
    

    For PHP 8.3+ projects, use ~4.0 instead.

  2. First Use Case: Sanitize user input in a Laravel controller or request handler:

    use Joomla\Filter\InputFilter;
    
    $cleanInput = InputFilter::clean(
        $userInput,
        InputFilter::ONLY_ALLOW_DEFINED_TAGS,
        ['p', 'b', 'i', 'a']
    );
    
  3. Where to Look First:


Implementation Patterns

Usage Patterns

  1. Request Sanitization Pipeline:

    // In a Laravel Form Request or middleware
    public function sanitize($input, array $allowedTags = ['p', 'a'])
    {
        return InputFilter::clean(
            $input,
            InputFilter::ONLY_ALLOW_DEFINED_TAGS,
            $allowedTags
        );
    }
    
  2. Service Provider Integration:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton('filter', function () {
            return new InputFilter();
        });
    }
    

    Inject via constructor:

    public function __construct(private InputFilter $filter) {}
    
  3. Dynamic Whitelists:

    // Allow tags based on user role
    $allowedTags = auth()->user()->role === 'admin' ? ['div', 'span'] : ['p', 'b'];
    $cleanHtml = $this->filter->clean($input, InputFilter::ONLY_ALLOW_DEFINED_TAGS, $allowedTags);
    
  4. Attribute-Level Control:

    // Allow only href in <a> tags
    $cleanHtml = InputFilter::clean(
        $input,
        InputFilter::ONLY_ALLOW_DEFINED_TAGS | InputFilter::ONLY_ALLOW_DEFINED_ATTRIBUTES,
        ['a'],
        ['href']
    );
    

Workflows

  1. Form Handling:

    • Use in validate() or sanitize() methods of Laravel Form Requests.
    • Example:
      public function rules()
      {
          return ['content' => 'required|string'];
      }
      
      public function sanitize($attribute, $value)
      {
          return InputFilter::clean($value, InputFilter::ONLY_ALLOW_DEFINED_TAGS, ['p', 'b']);
      }
      
  2. API Payloads:

    • Sanitize JSON inputs before processing:
      $data = json_decode($request->getContent(), true);
      $data['description'] = InputFilter::clean($data['description'], ...);
      
  3. CMS Content:

    • Integrate with Laravel Nova’s DetailPanel or custom fields:
      // Nova Field
      public function resolve($resource, $attribute)
      {
          return InputFilter::clean($resource->$attribute, ...);
      }
      

Integration Tips

  1. Laravel Validation Rules: Extend Laravel’s validation with custom rules:

    use Joomla\Filter\InputFilter;
    
    class Sanitize extends FormRequest
    {
        public function rules()
        {
            return ['bio' => ['required', new SanitizeRule(['p', 'a'])]];
        }
    }
    
    class SanitizeRule extends Rule
    {
        public function __construct(private array $allowedTags)
        {
            parent::__construct();
        }
    
        public function passes($attribute, $value)
        {
            return InputFilter::clean($value, InputFilter::ONLY_ALLOW_DEFINED_TAGS, $this->allowedTags) !== false;
        }
    }
    
  2. Blade Directives: Create a custom Blade directive for sanitized output:

    // app/Providers/BladeServiceProvider.php
    Blade::directive('sanitize', function ($expression) {
        return "<?php echo InputFilter::clean({$expression}, InputFilter::ONLY_ALLOW_DEFINED_TAGS, ['p', 'b']); ?>";
    });
    

    Usage:

    {!! sanitize($user->bio) !!}
    
  3. Event Listeners: Sanitize data on model events (e.g., saving):

    public function saving(Post $post)
    {
        $post->content = InputFilter::clean(
            $post->content,
            InputFilter::ONLY_ALLOW_DEFINED_TAGS,
            ['h1', 'p', 'ul', 'li']
        );
    }
    

Gotchas and Tips

Pitfalls

  1. PHP Version Mismatch:

    • v3.x: Requires PHP 8.1+.
    • v4.x: Requires PHP 8.3+.
    • Fix: Use ~3.0 for older Laravel projects (e.g., Laravel 9).
  2. False Positives in Sanitization:

    • Aggressive filtering may break legitimate HTML (e.g., <img src="..."> if src isn’t whitelisted).
    • Fix: Test with real-world HTML snippets (e.g., from TinyMCE or CKEditor outputs).
  3. Nested Tag Issues:

    • Older versions (<3.0.2) had case-sensitivity bugs in stripImages/stripIframes.
    • Fix: Upgrade to ~3.0.2 or later.
  4. Attribute Filtering Quirks:

    • ONLY_ALLOW_DEFINED_ATTRIBUTES can strip valid attributes if not configured carefully.
    • Fix: Explicitly whitelist attributes (e.g., ['href', 'title'] for <a> tags).
  5. Performance Overhead:

    • Heavy filtering (e.g., large HTML blocks) may slow down requests.
    • Fix: Cache sanitized results or use lazy loading for non-critical fields.

Debugging

  1. Unexpected Output:

    • Use InputFilter::clean() with InputFilter::RETURN_ERRORS flag to debug:
      $result = InputFilter::clean($input, InputFilter::RETURN_ERRORS, ['p']);
      if ($result === false) {
          dd(InputFilter::getErrors()); // Inspect why sanitization failed
      }
      
  2. XSS Evasion Bypasses:

    • Test with payloads like:
      <script>alert(1)</script>
      <img src=x onerror=alert(1)>
      <a href="javascript:alert(1)">Click</a>
      
    • Fix: Ensure ~4.0.1+ (removes common evasion chars) or manually add rules.
  3. Whitelist Misconfigurations:

    • Verify allowed tags/attributes with:
      $config = InputFilter::getConfig();
      dd($config->allowedTags, $config->allowedAttributes);
      

Config Quirks

  1. Static vs. Instance Methods:

    • Static methods (e.g., InputFilter::clean()) use global config.
    • Instance methods allow per-object customization:
      $filter = new InputFilter();
      $filter->setAllowedTags(['div', 'span']);
      $clean = $filter->clean($input);
      
  2. OutputFilter Dependencies:

    • OutputFilter::stringURLSafe() requires joomla/language package.
    • Fix: Install via Composer if needed:
      composer require joomla/language
      
  3. Legacy Constant Names:

    • Older code may use deprecated constants (e.g., TAGS_WHITELIST).
    • Fix: Update to new names (e.g., ONLY_ALLOW_DEFINED_TAGS).

Extension Points

  1. Custom Filters: Extend InputFilter to add domain-specific rules:

    class CustomFilter extends InputFilter
    {
        public function cleanCustom($input)
        {
            return $this->clean($input, InputFilter::ONLY_ALLOW_DEFINED_TAGS, ['custom']);
        }
    }
    
  2. Event-Driven Sanitization: Use Laravel events to trigger sanitization:

    // In a service provider
    event(new SanitizeEvent($input));
    

    Handle with a listener:

    public function handle(SanitizeEvent $event)
    {
        $event->setSanitized(InputFilter::clean($event->input, ...));
    }
    
  3. Testing Helpers: Create a test

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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata