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

Php String Script Language Laravel Package

lasserafn/php-string-script-language

Detect which writing system a string uses with a simple PHP API. Check if text contains Arabic, Latin, Cyrillic, Thai, Han/Chinese, Japanese (Hiragana/Katakana), and many more scripts via boolean helpers like StringScript::isThai($text).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require lasserafn/php-string-script-language
    

    Add to composer.json if not using autoloading:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Lasserafn\\StringScriptLanguage\\": "vendor/lasserafn/php-string-script-language/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Detect the language of a string:

    use Lasserafn\StringScriptLanguage\StringScriptLanguage;
    
    $detector = new StringScriptLanguage();
    $language = $detector->detectLanguage('Bonjour le monde!');
    echo $language; // Outputs: "fr"
    
  3. Where to Look First:

    • Source Code (if available; otherwise, inspect vendor/lasserafn/php-string-script-language/src/).
    • Class StringScriptLanguage for core methods.
    • Test files (if any) for edge-case examples.

Implementation Patterns

Usage Patterns

  1. Basic Detection:

    $detector = new StringScriptLanguage();
    $language = $detector->detectLanguage($string);
    

    Supports strings in ISO 639-1 (e.g., en, fr, de).

  2. Encoding Detection (if extended):

    // Hypothetical: If encoding detection is added later
    $encoding = $detector->detectEncoding($string);
    
  3. Batch Processing:

    $strings = ['Hello', 'Hola', 'Ciao'];
    $languages = array_map([$detector, 'detectLanguage'], $strings);
    // Output: ['en', 'es', 'it']
    
  4. Integration with Laravel:

    • Service Provider:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton(StringScriptLanguage::class);
      }
      
    • Facade (optional):
      // app/Facades/StringScriptLanguage.php
      public static function detectLanguage($string) {
          return app(StringScriptLanguage::class)->detectLanguage($string);
      }
      
  5. Middleware for Localization:

    // app/Http/Middleware/DetectLanguage.php
    public function handle($request, Closure $next) {
        $language = app(StringScriptLanguage::class)->detectLanguage($request->input('content'));
        app()->setLocale($language);
        return $next($request);
    }
    

Workflows

  1. User-Generated Content: Detect language of comments/reviews in real-time:

    $commentLanguage = $detector->detectLanguage($request->comment);
    $this->translateComment($commentLanguage, $request->comment);
    
  2. SEO/Content Analysis: Analyze blog posts or product descriptions:

    $postLanguage = $detector->detectLanguage($post->content);
    $this->indexPostForSearch($postLanguage, $post);
    
  3. Multilingual APIs: Route requests based on detected language:

    $language = $detector->detectLanguage($request->body);
    return redirect()->route("content.$language");
    

Integration Tips

  • Caching Results: Cache detected languages to avoid redundant processing:

    $cacheKey = 'language_'.md5($string);
    $language = cache()->remember($cacheKey, now()->addHours(1), function() use ($detector, $string) {
        return $detector->detectLanguage($string);
    });
    
  • Fallback Logic: Combine with Laravel’s locale fallbacks:

    $language = $detector->detectLanguage($string) ?: config('app.fallback_locale');
    
  • Testing: Mock the detector in unit tests:

    $mockDetector = Mockery::mock(StringScriptLanguage::class);
    $mockDetector->shouldReceive('detectLanguage')->andReturn('fr');
    $this->app->instance(StringScriptLanguage::class, $mockDetector);
    

Gotchas and Tips

Pitfalls

  1. False Positives:

    • Short strings (e.g., "Ok") may return ambiguous results.
    • Fix: Add a minimum length check or whitelist known phrases.
      if (strlen($string) < 5) {
          return config('app.fallback_locale');
      }
      
  2. Non-Latin Scripts:

    • The package may not support non-Latin scripts (e.g., Arabic, Chinese) unless explicitly configured.
    • Fix: Extend the detector or use a dedicated library like symfony/intl for multilingual support.
  3. Performance:

    • Heavy usage (e.g., detecting language for every request) may impact performance.
    • Fix: Cache results aggressively or batch-process strings.
  4. Encoding Issues:

    • If the input string has incorrect encoding (e.g., UTF-8 vs. ISO-8859-1), detection may fail.
    • Fix: Normalize encoding first:
      $normalized = mb_convert_encoding($string, 'UTF-8');
      
  5. Undocumented Methods:

    • The package is lightweight; some features (e.g., encoding detection) may not exist.
    • Fix: Inspect the source code or open an issue to request features.

Debugging

  1. Log Detection Results:

    \Log::debug('Detected language', ['string' => $string, 'language' => $language]);
    
  2. Test Edge Cases:

    • Empty strings, numbers, or special characters:
      $this->assertEquals('en', $detector->detectLanguage('Hello 123!'));
      $this->assertNull($detector->detectLanguage('')); // Handle null/undefined
      
  3. Compare with Other Libraries:

Tips

  1. Extend the Detector: Add custom rules for domain-specific languages:

    class CustomStringScriptLanguage extends StringScriptLanguage {
        protected function getCustomRules() {
            return [
                'jp' => ['/^こんにちは$/u', '/^ありがとう$/u'],
            ];
        }
    }
    
  2. Combine with Laravel Localization: Use detected languages to set the app locale:

    $language = $detector->detectLanguage($string);
    app()->setLocale($language);
    
  3. Localization Fallbacks: Configure a fallback chain in config/app.php:

    'fallback_locale' => 'en',
    'locale_fallbacks' => [
        'fr' => ['en'],
        'de' => ['en'],
    ],
    
  4. Document Assumptions: Clearly document in your codebase that the detector is not 100% accurate and may require manual review for critical use cases (e.g., legal documents).

  5. Monitor Accuracy: Track detection accuracy over time and retrain/customize rules as needed:

    // Pseudocode for tracking
    $stats = [
        'total' => 0,
        'correct' => 0,
    ];
    $stats['total']++;
    if ($detected === $expected) $stats['correct']++;
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky