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

Blasp Laravel Package

blaspsoft/blasp

Advanced profanity filtering for Laravel with driver-based detection (regex/pattern/phonetic/pipeline), multi-language support, severity scoring, masking strategies, Eloquent trait, middleware and validation rules, events, and test fakes. Powers blasp.app API.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require blaspsoft/blasp
    php artisan vendor:publish --tag="blasp"
    

    Publish only the config if you don’t need language files.

  2. First Use Case: Check a string for profanity and mask it:

    use Blaspsoft\Blasp\Facades\Blasp;
    
    $result = Blasp::check('This is a fucking sentence');
    echo $result->clean(); // "This is a ******* sentence"
    
  3. Quick Validation: Use the validation rule in a form request:

    $request->validate(['comment' => 'required|blasp_check']);
    

Where to Look First

  • Config: config/blasp.php for default settings (driver, language, masking).
  • Facade: Blasp facade for fluent API usage.
  • Validation Rules: Blaspsoft\Blasp\Rules\Profanity for customizable checks.

Implementation Patterns

Core Workflows

  1. Fluent API Chaining:

    $cleanText = Blasp::in('spanish')
        ->mask('#')
        ->withSeverity(Severity::High)
        ->check($text)
        ->clean();
    
  2. Middleware Integration: Protect routes with built-in middleware:

    Route::post('/submit', SubmitController::class)
        ->middleware('blasp:sanitize,moderate');
    

    Configure fields to check in config/blasp.php under middleware.fields.

  3. Eloquent Model Sanitization: Add the Blaspable trait to models:

    class Comment extends Model {
        use Blaspable;
        protected $blaspable = ['body', 'title'];
    }
    

    Override defaults per model (e.g., blaspMode = 'reject').

  4. Batch Processing: Check multiple strings at once:

    $results = Blasp::checkMany(['text1', 'text2']);
    foreach ($results as $result) {
        if ($result->isOffensive()) {
            // Handle profanity
        }
    }
    
  5. Custom Validation Logic: Use the Profanity rule object for granular control:

    $validator = Validator::make($data, [
        'bio' => ['required', Profanity::in('french')->maxScore(30)]
    ]);
    

Integration Tips

  • Blade Directives: Use @clean($text) to sanitize and escape text in views.
  • String Macros: Leverage Str::cleanProfanity() or Str::of($text)->cleanProfanity() for quick checks.
  • Events: Listen for ProfanityDetected or ModelProfanityDetected to log or notify admins:
    Event::listen(ModelProfanityDetected::class, function ($event) {
        Log::warning("Profanity detected in {$event->attribute}", $event->result->toArray());
    });
    
  • Testing: Use Blasp::fake() to mock results in tests:
    Blasp::fake([
        'This is clean' => false,
        'Profane text' => true,
    ]);
    

Gotchas and Tips

Pitfalls

  1. Performance with Regex Driver:

    • The regex driver is the most thorough but can be slow for large texts or high traffic.
    • Fix: Use the pattern driver for speed or cache results (config/blasp.php > cache.enabled = true).
  2. False Positives in Phonetic Driver:

    • The phonetic driver may flag words like "fork" or "duck" as profanity.
    • Fix: Add words to config/blasp.php > drivers.phonetic.false_positives or config/blasp.php > false_positives.
  3. Separator Limits in Regex:

    • The regex driver only handles up to 3 separators between letters (e.g., f--u--c--k).
    • Fix: For more complex obfuscation, combine with the phonetic driver in a pipeline.
  4. Case Sensitivity:

    • Profanity checks are case-insensitive by default.
    • Tip: Use Blasp::caseSensitive()->check($text) if needed (though this is rare).
  5. Middleware Field Exclusions:

    • Fields listed in middleware.except are always skipped, even if explicitly included in middleware.fields.
    • Fix: Ensure except doesn’t accidentally block critical fields.
  6. Model Reject Mode:

    • In reject mode, the model won’t save if profanity is detected. Ensure you handle the ProfanityRejectedException gracefully:
      try {
          $model->save();
      } catch (ProfanityRejectedException $e) {
          return back()->withErrors(['field' => 'Profanity not allowed.']);
      }
      
  7. Language-Specific Quirks:

    • Some languages (e.g., Spanish) may have different severity mappings for the same word.
    • Tip: Test with Blasp::in('language')->check($text) to verify behavior.

Debugging Tips

  1. Inspect Results: Dump the Result object to debug matches:

    $result = Blasp::check($text);
    dd($result->words()); // Collection of MatchedWord objects with positions/severity
    
  2. Enable Events for Logging: Set 'events' => true in config/blasp.php to log profanity detections via ProfanityDetected events.

  3. Check Cache: If using caching, clear it during development:

    php artisan cache:clear
    
  4. Override Default Drivers: Temporarily switch drivers to isolate issues:

    Blasp::driver('pattern')->check($text); // Faster but less thorough
    

Extension Points

  1. Custom Drivers: Create a driver by implementing DriverInterface:

    use Blaspsoft\Blasp\Core\Contracts\DriverInterface;
    
    class CustomDriver implements DriverInterface {
        public function check(string $text, Dictionary $dictionary): Result {
            // Implement your logic
            return new Result($text, $matches);
        }
    }
    

    Register it in Blasp::extend('custom', CustomDriver::class).

  2. Dynamic Config: Override config per request using Blasp::configure():

    Blasp::configure(function ($config) {
        $config->set('language', 'spanish');
        $config->set('severity', Severity::Moderate);
    });
    
  3. Custom Masking: Use a callback for dynamic masking:

    Blasp::mask(fn($word, $length) => str_repeat('X', $length))->check($text);
    
  4. Language-Specific Dictionaries: Extend language files by publishing and modifying:

    php artisan vendor:publish --tag="blasp-languages"
    

    Add words to resources/lang/blasp/{language}.php.

  5. Severity Tuning: Adjust severity thresholds in config/blasp.php or dynamically:

    Blasp::withSeverity(Severity::High)->check($text);
    

Config Quirks

  • Pipeline Driver: If using pipeline, ensure sub-drivers are listed in config/blasp.php > drivers.pipeline.drivers.
  • Cache TTL: Set cache.ttl to a reasonable value (e.g., 86400 for 24 hours) to avoid stale results.
  • Allow/Block Lists: Global lists in config/blasp.php are merged with per-check allow/block lists. Block lists override allows.

Testing Utilities

  • Fake Results:
    Blasp::fake([
        'clean text' => false,
        'bad text' => true,
    ]);
    
  • Assertions:
    $this->assertTrue(Blasp::check('bad text')->isOffensive());
    $this->assertEquals('****', Blasp::check('bad')->clean());
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope