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 (0–100), configurable masking, Eloquent trait auto-sanitizing, middleware and validation rules, plus events and testing fakes.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation: Run composer require blaspsoft/blasp and publish config with php artisan vendor:publish --tag="blasp".
  2. First Use Case: Check a string for profanity:
    use Blaspsoft\Blasp\Facades\Blasp;
    $result = Blasp::check('This is a fucking sentence');
    echo $result->clean(); // "This is a ******* sentence"
    
  3. Key Files:
    • config/blasp.php (configuration)
    • app/Providers/BlaspServiceProvider.php (custom drivers, if needed)
    • app/Models/YourModel.php (for Eloquent integration)

Implementation Patterns

1. Basic Usage

  • Single Check: Use the fluent API for one-off checks:
    $cleanText = Blasp::mask('#')->check($userInput)->clean();
    
  • Batch Processing: Sanitize an array of strings:
    $results = Blasp::checkMany(['text1', 'text2']);
    foreach ($results as $result) {
        echo $result->clean();
    }
    

2. Eloquent Integration

  • Auto-Sanitization: Add the Blaspable trait to models:
    class Comment extends Model {
        use Blaspsoft\Blasp\Blaspable;
        protected $blaspable = ['body', 'title'];
    }
    
  • Reject Mode: Block profanity entirely:
    class Comment extends Model {
        use Blaspsoft\Blasp\Blaspable;
        protected $blaspMode = 'reject';
    }
    

3. Middleware for Requests

  • Route-Level Protection: Apply middleware to routes:
    Route::post('/comment', CommentController::class)
        ->middleware('blasp:sanitize,high');
    
  • Custom Fields: Override middleware config in config/blasp.php:
    'middleware' => [
        'fields' => ['comment', 'title'],
        'except' => ['password'],
    ],
    

4. Validation Rules

  • Form Validation: Use the Profanity rule:
    use Blaspsoft\Blasp\Rules\Profanity;
    $request->validate([
        'bio' => ['required', Profanity::in('spanish')->maxScore(30)],
    ]);
    

5. Blade Directives

  • Safe Output: Sanitize and escape text in views:
    <p>@clean($comment->body)</p>
    

6. String Macros

  • Helper Methods: Use Str helpers:
    $cleanText = Str::cleanProfanity($userInput);
    if (Str::isProfane($userInput)) { ... }
    

7. Custom Drivers

  • Extend Functionality: Create a new driver for niche use cases:
    class CustomDriver implements DriverInterface {
        public function check(string $text, Dictionary $dictionary): Result {
            // Custom logic
        }
    }
    
    Register it in BlaspServiceProvider:
    public function boot() {
        Blasp::extend('custom', function () {
            return new CustomDriver();
        });
    }
    

Gotchas and Tips

Pitfalls

  1. Performance with Regex Driver:

    • The regex driver is thorough but slower. Use pattern for speed or pipeline for balanced performance.
    • Cache results if checking the same text repeatedly:
      Blasp::cacheResults(true)->check($text);
      
  2. False Positives in Phonetic Driver:

    • The phonetic driver may flag words like "fork" or "duck." Add them to config/blasp.php under drivers.phonetic.false_positives.
  3. Severity Mismatches:

    • Ensure severity thresholds align with your use case. For example, Severity::High may block too much in a casual forum but fit a professional setting.
  4. Eloquent Trait Conflicts:

    • If using Blaspable, ensure $blaspable attributes are serializable (no closures or non-string keys).
  5. Middleware Field Matching:

    • Wildcards (*) in middleware.fields match all fields, but except takes precedence. Test edge cases like nested arrays or objects.

Debugging Tips

  1. Inspect Results:

    • Dump the full result object to debug:
      dd(Blasp::check($text)->toArray());
      
    • Check uniqueWords() and words() for granular details.
  2. Log Detected Words:

    • Listen to ProfanityDetected events:
      Event::listen(ProfanityDetected::class, function ($event) {
          Log::debug('Profanity detected:', $event->result->toArray());
      });
      
  3. Test Obfuscation:

    • Verify the regex driver catches variations:
      $result = Blasp::driver('regex')->check('f-u-c-k');
      $result->uniqueWords(); // Should return ['fuck']
      
  4. Cache Issues:

    • Clear cached results if config changes:
      Blasp::flushCache();
      

Extension Points

  1. Custom Masking:

    • Override the default mask with a callback:
      Blasp::mask(fn($word, $len) => str_repeat('X', $len))->check($text);
      
  2. Dynamic Language Selection:

    • Use middleware or request data to switch languages:
      $language = request()->header('Accept-Language');
      Blasp::in($language)->check($text);
      
  3. Severity-Based Actions:

    • Route actions based on severity score:
      $score = Blasp::check($text)->score();
      if ($score > 70) {
          // Escalate to moderator
      }
      
  4. Batch Processing with Jobs:

    • Offload heavy checks to queues:
      SanitizeTextJob::dispatch($text)->onQueue('blasp');
      
  5. Custom Dictionary:

    • Extend language files by publishing and modifying:
      php artisan vendor:publish --tag="blasp-languages"
      
    • Add words to resources/lang/blasp/english.php under words.
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