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 Bundle Laravel Package

bitandblack/hyphenizer-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require bitandblack/hyphenizer-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        BitAndBlack\HyphenizerBundle\BitAndBlackHyphenizerBundle::class => ['all' => true],
    ];
    
  2. Configure API Token Add your Hyphenizer API token to .env:

    HYPHENIZER_API_TOKEN=your_api_token_here
    

    (Optional) Override default config in config/packages/bit_and_black_hyphenizer.yaml:

    bit_and_black_hyphenizer:
        api_token: '%env(HYPHENIZER_API_TOKEN)%'
        timeout: 30
        base_url: 'https://api.hyphenizer.com'
    
  3. First Use Case Inject the HyphenizerClient service and hyphenate text:

    use BitAndBlack\HyphenizerBundle\Service\HyphenizerClient;
    
    class SomeController
    {
        public function __construct(private HyphenizerClient $hyphenizer)
        {
        }
    
        public function hyphenateText()
        {
            $text = "This is a sample text to hyphenate.";
            $hyphenated = $this->hyphenizer->hyphenate($text);
            return new Response($hyphenated);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Twig Integration Extend Twig with a custom filter for seamless hyphenation in templates:

    // src/Twig/HyphenizerExtension.php
    namespace App\Twig;
    
    use BitAndBlack\HyphenizerBundle\Service\HyphenizerClient;
    use Twig\Extension\AbstractExtension;
    use Twig\TwigFilterMethod;
    
    class HyphenizerExtension extends AbstractExtension
    {
        public function __construct(private HyphenizerClient $hyphenizer)
        {
        }
    
        public function getFilters()
        {
            return [
                new TwigFilterMethod($this, 'hyphenate', ['is_safe' => ['html']]),
            ];
        }
    
        public function hyphenate(string $text): string
        {
            return $this->hyphenizer->hyphenate($text);
        }
    }
    

    Register the extension in config/services.yaml:

    services:
        App\Twig\HyphenizerExtension:
            tags: ['twig.extension']
    

    Usage in Twig:

    {{ 'This is a long text.'|hyphenate }}
    
  2. Batch Processing Process multiple texts efficiently using hyphenateBatch():

    $texts = ["Text 1", "Text 2", "Text 3"];
    $results = $this->hyphenizer->hyphenateBatch($texts);
    // $results = ["Hyphenated Text 1", "Hyphenated Text 2", "Hyphenated Text 3"]
    
  3. Event-Driven Hyphenation Use Symfony events to hyphenate content before rendering (e.g., in KernelEvents::VIEW):

    use Symfony\Component\HttpKernel\Event\ViewEvent;
    use Symfony\Component\HttpKernel\KernelEvents;
    
    $eventDispatcher->addListener(KernelEvents::VIEW, function (ViewEvent $event) {
        $content = $event->getControllerResult();
        if (is_string($content)) {
            $event->setControllerResult(
                $this->hyphenizer->hyphenate($content)
            );
        }
    });
    

Integration Tips

  • Caching: Cache hyphenated results to reduce API calls:
    use Symfony\Contracts\Cache\CacheInterface;
    
    class CachedHyphenizerClient
    {
        public function __construct(
            private HyphenizerClient $hyphenizer,
            private CacheInterface $cache
        ) {}
    
        public function hyphenate(string $text): string
        {
            return $this->cache->get($text, function () use ($text) {
                return $this->hyphenizer->hyphenate($text);
            });
        }
    }
    
  • Fallback Mechanism: Handle API failures gracefully:
    try {
        return $this->hyphenizer->hyphenate($text);
    } catch (\Exception $e) {
        // Fallback to simple hyphenation (e.g., using PHP's `mb_str_split`)
        return str_replace(' ', '​', $text); // Soft hyphen
    }
    
  • Dynamic Language Detection: Use Symfony's RequestStack to detect user language and pass it to the hyphenator:
    $locale = $requestStack->getCurrentRequest()->getLocale();
    $this->hyphenizer->hyphenate($text, ['language' => $locale]);
    

Gotchas and Tips

Pitfalls

  1. API Token Leaks

    • Risk: Hardcoding API tokens in config files or version control.
    • Fix: Always use .env and add it to .gitignore. Validate token presence in config/packages/bit_and_black_hyphenizer.yaml:
      bit_and_black_hyphenizer:
          api_token: '%env(HYPHENIZER_API_TOKEN)%'
      
      Add a validator in a compiler pass or service factory to throw an exception if the token is missing.
  2. Rate Limiting

    • Issue: The Hyphenizer API may throttle requests if limits are exceeded.
    • Solution: Implement exponential backoff in custom clients:
      use Symfony\Component\HttpClient\RetryableHttpClient;
      use Symfony\Contracts\HttpClient\HttpClientInterface;
      
      $client = new RetryableHttpClient(
          HttpClientInterface::create(),
          [
              'max_retries' => 3,
              'delay' => 1000, // 1 second
              'multiplier' => 2,
              'max_delay' => 60000, // 1 minute
          ]
      );
      
  3. Character Encoding

    • Problem: Non-ASCII characters (e.g., German umlauts) may cause issues.
    • Fix: Ensure text is UTF-8 encoded before sending:
      $text = mb_convert_encoding($text, 'UTF-8');
      
  4. Batch Processing Limits

    • Warning: Sending large batches may hit API limits or timeouts.
    • Workaround: Process in chunks:
      $batchSize = 10;
      foreach (array_chunk($texts, $batchSize) as $chunk) {
          $results[] = $this->hyphenizer->hyphenateBatch($chunk);
      }
      

Debugging

  1. Enable API Debugging Configure the client to log requests/responses:

    # config/packages/bit_and_black_hyphenizer.yaml
    bit_and_black_hyphenizer:
        debug: '%kernel.debug%'
        logger: '@logger'
    

    Check logs in var/log/dev.log for API errors.

  2. Validate API Responses Inspect raw responses to debug issues:

    $response = $this->hyphenizer->getClient()->request('POST', '/hyphenate', [
        'json' => ['text' => $text],
    ]);
    $statusCode = $response->getStatusCode();
    $content = $response->getContent(false);
    
  3. Timeout Errors

    • Symptom: TimeoutException when processing long texts.
    • Fix: Increase timeout in config:
      bit_and_black_hyphenizer:
          timeout: 60 # seconds
      

Extension Points

  1. Custom Hyphenation Rules Extend the bundle by creating a decorator for HyphenizerClient:

    use BitAndBlack\HyphenizerBundle\Service\HyphenizerClientInterface;
    
    class CustomHyphenizerClient implements HyphenizerClientInterface
    {
        public function __construct(private HyphenizerClientInterface $decorated)
        {
        }
    
        public function hyphenate(string $text, array $options = []): string
        {
            // Pre-process text (e.g., replace custom patterns)
            $text = $this->preProcess($text);
    
            // Delegate to original client
            $result = $this->decorated->hyphenate($text, $options);
    
            // Post-process result
            return $this->postProcess($result);
        }
    
        private function preProcess(string $text): string
        {
            // Add custom logic (e.g., replace "---" with "—")
            return str_replace('---', '—', $text);
        }
    }
    

    Register the decorator in services.yaml:

    services:
        BitAndBlack\HyphenizerBundle\Service\HyphenizerClientInterface: '@App\Service\CustomHyphenizerClient'
    
  2. **Language-S

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.
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
spatie/mailcoach-vapor
spatie/laravel-javascript-views
spatie/ignition-contracts
earls/stork-command-queue-bundle