Weave 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

Clamav Validator Laravel Package

sunspikes/clamav-validator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sunspikes/clamav-validator
    

    Publish the config file:

    php artisan vendor:publish --provider="Sunspikes\ClamavValidator\ClamavValidatorServiceProvider" --tag="config"
    
  2. First Use Case: Validate a file upload in a Laravel controller or form request:

    use Sunspikes\ClamavValidator\Rules\ClamavScan;
    
    $request->validate([
        'file' => ['required', 'file', new ClamavScan],
    ]);
    
  3. Where to Look First:

    • Check config/clamav-validator.php for default settings (e.g., timeout, max_file_size).
    • Review app/Rules/ClamavScan.php (if extended) or the package’s Rules\ClamavScan for customization hooks.

Implementation Patterns

Core Workflows

  1. Basic File Validation:

    $request->validate([
        'avatar' => ['required', 'image', 'mimes:jpeg,png', new ClamavScan],
    ]);
    
    • Automatically scans uploaded files for viruses before processing.
  2. Customizing Scan Behavior:

    • Timeout: Adjust in config ('timeout' => 10).
    • Max File Size: Limit scanable files ('max_file_size' => 10240 for 10MB).
    • Excluded Extensions: Skip scans for specific file types:
      $request->validate([
          'file' => [new ClamavScan(['exclude_extensions' => ['pdf', 'docx']])],
      ]);
      
  3. Integration with Form Requests:

    use Sunspikes\ClamavValidator\Rules\ClamavScan;
    
    public function rules()
    {
        return [
            'resume' => ['required', 'file', new ClamavScan(['on_failure' => 'skip'])],
        ];
    }
    
    public function messages()
    {
        return [
            'resume.clamav' => 'The file contains a virus and cannot be processed.',
        ];
    }
    
  4. Manual Scanning (Advanced): Use the underlying ClamavScanner service directly:

    use Sunspikes\ClamavValidator\Facades\ClamavScanner;
    
    $path = $request->file('file')->store('temp');
    $result = ClamavScanner::scan($path);
    if ($result->hasVirus()) {
        throw new \Exception('Virus detected!');
    }
    
  5. Batch Processing: Scan multiple files in a loop (e.g., for bulk uploads):

    foreach ($request->file('files') as $file) {
        $path = $file->store('temp');
        if (!ClamavScanner::scan($path)->isClean()) {
            return back()->withErrors(['files' => 'Virus detected in one or more files.']);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. ClamAV Service Dependencies:

    • Error: Connection refused or Command not found if ClamAV isn’t installed/running.
    • Fix: Verify ClamAV daemon is active (sudo systemctl status clamav-daemon) and freshclam is updated.
    • Debug: Check config/clamav-validator.php for the correct clamav_command (default: clamscan).
  2. Performance Overhead:

    • Issue: Large files or high traffic may cause timeouts.
    • Mitigation:
      • Increase timeout in config (default: 5 seconds).
      • Use on_failure: 'skip' to bypass scans for non-critical files.
      • Offload scans to a queue (e.g., Laravel Queues) for async processing.
  3. False Positives/Negatives:

    • ClamAV Updates: Run sudo freshclam regularly to avoid outdated signatures.
    • Custom Signatures: Add local signatures via /etc/clamav/local.d/ if needed.
  4. File Size Limits:

    • Error: File too large if exceeding max_file_size (default: 10485760 bytes = 10MB).
    • Workaround: Increase the limit or pre-filter files by size:
      $request->validate([
          'file' => ['file', 'max:20480', new ClamavScan(['max_file_size' => 20971520])],
      ]);
      
  5. Windows Compatibility:

    • Note: Not officially tested. Use WSL or Docker with ClamAV if on Windows.

Debugging Tips

  1. Enable Logging: Add to config/clamav-validator.php:

    'log_errors' => true,
    

    Check storage/logs/laravel.log for ClamAV scan failures.

  2. Test Locally: Use a test file (e.g., EICAR test file) to verify scans:

    echo "X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*" > eicar.com
    

    Then upload it to trigger the validator.

  3. Custom Error Messages: Override default messages in your request:

    public function messages()
    {
        return [
            'file.clamav' => 'This file is infected with malware. Please clean it and try again.',
        ];
    }
    

Extension Points

  1. Custom Rules: Extend the ClamavScan rule for project-specific logic:

    namespace App\Rules;
    
    use Sunspikes\ClamavValidator\Rules\ClamavScan as BaseClamavScan;
    
    class ProjectClamavScan extends BaseClamavScan
    {
        public function __construct(array $options = [])
        {
            $options['exclude_extensions'] = array_merge(
                $options['exclude_extensions'] ?? [],
                ['iso', 'bin']
            );
            parent::__construct($options);
        }
    }
    
  2. Hook into Scan Events: Publish the service provider and bind events:

    // In AppServiceProvider@boot()
    \Sunspikes\ClamavValidator\Events\ClamavScanStarted::class => [YourListener::class, 'handle'],
    \Sunspikes\ClamavValidator\Events\ClamavScanCompleted::class => [YourListener::class, 'handle'],
    
  3. Mocking for Tests: Use a fake scanner in tests:

    $this->app->bind(\Sunspikes\ClamavValidator\Contracts\ClamavScanner::class, function () {
        return new \Sunspikes\ClamavValidator\Testing\FakeClamavScanner(['has_virus' => false]);
    });
    
  4. Docker Integration: Add ClamAV to your Dockerfile:

    RUN apt-get update && apt-get install -y clamav-daemon && freshclam
    CMD (service clamav-daemon start && tail -f /dev/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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style