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

Symfony Form Array To Delimited String Transformer Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps for Laravel Integration

  1. 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)));
        }
    }
    
  2. Register the Service: Bind it in AppServiceProvider@boot():

    $this->app->singleton(DelimitedStringTransformer::class, function ($app) {
        return new \App\Services\DelimitedStringTransformer(';', 1);
    });
    
  3. 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'];
    }
    
  4. Controller Usage:

    public function store(StorePostRequest $request) {
        $validated = $request->validated();
        // $validated['tags_array'] is now an array
    }
    
  5. 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:

  • Focus on app/Services/DelimitedStringTransformer.php for core logic.
  • Use FormRequest for input transformation (most common use case).
  • Skip Symfony-specific docs; prioritize the extracted Laravel service.

Implementation Patterns

Workflow: Input → Array → Storage

  1. User Input:
    • User submits a delimited string (e.g., "php;laravel;symfony").
  2. FormRequest Transformation:
    $this->merge([
        'tags' => app(DelimitedStringTransformer::class)->reverse($this->tags)
    ]);
    
  3. Validation:
    public function rules() {
        return ['tags' => 'required|array|min:1'];
    }
    
  4. Storage: Save the array to a database (e.g., JSON column or pivot table).

Workflow: Storage → Output → User

  1. Retrieve Data: Fetch the stored array (e.g., Post::find(1)->tags).
  2. Transform for Display:
    $tagsString = app(DelimitedStringTransformer::class)->transform($post->tags);
    
  3. Render in Blade:
    <input type="text" value="{{ $tagsString }}">
    

Integration Tips

  • Custom Delimiters: Bind different instances for different fields:
    $this->app->bind('semicolon.transformer', function () {
        return new \App\Services\DelimitedStringTransformer(';');
    });
    
  • Livewire Components: Use the transformer in updated() methods:
    public $tagsInput = '';
    
    public function updatedTagsInput() {
        $this->tags = app(DelimitedStringTransformer::class)->reverse($this->tagsInput);
    }
    
  • API Resources: Transform arrays to strings in toArray():
    public function toArray($request) {
        return [
            'tags' => app(DelimitedStringTransformer::class)->transform($this->tags)
        ];
    }
    
  • Database Casting: Cast JSON arrays to strings in models:
    protected $casts = [
        'tags' => \App\Services\DelimitedStringTransformer::class
    ];
    
    (Note: Requires custom accessors/mutators.)

Common Patterns

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).

Gotchas and Tips

Pitfalls

  1. Whitespace Handling:

    • The transformer trims input but may not handle edge cases like:
      '  a  ,  b  ' => ['a', 'b']  // Works
      'a,,b'        => ['a', '', 'b']  // Empty strings may slip through
      
    • Fix: Add validation or post-processing:
      $array = array_filter($transformer->reverse($input));
      
  2. Delimiter in Data:

    • If user input contains the delimiter (e.g., "a;b;c;d" with ; delimiter), the array will split incorrectly.
    • Fix: Escape delimiters or use a unique delimiter (e.g., |):
      new DelimitedStringTransformer('|');  // Less likely to appear in user input
      
  3. Symfony Dependency Risks:

    • Directly requiring dantleech/symfony-form-array-to-delimited-string-transformer may pull in unwanted Symfony components.
    • Fix: Use the extracted Laravel service (as shown in Getting Started).
  4. Padding Quirks:

    • Padding (e.g., 1, 1) adds spaces around delimiters:
      ['a', 'b'] => 'a , b'  // Note the spaces
      
    • Fix: Adjust padding or trim output if needed:
      trim($transformer->transform($array));
      
  5. Database Storage:

    • Storing delimited strings in a text column may cause:
      • Indexing issues (full-text search only).
      • Data integrity risks (e.g., "a,b" vs. ["a", "b"]).
    • Fix: Store as JSON or use a pivot table for tags.
  6. Case Sensitivity:

    • Delimiters like , or ; are case-sensitive. Mixed-case input (e.g., ";" vs "; ") may fail.
    • Fix: Normalize delimiters:
      $delimiter = strtolower(trim($this->delimiter));
      

Debugging Tips

  1. Log Transformations: Add debug logs to verify behavior:

    \Log::debug('Transformed:', [
        'input' => $input,
        'output' => $transformer->reverse($input)
    ]);
    
  2. Test Edge Cases: Write tests for:

    • Empty strings: ""[]
    • Whitespace: " a , b "["a", "b"]
    • Special characters: "a;b" with ; delimiter → ["a", "b"]
    • Nested delimiters: "a,,b"["a", "", "b"]
  3. Validate Against Manual Logic: Compare output with native PHP functions:

    $manual = array_filter(explode(',', $input));
    $transformed = $transformer->reverse($input);
    assert($manual === $transformed);
    

Extension Points

  1. 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;
        }
    }
    
  2. 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)));
    }
    
  3. Integration with Laravel Validation: Create a custom rule:

    use Illuminate\Contracts\Validation\Rule;
    
    class
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime