dantleech/symfony-form-array-to-delimited-string-transformer
Symfony Form data transformer that converts delimited text fields to arrays and back. Trims whitespace, ignores empty values, and supports custom delimiters plus configurable output padding for formatted tag/keyword input.
Extract Core Logic (Avoid Symfony Dependency): Create a standalone Laravel service to replicate the transformer’s functionality:
php artisan make:service DelimitedStringTransformer
// app/Services/DelimitedStringTransformer.php
namespace App\Services;
class DelimitedStringTransformer {
public function __construct(
private string $delimiter = ',',
private int $padding = 0
) {}
public function transform(array $array): string {
return implode(" {$this->delimiter} ", $array);
}
public function reverse(string $string): array {
return array_filter(explode($this->delimiter, trim($string)));
}
}
Register the Service:
Bind it in AppServiceProvider@boot():
$this->app->singleton(DelimitedStringTransformer::class, function ($app) {
return new \App\Services\DelimitedStringTransformer(';', 1);
});
First Use Case: Form Request Handling
Use in a FormRequest to transform delimited input (e.g., tags) into an array:
// app/Http/Requests/StorePostRequest.php
use App\Services\DelimitedStringTransformer;
public function prepareForValidation() {
$transformer = app(DelimitedStringTransformer::class);
$this->merge([
'tags_array' => $transformer->reverse($this->input('tags'))
]);
}
public function rules() {
return ['tags_array' => 'required|array'];
}
Controller Usage:
public function store(StorePostRequest $request) {
$validated = $request->validated();
// $validated['tags_array'] is now an array
}
Blade/Livewire Integration (Optional): For output (e.g., displaying stored tags):
$transformer = new \App\Services\DelimitedStringTransformer;
$tagsString = $transformer->transform($post->tags);
Where to Look First:
app/Services/DelimitedStringTransformer.php for core logic.FormRequest for input transformation (most common use case)."php;laravel;symfony").$this->merge([
'tags' => app(DelimitedStringTransformer::class)->reverse($this->tags)
]);
public function rules() {
return ['tags' => 'required|array|min:1'];
}
Post::find(1)->tags).$tagsString = app(DelimitedStringTransformer::class)->transform($post->tags);
<input type="text" value="{{ $tagsString }}">
$this->app->bind('semicolon.transformer', function () {
return new \App\Services\DelimitedStringTransformer(';');
});
updated() methods:
public $tagsInput = '';
public function updatedTagsInput() {
$this->tags = app(DelimitedStringTransformer::class)->reverse($this->tagsInput);
}
toArray():
public function toArray($request) {
return [
'tags' => app(DelimitedStringTransformer::class)->transform($this->tags)
];
}
protected $casts = [
'tags' => \App\Services\DelimitedStringTransformer::class
];
(Note: Requires custom accessors/mutators.)| Use Case | Implementation Pattern | Example |
|---|---|---|
| Tagging System | FormRequest + prepareForValidation() |
Transform input string to array for validation/storage. |
| CSV Import | Request middleware |
Transform delimited CSV data into arrays for processing. |
| Legacy System Bridge | API Resource or Form Request | Convert API payloads (e.g., "a,b") to arrays for internal use. |
| User-Generated Lists | Livewire/Blade + updated() |
Real-time transformation of user input (e.g., comma-separated values). |
Whitespace Handling:
' a , b ' => ['a', 'b'] // Works
'a,,b' => ['a', '', 'b'] // Empty strings may slip through
$array = array_filter($transformer->reverse($input));
Delimiter in Data:
"a;b;c;d" with ; delimiter), the array will split incorrectly.|):
new DelimitedStringTransformer('|'); // Less likely to appear in user input
Symfony Dependency Risks:
dantleech/symfony-form-array-to-delimited-string-transformer may pull in unwanted Symfony components.Padding Quirks:
1, 1) adds spaces around delimiters:
['a', 'b'] => 'a , b' // Note the spaces
trim($transformer->transform($array));
Database Storage:
text column may cause:
"a,b" vs. ["a", "b"]).Case Sensitivity:
, or ; are case-sensitive. Mixed-case input (e.g., ";" vs "; ") may fail.$delimiter = strtolower(trim($this->delimiter));
Log Transformations: Add debug logs to verify behavior:
\Log::debug('Transformed:', [
'input' => $input,
'output' => $transformer->reverse($input)
]);
Test Edge Cases: Write tests for:
"" → []" a , b " → ["a", "b"]"a;b" with ; delimiter → ["a", "b"]"a,,b" → ["a", "", "b"]Validate Against Manual Logic: Compare output with native PHP functions:
$manual = array_filter(explode(',', $input));
$transformed = $transformer->reverse($input);
assert($manual === $transformed);
Custom Validation: Extend the transformer to add validation rules:
class ValidatingDelimitedStringTransformer extends DelimitedStringTransformer {
public function reverse(string $string): array {
$array = parent::reverse($string);
if (count($array) > 5) {
throw new \InvalidArgumentException('Max 5 tags allowed.');
}
return $array;
}
}
Normalization: Add methods to normalize output (e.g., lowercase, trim):
public function transformWithNormalization(array $array): string {
return $this->transform(array_map('trim', array_map('strtolower', $array)));
}
Integration with Laravel Validation: Create a custom rule:
use Illuminate\Contracts\Validation\Rule;
class
How can I help you explore Laravel packages today?