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

Edi Parser Laravel Package

boda/edi-parser

Simple positional EDI parser that transforms a raw fixed-width EDI string into a structured key-value array using templates. Supports parsing header/body/footer sections and grouped lines for nested records. Install via Composer and use as a Symfony bundle.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps for Laravel Integration

  1. Extract Core Logic:

    • Clone the repo and isolate the EdiParser class (located in src/Boda/EdiParserBundle/Parser/EdiParser.php).
    • Publish this as a standalone Composer package or directly into your project’s vendor folder.
  2. Install via Composer:

    composer require boda/edi-parser
    

    Note: Since this is a Symfony bundle, manually extract the EdiParser class or use a wrapper.

  3. Basic Usage in Laravel:

    // Register the parser in a service provider
    $this->app->singleton('edi.parser', function ($app) {
        return new \Boda\EdiParserBundle\Parser\EdiParser($app['config']['edi.templates']);
    });
    
    // Parse EDI in a controller or command
    $rawEdi = file_get_contents('path/to/edi_file.txt');
    $parser = app('edi.parser');
    $parsedData = $parser->parse($rawEdi, 'invoice_template');
    
  4. Define a Template: Create a config file (config/edi.php) to define your EDI template structure:

    return [
        'templates' => [
            'invoice' => [
                'header' => [
                    'IDENTIFIER' => ['start' => 0, 'length' => 2],
                    'DOT' => ['start' => 2, 'length' => 1],
                    // ... other fields
                ],
                'body' => [
                    'group' => [
                        'IDENTIFIER' => ['start' => 0, 'length' => 2],
                        'CONTENT' => ['start' => 5, 'length' => 20],
                    ],
                ],
            ],
        ],
    ];
    
  5. First Use Case: Parse a simple EDI file and log the output:

    use Illuminate\Support\Facades\Log;
    
    $parsed = app('edi.parser')->parse($rawEdi, 'invoice');
    Log::info('Parsed EDI:', ['data' => $parsed]);
    

Implementation Patterns

Workflows

1. EDI Parsing Pipeline

  • Ingest: Read EDI files from storage (e.g., S3, local filesystem) or API responses.
  • Parse: Use the EdiParser with a predefined template.
  • Validate: Check for required fields or business rules (extend with Laravel Validation).
  • Store: Save parsed data to a database (Eloquent models) or queue for async processing.
  • Notify: Trigger events (e.g., EdiParsed) or send alerts for failures.

Example:

// app/Services/EdiParserService.php
class EdiParserService {
    public function process(string $filePath, string $templateName) {
        $rawEdi = file_get_contents($filePath);
        $parsed = app('edi.parser')->parse($rawEdi, $templateName);

        // Validate
        $validator = Validator::make($parsed, [
            'header.IDENTIFIER' => 'required|string',
            'body.*.CONTENT' => 'required',
        ]);

        if ($validator->fails()) {
            throw new \RuntimeException('EDI validation failed');
        }

        // Store
        Edi::create($parsed);
    }
}

2. Template Management

  • Static Templates: Define templates in config/edi.php for fixed EDI formats.
  • Dynamic Templates: Load templates from a database or external API for flexible EDI schemas.
    // Custom template loader
    $template = TemplateRepository::find($templateId);
    $parsed = app('edi.parser')->parse($rawEdi, $template->toArray());
    
  • Template Versioning: Use Laravel’s config_cache or a migration-based approach to version templates.

3. Integration with Laravel Features

  • Queues: Offload parsing to a queue for large EDI files:
    EdiParseJob::dispatch($rawEdi, $templateName)->onQueue('edi');
    
  • Events: Dispatch events for parsed EDI:
    event(new EdiParsed($parsedData));
    
  • API Responses: Return parsed EDI as a Laravel API resource:
    return new EdiResource($parsedData);
    

4. Hybrid EDI Parsing

Combine positional parsing with other formats (e.g., CSV for delimited fields):

$header = app('edi.parser')->parse(substr($rawEdi, 0, 100), 'header_template');
$body = array_map(function ($line) {
    return str_getcsv($line);
}, explode("\n", substr($rawEdi, 100)));

Integration Tips

Laravel-Specific Adaptations

  1. Service Container Binding: Bind the EdiParser to Laravel’s container in a service provider:

    $this->app->bind('edi.parser', function ($app) {
        return new \Boda\EdiParserBundle\Parser\EdiParser(
            $app['config']['edi.templates']
        );
    });
    
  2. Configuration: Use Laravel’s config system to define templates:

    // config/edi.php
    return [
        'templates' => [
            'invoice' => [
                'header' => [
                    'IDENTIFIER' => ['start' => 0, 'length' => 2],
                    // ...
                ],
            ],
        ],
    ];
    
  3. Artisan Commands: Create a command to test EDI parsing:

    // app/Console/Commands/ParseEdi.php
    class ParseEdi extends Command {
        protected $signature = 'edi:parse {file} {template}';
        public function handle() {
            $rawEdi = file_get_contents($this->argument('file'));
            $parsed = app('edi.parser')->parse($rawEdi, $this->argument('template'));
            $this->info(json_encode($parsed, JSON_PRETTY_PRINT));
        }
    }
    
  4. Testing: Use Laravel’s testing tools to mock the parser:

    $this->app->instance('edi.parser', Mockery::mock(EdiParser::class));
    $mockParser->shouldReceive('parse')->andReturn($mockData);
    

Performance Optimizations

  • Caching Templates: Cache parsed templates in Laravel’s cache:
    $template = Cache::remember("edi.template.{$templateName}", now()->addHours(1), function () use ($templateName) {
        return config("edi.templates.{$templateName}");
    });
    
  • Streaming Large Files: Process EDI files in chunks for memory efficiency:
    $handle = fopen($filePath, 'r');
    while (!feof($handle)) {
        $chunk = fread($handle, 8192);
        $parsedChunk = app('edi.parser')->parse($chunk, $template);
        // Process chunk
    }
    

Gotchas and Tips

Pitfalls

  1. Symfony Dependency Hell:

    • The package is a Symfony bundle, so direct integration may pull in unwanted Symfony dependencies.
    • Fix: Extract only the EdiParser class and avoid including the full bundle.
  2. Template Mismatches:

    • If the EDI file doesn’t match the template, the parser may silently fail or produce incorrect data.
    • Fix: Add validation after parsing:
      $validator = Validator::make($parsed, [
          'header.IDENTIFIER' => 'required|size:2',
          'body.*.CONTENT' => 'required|string',
      ]);
      
  3. No Built-in Error Handling:

    • The package lacks robust error handling for malformed EDI.
    • Fix: Wrap the parser in a try-catch block and log errors:
      try {
          $parsed = app('edi.parser')->parse($rawEdi, $template);
      } catch (\Exception $e) {
          Log::error("EDI parsing failed: {$e->getMessage()}");
          throw new \RuntimeException('Failed to parse EDI', 0, $e);
      }
      
  4. Static Templates:

    • Templates are hardcoded, making it difficult to handle dynamic EDI formats.
    • Fix: Implement a custom template loader (e.g., from a database or API):
      $template = Template::where('name', $templateName)->first()->toArray();
      $parsed = app('edi.parser')->parse($rawEdi, $template);
      
  5. No Support for X12/EDIFACT:

    • The package only supports positional EDI, not complex standards like X12 or EDIFACT.
    • Fix: Use a dedicated library (e.g., baselink/edi) for these formats.
  6. Outdated Codebase:

    • The last release was in 2019, and the
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity