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

Hyphenizer Sdk Php Laravel Package

bitandblack/hyphenizer-sdk-php

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:
    composer require bitandblack/hyphenizer-sdk-php
    
  2. Initialize the Client:
    use BitAndBlack\HyphenizerSdk\Client;
    use BitAndBlack\HyphenizerSdk\Config;
    
    $config = new Config('YOUR_API_KEY');
    $client = new Client($config);
    
  3. First Use Case: Hyphenate a simple string:
    $result = $client->hyphenate('Laravel', 'en');
    echo $result->getHyphenatedText(); // Output: "La-ra-vel"
    

Where to Look First

  • Documentation: Check the GitHub repository (if available) or inspect the src/ directory for class methods.
  • Config: Review Config class for API key, endpoint, and timeout settings.
  • Response Handling: Explore HyphenationResult methods like getHyphenatedText(), getLanguage(), and getStatus().

Implementation Patterns

Common Workflows

  1. Batch Hyphenation:

    $texts = ['Laravel', 'Eloquent', 'Blade'];
    $language = 'en';
    
    foreach ($texts as $text) {
        $result = $client->hyphenate($text, $language);
        // Process result (e.g., store in DB, render in view)
    }
    
  2. Language Detection: Use a library like mobiledetectlib/mobile-detect to auto-detect language and pass it to the hyphenator:

    $detect = new MobileDetect;
    $language = $detect->getLanguage() ?: 'en'; // Fallback to English
    $result = $client->hyphenate($userInput, $language);
    
  3. Integration with Blade Views: Create a custom Blade directive or helper:

    // app/Helpers/Hyphenator.php
    use BitAndBlack\HyphenizerSdk\Client;
    use BitAndBlack\HyphenizerSdk\Config;
    
    function hyphenate($text, $language = 'en') {
        static $client = new Client(new Config(config('services.hyphenizer.api_key')));
        return $client->hyphenate($text, $language)->getHyphenatedText();
    }
    

    Usage in Blade:

    <p>{{ hyphenate('Laravel', 'en') }}</p>
    
  4. Caching Responses: Cache hyphenated results to reduce API calls (e.g., using Laravel's cache):

    $cacheKey = "hyphenated:{$text}:{$language}";
    $hyphenatedText = cache()->remember($cacheKey, now()->addHours(1), function() use ($client, $text, $language) {
        return $client->hyphenate($text, $language)->getHyphenatedText();
    });
    

Integration Tips

  • Environment Configuration: Store the API key in .env:

    HYPHENIZER_API_KEY=your_api_key_here
    

    Load it in config/services.php:

    'hyphenizer' => [
        'api_key' => env('HYPHENIZER_API_KEY'),
    ],
    

    Then inject the config into the Client:

    $client = new Client(new Config(config('services.hyphenizer.api_key')));
    
  • Error Handling: Wrap API calls in try-catch blocks to handle exceptions (e.g., BitAndBlack\HyphenizerSdk\Exception\HyphenizerException):

    try {
        $result = $client->hyphenate($text, $language);
    } catch (\Exception $e) {
        Log::error("Hyphenation failed: " . $e->getMessage());
        return $text; // Fallback to original text
    }
    
  • Rate Limiting: Implement a queue (e.g., Laravel Queues) for bulk hyphenation to avoid hitting API limits:

    // Dispatch a job for each text
    HyphenateJob::dispatch($text, $language);
    

Gotchas and Tips

Pitfalls

  1. API Key Leaks:

    • Never hardcode the API key in your source files. Always use environment variables.
    • Exclude .env from version control (add it to .gitignore).
  2. Language Support:

    • The API may not support all languages. Test edge cases (e.g., und for Undetermined) and handle unsupported languages gracefully:
      $supportedLanguages = ['en', 'de', 'fr']; // Example
      if (!in_array($language, $supportedLanguages)) {
          $language = 'en'; // Default fallback
      }
      
  3. Text Length Limits:

    • The API may have limits on input text length. Validate input before sending:
      if (strlen($text) > 1000) {
          throw new \InvalidArgumentException("Text too long for hyphenation.");
      }
      
  4. Rate Limits:

    • Monitor API response headers for X-RateLimit-* fields. Implement exponential backoff for retries:
      use Symfony\Component\HttpClient\Retry\RetryStrategy;
      
      $client = new Client($config, [
          'http_client' => HttpClient::create([
              'base_uri' => 'https://api.bitandblack.com',
              'retry' => RetryStrategy::create(
                  RetryStrategy::MAX_RETRIES,
                  RetryStrategy::PURE_RETRY,
                  null,
                  null,
                  null,
                  100 // Initial delay in ms
              ),
          ]),
      ]);
      
  5. Case Sensitivity:

    • Hyphenation results may vary for mixed-case input (e.g., "Laravel" vs. "laravel"). Normalize input if consistency is critical:
      $normalizedText = mb_strtolower($text);
      

Debugging Tips

  1. Enable Verbose Logging: Configure the HTTP client to log requests/responses:

    $client = new Client($config, [
        'http_client' => HttpClient::create([
            'headers' => [
                'Accept' => 'application/json',
            ],
            'event_dispatcher' => new EventDispatcher(),
            'logger' => new StreamHandler(storage_path('logs/hyphenizer.log'), Logger::DEBUG),
        ]),
    ]);
    
  2. Inspect Raw Responses: Access the raw response object for debugging:

    $result = $client->hyphenate($text, $language);
    \Log::debug('Raw response:', [$result->getRawResponse()->getContent(false)]);
    
  3. Mock the Client for Testing: Use Laravel's MockHttpClient to simulate API responses in tests:

    use Symfony\Component\HttpClient\MockHttpClient;
    
    $mockClient = new MockHttpClient([
        new MockResponse('{"hyphenatedText":"La-ra-vel"}', ['http_code' => 200]),
    ]);
    
    $client = new Client($config, ['http_client' => $mockClient]);
    

Extension Points

  1. Custom Response Handlers: Extend the HyphenationResult class to add domain-specific methods:

    class CustomHyphenationResult extends HyphenationResult {
        public function isValid(): bool {
            return $this->getStatus() === 'success';
        }
    
        public function getHyphenatedWords(): array {
            return explode('-', $this->getHyphenatedText());
        }
    }
    

    Override the client's response factory to return your custom class.

  2. Add Retry Logic: Implement custom retry logic for specific HTTP status codes (e.g., 429 Too Many Requests):

    $client = new Client($config, [
        'http_client' => HttpClient::create([
            'on_options' => function (Options $options) {
                $options->setRetry(5, 100, function ($result, $retry, $options) {
                    return $result->getStatusCode() >= 500 || $result->getStatusCode() === 429;
                });
            },
        ]),
    ]);
    
  3. Language Fallback Chain: Create a fallback chain for unsupported languages:

    $fallbackLanguages = ['en', 'de', 'fr'];
    $language = $this->resolveLanguage($request->language, $fallbackLanguages);
    
    private function resolveLanguage(?string $language, array $fallbacks): string {
        return in_array($language, $fallbacks) ? $language : $fallbacks[0];
    }
    
  4. Batch Processing Middleware: Add middleware to the HTTP client to log or transform requests/responses:

    $client = new Client($config, [
        'http_client' => HttpClient::create([
            'on_options' => function (
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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