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

Htmlpurifier Bundle Laravel Package

exercise/htmlpurifier-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require exercise/htmlpurifier-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Exercise\HTMLPurifierBundle\ExerciseHTMLPurifierBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Inject the purifier service into a controller or service:

    use Exercise\HTMLPurifierBundle\HTMLPurifier;
    
    class MyController extends AbstractController
    {
        public function __construct(private HTMLPurifier $purifier) {}
    
        public function sanitize(Request $request)
        {
            $dirtyHtml = $request->request->get('content');
            $cleanHtml = $this->purifier->purify($dirtyHtml);
            return new Response($cleanHtml);
        }
    }
    
  3. Basic Configuration: Override defaults in config/packages/exercise_html_purifier.yaml:

    exercise_html_purifier:
        default_cache_serializer_path: '%kernel.project_dir%/var/cache/htmlpurifier'
        default_cache_serializer_permissions: 493
    

Implementation Patterns

Core Workflows

  1. Sanitizing User Input:

    // Controller/Service
    $purified = $this->purifier->purify($userInput, 'custom_profile');
    
    • Use named profiles (e.g., custom_profile) for different sanitization rules.
  2. Dynamic Profile Switching:

    # config/packages/exercise_html_purifier.yaml
    exercise_html_purifier:
        profiles:
            admin_panel:
                HTML.Allowed: 'p[style],strong,em,a[href|title],ul,ol,li'
                HTML.TargetBlank: true
            public_content:
                HTML.Allowed: 'p,br,strong,em,a[href],img[src|alt]'
    
    $this->purifier->purify($html, 'admin_panel');
    
  3. Integration with Forms:

    • Use with Symfony’s DataTransformer to auto-sanitize form submissions:
    use Exercise\HTMLPurifierBundle\HTMLPurifier;
    
    class HtmlSanitizerTransformer implements DataTransformerInterface
    {
        public function __construct(private HTMLPurifier $purifier) {}
    
        public function transform($value): ?string
        {
            return $this->purifier->purify($value);
        }
    
        public function reverseTransform($value): string
        {
            return $value; // No reverse transform needed
        }
    }
    
  4. Twig Integration:

    {{ user_content|purify('public_content') }}
    

    Add to twig.yaml:

    twig:
        filters:
            purify: Exercise\HTMLPurifierBundle\Twig\PurifyFilter
    
  5. Batch Processing:

    $purifier = $this->purifier->getPurifier('default');
    $batch = ['<script>alert(1)</script>', '<b>Safe</b>'];
    array_walk($batch, fn(&$item) => $item = $purifier->purify($item));
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Caching is enabled by default (default_cache_serializer_path). Monitor cache growth in production.
    • Fix: Adjust default_cache_serializer_permissions if filesystem permissions cause issues (e.g., 493 for 0755).
  2. Profile Inheritance:

    • Custom profiles inherit from default. Override explicitly:
    profiles:
        strict:
            HTML.Allowed: 'p,br'  # Overrides default's allowed tags
            HTML.TargetBlank: false  # Disables target="_blank"
    
  3. XSS Edge Cases:

    • HTMLPurifier may not catch all XSS vectors (e.g., SVG, JavaScript URIs). Test with:
    $this->purifier->purify('<svg onload=alert(1)>', 'strict');
    
    • Tip: Combine with Symfony’s SecurityContext for additional checks.
  4. Configuration Validation:

    • Invalid YAML (e.g., typos in HTML.Allowed) throws silent failures. Validate with:
    php bin/console debug:config exercise_html_purifier
    
  5. Dependency Conflicts:

    • Avoid mixing with other sanitizers (e.g., white-october/pagerfanta-bundle). HTMLPurifier is not a replacement for CSRF protection.

Debugging

  1. Log Purified Output:

    $this->purifier->purify($html, 'debug', [
        'HTMLPurifier.Logging' => true,
        'HTMLPurifier.Logger' => new \Exercise\HTMLPurifierBundle\Logger\MonologLogger($this->logger),
    ]);
    
  2. Inspect Cache:

    • Check var/cache/htmlpurifier/ for corrupted cache files (delete and regenerate if needed).
  3. Profile Testing:

    • Use the HTMLPurifier_ConfigSchema to validate profiles:
    $config = $this->purifier->getConfig('custom_profile');
    $config->validate();
    

Extension Points

  1. Custom Profiles via Code:

    $this->purifier->addProfile('dynamic_profile', [
        'HTML.Allowed' => 'div[class],span',
        'Attr.AllowedFrame' => ['src'],
    ]);
    
  2. Event Listeners:

    • Subscribe to exercise.htmlpurifier.purify events to log/transform input:
    // src/EventListener/PurifierListener.php
    public function onPurify(PurifyEvent $event) {
        $event->setHtml(str_replace('&', '&amp;', $event->getHtml()));
    }
    

    Register in services.yaml:

    services:
        App\EventListener\PurifierListener:
            tags:
                - { name: 'kernel.event_listener', event: 'exercise.htmlpurifier.purify' }
    
  3. Override Default Config:

    • Extend the base config class:
    use Exercise\HTMLPurifierBundle\DependencyInjection\Configuration;
    
    class CustomConfiguration extends Configuration
    {
        public function getKey() { return 'custom_htmlpurifier'; }
        // Add custom parameters
    }
    

    Update Resources/config/services.yaml to point to your config class.

  4. Performance Tuning:

    • Disable caching for non-critical paths:
    exercise_html_purifier:
        profiles:
            no_cache:
                Cache.SerializerPath: null
    
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope