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

Typo Fixer Bundle Laravel Package

amalricbzh/typo-fixer-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require amalricbzh/typo-fixer-bundle
    

    Add to config/bundles.php (Symfony) or config/app.php (Laravel via bridge):

    return [
        // ...
        AmalricBzh\TypoFixerBundle\TypoFixerBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Inject the TypoFixer service into a controller or command:

    use AmalricBzh\TypoFixerBundle\Service\TypoFixer;
    
    class MyController extends Controller {
        public function __construct(private TypoFixer $typoFixer) {}
    
        public function fixTypo(Request $request) {
            $text = $request->input('text');
            $fixedText = $this->typoFixer->fix($text);
            return response()->json(['fixed' => $fixedText]);
        }
    }
    

    Test with a known typo:

    curl -X POST http://your-app.test/api/fix-typo -d "text=Je vouldrais un café"
    

    Expected output: Je voudrais un café.


Implementation Patterns

Common Workflows

  1. Real-Time Form Validation: Use middleware to auto-correct typos in submitted forms:

    namespace App\Http\Middleware;
    
    use AmalricBzh\TypoFixerBundle\Service\TypoFixer;
    
    class FixFrenchTypoMiddleware {
        public function __construct(private TypoFixer $typoFixer) {}
    
        public function handle($request, Closure $next) {
            $data = $request->all();
            foreach ($data as &$value) {
                if (is_string($value)) {
                    $value = $this->typoFixer->fix($value);
                }
            }
            return $next($request->merge($data));
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        // ...
        \App\Http\Middleware\FixFrenchTypoMiddleware::class,
    ];
    
  2. Batch Processing: Process large datasets (e.g., database records) with a job:

    use AmalricBzh\TypoFixerBundle\Service\TypoFixer;
    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class FixTypoJob implements ShouldQueue {
        use Queueable;
    
        public function __construct(
            private TypoFixer $typoFixer,
            private string $table,
            private string $column
        ) {}
    
        public function handle() {
            DB::table($this->table)
                ->whereRaw("{$this->column} REGEXP '[a-zA-Z]')
                ->chunk(100, function ($records) {
                    foreach ($records as $record) {
                        $fixedValue = $this->typoFixer->fix($record->{$this->column});
                        $record->update([$this->column => $fixedValue]);
                    }
                });
        }
    }
    
  3. API Response Filtering: Auto-correct typos in API responses using a response filter:

    namespace App\Filters;
    
    use AmalricBzh\TypoFixerBundle\Service\TypoFixer;
    
    class FrenchTypoFilter {
        public function __construct(private TypoFixer $typoFixer) {}
    
        public function apply($response) {
            if ($response->isJson()) {
                $data = $response->getData();
                $this->fixNestedArray($data);
                $response->setData($data);
            }
            return $response;
        }
    
        private function fixNestedArray(&$array) {
            foreach ($array as &$value) {
                if (is_array($value)) {
                    $this->fixNestedArray($value);
                } elseif (is_string($value)) {
                    $value = $this->typoFixer->fix($value);
                }
            }
        }
    }
    

Integration Tips

  • Localization Awareness: Combine with Laravel’s localization system to respect user locale:
    $fixedText = app('locale') === 'fr' ? $typoFixer->fix($text) : $text;
    
  • Caching: Cache frequent corrections to improve performance:
    $cacheKey = 'typo_fixer:' . md5($text);
    $fixedText = Cache::remember($cacheKey, now()->addHours(1), function() use ($text, $typoFixer) {
        return $typoFixer->fix($text);
    });
    
  • Configuration: Override default rules via config/typo_fixer.php:
    return [
        'rules' => [
            'vouldrais' => 'voudrais',
            'café' => 'café', // Override if needed
        ],
    ];
    

Gotchas and Tips

Pitfalls

  1. False Positives:

    • The bundle may incorrectly "fix" valid but rare French words (e.g., proper nouns or slang).
    • Mitigation: Whitelist known terms or exclude specific fields:
      $typoFixer->fix($text, ['exclude' => ['name', 'brand']]);
      
  2. Performance:

    • Processing large texts or datasets can be slow. Use chunking or queue jobs for batch operations.
    • Tip: Disable auto-fixing for non-critical paths (e.g., admin panels).
  3. Case Sensitivity:

    • The bundle may not preserve case correctly (e.g., "Je Vouldrais" → "je voudrais").
    • Workaround: Pre-process text to lowercase or use custom rules:
      $typoFixer->addRule('Vouldrais', 'Voudrais');
      
  4. Non-French Text:

    • Passing non-French text may yield unexpected results or errors.
    • Solution: Add a guard clause:
      if (preg_match('/[àâäéèêëîïôöùûüçœæ]/', $text)) {
          return $typoFixer->fix($text);
      }
      return $text;
      

Debugging

  • Log Corrections: Enable logging to track changes:
    $typoFixer->setLogger(app(\Psr\Log\LoggerInterface::class));
    
  • Inspect Rules: Dump the active rules for debugging:
    dd($typoFixer->getRules());
    
  • Test Edge Cases: Validate with:
    • Mixed-case text: "Je Vouldrais".
    • Punctuation: "Café, s'il vous plaît".
    • Numbers/emojis: "123 vouldrais 😊".

Extension Points

  1. Custom Rules: Extend the rule set dynamically:

    $typoFixer->addRule('custom_typo', 'correction');
    

    Or via a service provider:

    public function register() {
        $this->app->booted(function() {
            $typoFixer = $this->app->make(TypoFixer::class);
            $typoFixer->addRule('laravel', 'Laravel');
        });
    }
    
  2. Event Listeners: Trigger actions on typo fixes (e.g., analytics):

    $typoFixer->onFix(function(string $original, string $fixed) {
        \Log::info("Typo fixed: '$original' → '$fixed'");
    });
    
  3. Language Support: While primarily French-focused, you can adapt it for other languages by:

    • Forking the package and extending the TypoFixer class.
    • Overriding the rule set entirely:
      $typoFixer->setRules(['spanish' => 'rules' => [...]]);
      

Configuration Quirks

  • Rule Priority: Rules are matched in order. Place more specific rules first.
  • Case Handling: The bundle defaults to case-insensitive matching. For case-sensitive fixes, use custom rules with exact casing.
  • Performance Tuning: Adjust the max_iterations config if dealing with nested typos (e.g., "vouldrais" → "voudrrais" → "voudrais").
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.
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin