Installation
composer require bitandblack/hyphenizer-bundle
Add the bundle to config/bundles.php:
return [
// ...
BitAndBlack\HyphenizerBundle\BitAndBlackHyphenizerBundle::class => ['all' => true],
];
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'
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);
}
}
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 }}
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"]
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)
);
}
});
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);
});
}
}
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
}
RequestStack to detect user language and pass it to the hyphenator:
$locale = $requestStack->getCurrentRequest()->getLocale();
$this->hyphenizer->hyphenate($text, ['language' => $locale]);
API Token Leaks
.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.Rate Limiting
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
]
);
Character Encoding
$text = mb_convert_encoding($text, 'UTF-8');
Batch Processing Limits
$batchSize = 10;
foreach (array_chunk($texts, $batchSize) as $chunk) {
$results[] = $this->hyphenizer->hyphenateBatch($chunk);
}
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.
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);
Timeout Errors
TimeoutException when processing long texts.bit_and_black_hyphenizer:
timeout: 60 # seconds
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'
**Language-S
How can I help you explore Laravel packages today?