PHP code example of dolmatovdev / laravel-x12-parser

1. Go to this page and download the library: Download dolmatovdev/laravel-x12-parser library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dolmatovdev / laravel-x12-parser example snippets


return [
    'delimiters' => [
        'segment' => '~',
        'element' => '*',
        'sub_element' => '>',
    ],

    /*
    |--------------------------------------------------------------------------
    | Transaction-Specific Delimiters
    |--------------------------------------------------------------------------
    |
    | Custom delimiters for specific transaction types.
    | If a transaction type is not listed here, the default delimiters will be used.
    |
    */
    'transaction_delimiters' => [
        // Example: Custom delimiters for 270 transactions
        // '270' => [
        //     'segment' => '~',
        //     'element' => '*',
        //     'sub_element' => '>',
        // ],
        
        // Example: Different delimiters for 837 transactions
        // '837' => [
        //     'segment' => '|',
        //     'element' => '^',
        //     'sub_element' => '&',
        // ],
        
        // Example: Legacy format with different delimiters
        // 'legacy_270' => [
        //     'segment' => '\r\n',
        //     'element' => ',',
        //     'sub_element' => ';',
        // ],
    ],
    
    'transaction_types' => [
        '270' => \DolmatovDev\X12Parser\Validators\Validator270::class,
    ],
    
    'file_storage' => [
        'default_path' => storage_path('ansi'),
        'permissions' => 0644,
        'backup_enabled' => true,
    ],

    /*
    |--------------------------------------------------------------------------
    | File Naming Configuration
    |--------------------------------------------------------------------------
    |
    | Configuration for file naming patterns and conventions.
    | You can specify custom naming patterns for different transaction types.
    |
    */
    'file_naming' => [
        // Default file naming pattern
        'default_pattern' => 'x12_{transaction_type}_{timestamp}.txt',
        
        // Custom naming patterns for specific transaction types
        'transaction_patterns' => [
            // Example: Custom naming for 270 transactions
            // '270' => 'eligibility_inquiry_{timestamp}_{random}.txt',
            
            // Example: Custom naming for 837 transactions
            // '837' => 'claim_{provider_id}_{date}_{sequence}.txt',
            
            // Example: Custom naming for 835 transactions
            // '835' => 'payment_remittance_{payer_id}_{date}.txt',
        ],
        
        // Available placeholders for file naming
        'placeholders' => [
            '{transaction_type}' => 'The transaction type (e.g., 270, 837)',
            '{timestamp}' => 'Current timestamp in Y-m-d_H-i-s format',
            '{date}' => 'Current date in Y-m-d format',
            '{time}' => 'Current time in H-i-s format',
            '{random}' => 'Random 6-digit number',
            '{sequence}' => 'Sequential number (increments per file)',
            '{provider_id}' => 'Provider ID from the data (if available)',
            '{payer_id}' => 'Payer ID from the data (if available)',
            '{member_id}' => 'Member ID from the data (if available)',
        ],
        
        // File extension
        'extension' => '.txt',
        
        // Whether to use custom naming by default
        'use_custom_naming' => false,
    ],
    
    'validation' => [
        'strict_mode' => true,
        'allow_warnings' => true,
        'max_segments' => 10000,
        'max_segment_length' => 1000,
    ],

    'logging' => [
        'enabled' => false,
        'level' => 'info',
    ],

    'cache' => [
        'enabled' => false,
        'ttl' => 3600,
    ],
];

use DolmatovDev\X12Parser\Facades\X12Parser;

// Parse X12 file to array
$data = X12Parser::parseFile('path/to/file.txt');

// Parse X12 file to JSON
$json = X12Parser::parseFileToJson('path/to/file.txt');

// Build X12 file from JSON
$x12Content = X12Parser::buildFromJson($jsonData);

// Save X12 content to file
X12Parser::saveToFile($x12Content, 'output.txt');

// Validate file without parsing
$result = X12Parser::validateFile('path/to/file.txt');
if ($result->isSuccessful()) {
    echo "File is valid!";
} else {
    echo "Validation errors: " . implode(', ', $result->errors);
}

// Build and save with auto-generated filename
$filePath = X12Parser::buildAndSaveWithAutoName($jsonData, '270');

// Get supported transaction types
$types = X12Parser::getSupportedTransactionTypes();

use DolmatovDev\X12Parser\Services\AnsiParserService;
use DolmatovDev\X12Parser\DTO\Eligibility270DTO;

class X12Controller extends Controller
{
    public function __construct(
        private AnsiParserService $ansiService
    ) {}

    public function parseFile(Request $request)
    {
        $filePath = $request->file('x12_file')->getPathname();
        
        try {
            $data = $this->ansiService->parseFile($filePath);
            return response()->json($data);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }

    public function buildFile(Request $request)
    {
        $jsonData = $request->input('data');
        
        try {
            $ansiContent = $this->ansiService->buildFromJson($jsonData);
            return response($ansiContent)->header('Content-Type', 'text/plain');
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }
}

use DolmatovDev\X12Parser\DTO\Eligibility270DTO;
use DolmatovDev\X12Parser\Builder\X12Builder;

// Create DTO from array
$dto = Eligibility270DTO::fromArray([
    'subscriber_id' => '123456789',
    'subscriber_first_name' => 'John',
    'subscriber_last_name' => 'Doe',
    'subscriber_date_of_birth' => '19800101',
    'subscriber_gender' => 'M',
    'inquiries' => [
        ['service_type_code' => '30']
    ]
]);

// Build ANSI content from DTO
$builder = new X12Builder();
$ansiContent = $builder->buildFrom270DTO($dto);

use DolmatovDev\X12Parser\Facades\X12Parser;

// Parse with custom delimiters for a specific transaction type
$result = X12Parser::parseFromFile('path/to/legacy_file.txt', '270');

// Build with custom delimiters
$ansiContent = X12Parser::buildFromJson($jsonData, '270', '270');

// Using the Parser directly with custom delimiters
use DolmatovDev\X12Parser\Parser;

$parser = new Parser();
$parser->setDelimitersForTransaction('270'); // Uses config from x12-parser.transaction_delimiters.270
$result = $parser->parseContent($content, '270');

// Set custom delimiters manually
$parser->setDelimiters([
    'segment' => '|',
    'element' => '^',
    'sub_element' => '&',
]);

use DolmatovDev\X12Parser\Facades\X12Parser;

// Build and save with auto-generated filename
$filePath = X12Parser::buildAndSaveWithAutoName($jsonData, '270');

// Build and save with custom naming pattern
$filePath = X12Parser::buildAndSaveWithAutoName(
    $jsonData, 
    '270', 
    ['provider_id' => '12345', 'member_id' => '67890'],
    'claim_{provider_id}_{member_id}_{timestamp}.txt'
);

// Generate filename only
$fileName = X12Parser::generateFileName('270', ['provider_id' => '12345']);

// Get available placeholders
$placeholders = X12Parser::getAvailablePlaceholders();

// Reset sequence counter
X12Parser::resetSequence();

// Set sequence counter
X12Parser::setSequence(1000);

use DolmatovDev\X12Parser\Parser;
use DolmatovDev\X12Parser\Validators\Validator270;

// Test parser
$parser = new Parser();
$result = $parser->parseContent('ST*270*0001~');
$this->assertTrue($result->isSuccessful());

// Test validator
$validator = new Validator270();
$segments = ['ST*270*0001', 'SE*2*0001'];
$result = $validator->validate($segments);
$this->assertFalse($result->isSuccessful()); // Missing 

$result = X12Parser::validateFile('file.txt');

if ($result->isSuccessful()) {
    echo "File is valid!";
} else {
    echo "Errors: " . implode(', ', $result->errors);
    echo "Warnings: " . implode(', ', $result->warnings);
}

namespace DolmatovDev\X12Parser\Validators;

use DolmatovDev\X12Parser\DTO\ValidationResult;

class Validator271 implements AnsiValidatorInterface
{
    public function validate(array $segments): ValidationResult
    {
        // Implement validation logic
    }

    public function getTransactionType(): string
    {
        return '271';
    }

    public function getRequiredSegments(): array
    {
        return ['ISA', 'GS', 'ST', 'SE', 'GE', 'IEA'];
    }

    public function getOptionalSegments(): array
    {
        return [];
    }
}

// In config/x12-parser.php
    'transaction_types' => [
        '270' => \DolmatovDev\X12Parser\Validators\Validator270::class,
        '271' => \DolmatovDev\X12Parser\Validators\Validator271::class,
    ],
bash
php artisan vendor:publish --tag=x12-parser-config
bash
php artisan vendor:publish --tag=x12-parser-stubs