onnov/detect-encoding
Fast Cyrillic text encoding detector for PHP to replace unreliable mb_detect_encoding. Identifies Windows-1251, KOI8-R, ISO-8859-5 (optionally IBM866/MacCyrillic) using code page ranges, with high accuracy even on short strings and very large texts.
## Integration Approach
### **Migration Path**
- **Phase 2: Wrapper Abstraction** (continued)
```php
public function detect(string $text): string {
if ($this->isWhitelistedEncoding($text)) {
return (new \Onnov\DetectEncoding\EncodingDetector())->getEncoding($text);
}
return mb_detect_encoding($text, $this->fallbackEncodings, true);
}
}
```
- **Phase 3: Rollout**
- Replace calls in **controllers**, **commands**, and **jobs** using a **regex search/replace** (e.g., `mb_detect_encoding(` → `app('encodingDetector')->detect(`).
- Use **Laravel’s `app()` helper** for dependency injection:
```php
$encoding = app(\App\Services\EncodingDetector::class)->detect($text);
```
### **Compatibility**
- **PHP Version**: Test on **PHP 7.4+** (Laravel’s LTS support). PHP 8.x may require minor adjustments (e.g., named arguments).
- **Laravel Version**: Compatible with **Laravel 7+** (no framework-specific code). For older versions, ensure `composer.json` constraints allow PHP 7.4+.
- **Dependency Conflicts**: None (single class, no Composer dependencies beyond PHP).
- **Encoding Support**:
- **Enabled by Default**: `windows-1251`, `koi8-r`, `iso-8859-5`, `ibm866`.
- **Disabled by Default**: `MAC_CYRILLIC` (enable only if needed).
- **Custom Encodings**: Extend via `addEncoding()` if supporting niche cases (e.g., `x-mac-cyrillic`).
### **Sequencing**
1. **Add to `composer.json`**:
```bash
composer require onnov/detect-encoding
php artisan make:service EncodingDetector
AppServiceProvider@boot():
$this->app->singleton(\App\Services\EncodingDetector::class);
// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->bind(\App\Services\EncodingDetector::class);
}
windows-1251).tideways or blackfire.io).README.md.StringUtils or PHP’s intl extension if this package stagnates.mb_detect_encoding improves (track PHP RFCs).\Log::debug('Encoding detection failed', ['text' => substr($text, 0, 100), 'result' => $encoding]);
mb_detect_encoding.| Failure Scenario | Impact | Mitigation |
|---|---|---|
| False Encoding Detection | Data corruption (e.g., koi8-r → utf-8) |
Fallback to mb_detect_encoding + manual review. |
| Unsupported Encoding | Silent failure or exception | Whitelist encodings; log unsupported cases. |
| Malicious Input | Exploit encoding bugs (e.g., buffer overflows) | Validate input length/character ranges. |
| PHP Version Incompatibility | Breaks in PHP 8.x | Test on target PHP version; fork if needed. |
| Custom Encoding Mismatch | Incorrect ranges for added encodings | Validate custom encodings with test data. |
internal or docs/encoding.md.// Detect encoding
$encoding = app(\App\Services\EncodingDetector::class)->detect($text);
// Convert to UTF-8
$utf8Text = app(\App\Services\EncodingDetector::class)->toUtf8($text);
mb_detect_encoding with real-world samples.
```markdown
## Operational Impact (Continued)
### **Monitoring**
- **Key Metrics**:
- **Detection Accuracy**: Log success/failure rates by encoding (e.g., Prometheus counter).
- **Performance**: Track detection time for large texts (e.g., `histogram` in APM tools).
- **Fallback Usage**: Percentage of detections using `mb_detect_encoding` (should trend to 0%).
- **Alerts**:
- **Anomaly Detection**: Alert if false-positive rate exceeds 1% for a given encoding.
- **Latency Spikes**: Notify if detection time > 10ms for texts >10KB.
### **Disaster Recovery**
- **Data Corruption**:
- **Audit Trail**: Log original text + detected encoding for reversible changes.
- **Backup**: Store raw files alongside processed data during migrations.
- **Outage**:
- **Graceful Degradation**: Fall back to `mb_detect_encoding` or disable encoding detection entirely (with user notification).
### **Team Skills**
- **Required**:
- Familiarity with **Laravel service containers** and **dependency injection**.
- Basic **PHP string manipulation** (e.g., `iconv`, `mb_*` functions).
- **Upskill**:
- **Encoding Theory**: Train team on `windows-1251` vs. `koi8-r` differences (critical for debugging).
- **Performance Profiling**: Use tools like **Xdebug** to analyze detection bottlenecks.
### **Cost Analysis**
- **Development**:
- **Low**: ~5–10 dev hours for integration (wrapper + tests).
- **Operational**:
- **None**: No hosting, APIs, or licenses.
- **Risk Mitigation**:
- **High**: Potential data corruption if misconfigured (offset by fallback logic).
- **Low**: Maintenance or scaling costs.
### **Stakeholder Communication**
- **For Developers**:
- *"Use `app('encodingDetector')->detect($text)` instead of `mb_detect_encoding`. For custom encodings, extend the service class."*
- **For QA**:
- *"Test with Cyrillic/Windows-1251 texts. Log any misdetections for review."*
- **For Product**:
How can I help you explore Laravel packages today?