respect/string-formatter
Flexible PHP string formatting library with chainable formatters and templated placeholders. Mask, pattern, date, number, and more to transform/format values (e.g., credit cards, phones, amounts) via FormatterBuilder or PlaceholderFormatter modifiers.
The respect/string-formatter package is a highly modular and composable solution tailored for Laravel applications requiring structured string transformations. Its chainable formatter pattern (FormatterBuilder) aligns seamlessly with Laravel’s dependency injection, service container, and middleware/validation pipelines. Key architectural advantages include:
CreditCardFormatter, DateFormatter, SecureCreditCardFormatter) eliminate custom logic for compliance-critical or repetitive tasks, reducing technical debt.PlaceholderFormatter enables dynamic string interpolation without coupling to Twig or Blade, ideal for emails, notifications, or API responses.mb_* functions and pattern-based formatting.Potential Misalignments:
str_replace, preg_replace) may find the package unnecessary.PatternFormatter’s regex-like syntax) require familiarity with the library’s patterns.Str::) or Eloquent model integration.Laravel-Specific Strategies:
Service Container Binding:
FormatterBuilder as a singleton or resolve dynamically:
$this->app->singleton(FormatterBuilder::class, fn() => f::create());
string.formatters).Facade Wrapper:
StringFormatter) to simplify usage:
use Illuminate\Support\Facades\Facade;
class StringFormatter extends Facade {
protected static function getFacadeAccessor() { return 'formatter'; }
}
StringFormatter::mask('###-###-####')->format($phone);
Validation Integration:
use Respect\StringFormatter\CreditCardFormatter;
class MaskedCreditCard extends Rule {
public function passes($attribute, $value) {
return (new CreditCardFormatter())->format($value) !== $value;
}
}
public function rules() {
return ['credit_card' => ['required', new MaskedCreditCard]];
}
Middleware/Response Filtering:
public function handle($request, Closure $next) {
$request->merge([
'formatted_phone' => f::create()->mask('(###) ###-####')->format($request->phone),
]);
return $next($request);
}
Blade/Template Integration:
PlaceholderFormatter for dynamic content:
@php
$formatter = new \Respect\StringFormatter\PlaceholderFormatter([
'user' => $user,
]);
@endphp
<p>{{ $formatter->format('Hello, {{user.name|uppercase}}!') }}</p>
Compatibility Notes:
Str:: helpers to avoid redundancy.| Risk Area | Mitigation Strategy |
|---|---|
| Performance Overhead | Benchmark critical paths (e.g., bulk string processing). Use caching (e.g., Redis) for repeated operations. |
| Complexity | Start with basic formatters (e.g., TrimFormatter, PatternFormatter) before adopting advanced ones. |
| Unicode Edge Cases | Test with CJK, emoji, and RTL scripts to ensure mb_* functions work as expected. |
| Breaking Changes | Pin to a specific version (e.g., ^1.0.0) until adoption stabilizes. |
| Security | Validate all user-provided patterns (e.g., PatternFormatter) to prevent ReDoS or injection. |
| Dependency Bloat | Audit Laravel’s existing string utilities (e.g., Str::, Illuminate\Support\Stringable) to avoid overlap. |
Key Questions for TPM:
symfony/string, league/pipe) that could conflict?PatternFormatter or malformed input).Str::)?SecureCreditCardFormatter)?Laravel Ecosystem Synergy:
$this->app->bind(FormatterBuilder::class, fn() => f::create()->mask('###-###-####'));
prepareForValidation or withValidator to transform input before processing.toArray() or toResponse() methods for consistent output.PlaceholderFormatter for dynamic UI content without coupling to Twig.Example Integration Workflow:
// App\Http\Requests\StoreUserRequest.php
public function prepareForValidation() {
$this->merge([
'phone' => f::create()->mask('(###) ###-####')->format($this->phone),
]);
}
// App\Http\Resources\UserResource.php
public function toArray($request) {
return [
'formatted_phone' => f::create()->pattern('(###) ###-####')->format($this->phone),
];
}
// app/Mail/OrderConfirmation.php
public function build() {
$formatter = new PlaceholderFormatter(['amount' => $this->order->amount]);
return $this->markdown('emails.order')
->with(['content' => $formatter->format('Total: ${{amount|number:2}}')]);
}
Microservices/Queues:
created, updated).| Phase | Action Items |
|---|---|
| Assessment | Audit existing string manipulation logic (e.g., regex, custom functions) to identify replacement candidates. |
| Pilot Integration | Integrate into a non-critical module (e.g., admin panel input masking or internal APIs) to validate performance and usability. |
| Core Adoption | Replace legacy logic in validation, APIs, and templates with formatters. Prioritize high-impact areas (e.g., user input, compliance-sensitive data). |
| Customization | Develop custom formatters/modifiers for unique use cases (e.g., domain-specific masking rules). Follow the package’s templates for consistency. |
| Testing | Write comprehensive tests for all formatter usages, including edge cases (e.g., Unicode, empty strings). |
| Documentation | Update internal docs with usage guidelines, examples, and migration steps for the team. |
| Performance Tuning | Benchmark critical paths and optimize (e.g., caching, lazy loading) if needed. |
How can I help you explore Laravel packages today?