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

Data Processor Laravel Package

derafu/data-processor

Laravel/PHP data processing toolkit for defining, transforming, validating, and exporting datasets through a consistent pipeline. Provides reusable processors and helpers to normalize inputs, run rules, and produce clean output for apps, imports, and integrations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require derafu/data-processor
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Derafu\DataProcessor\DataProcessorServiceProvider::class,
    ],
    
  2. Basic Usage Define a processor class (e.g., app/Processors/UserProcessor.php):

    namespace App\Processors;
    
    use Derafu\DataProcessor\Contracts\Processor;
    
    class UserProcessor implements Processor
    {
        public function process(array $data): array
        {
            return [
                'name' => strtoupper($data['name'] ?? ''),
                'email' => strtolower($data['email'] ?? ''),
            ];
        }
    }
    
  3. First Use Case Register and run a processor via a facade:

    use Derafu\DataProcessor\Facades\DataProcessor;
    
    $processor = DataProcessor::register('user', UserProcessor::class);
    $result = $processor->process(['name' => 'John', 'email' => 'JOHN@EXAMPLE.COM']);
    // Output: ['name' => 'JOHN', 'email' => 'john@example.com']
    
  4. Key Files to Explore

    • config/data-processor.php (default config)
    • src/Contracts/Processor.php (interface definition)
    • src/Exceptions/ (custom exceptions)

Implementation Patterns

Core Workflow

  1. Processor Registration

    • Manual Registration (as shown above).
    • Automatic Discovery: Place processors in app/Processors and configure discover_processors in config/data-processor.php to true.
  2. Four-Phase Processing Implement these methods in your Processor class for full control:

    public function prepare(array $data): array { /* Pre-processing */ }
    public function validate(array $data): void { /* Validation */ }
    public function transform(array $data): array { /* Core logic */ }
    public function finalize(array $data): array { /* Post-processing */ }
    
  3. Chaining Processors

    $result = DataProcessor::chain('user', 'sanitize')
        ->process($rawData);
    
  4. Dependency Injection Bind dependencies in the processor constructor:

    public function __construct(private Logger $logger) {}
    

Integration Tips

  • Laravel Events: Trigger events after processing:
    event(new DataProcessed($result, $this));
    
  • Queue Jobs: Offload heavy processing:
    DataProcessor::dispatch('user', $data)->onQueue('processors');
    
  • API Responses: Use middleware to auto-process incoming requests:
    public function handle($request, Closure $next)
    {
        $request->merge(DataProcessor::process('api_input', $request->all()));
        return $next($request);
    }
    

Gotchas and Tips

Common Pitfalls

  1. Phase Order

    • Phases execute in this order: preparevalidatetransformfinalize.
    • Skipping validate may lead to unhandled invalid data.
  2. Circular Dependencies

    • Avoid processors that depend on each other in a loop (e.g., A calls B, which calls A).
  3. Data Mutability

    • The process() method receives a copy of the input array. Modify it carefully to avoid unintended side effects.
  4. Error Handling

    • Always catch ValidationException in validate() to provide meaningful feedback:
      public function validate(array $data): void
      {
          if (empty($data['email'])) {
              throw new ValidationException('Email is required.');
          }
      }
      

Debugging Tips

  • Enable Logging Set 'debug' => true in config/data-processor.php to log phase execution.

  • Dump Data Use DataProcessor::debug()->process($data) to inspect intermediate states.

  • Check Cache Processors are cached by default. Clear the cache (php artisan cache:clear) if changes aren’t reflected.

Extension Points

  1. Custom Phases Extend the base Processor class to add middleware-like phases:

    public function beforeTransform(array $data): array { /* Custom logic */ }
    
  2. Processor Decorators Wrap processors to add cross-cutting concerns (e.g., logging, caching):

    DataProcessor::decorate('user', function ($processor) {
        return new class($processor) implements Processor {
            public function process(array $data): array {
                Log::info('Processing started', ['data' => $data]);
                return $this->processor->process($data);
            }
        };
    });
    
  3. Dynamic Processor Resolution Use closures for runtime processor resolution:

    DataProcessor::register('dynamic', function ($data) {
        return new class($data) implements Processor { /* ... */ };
    });
    

Configuration Quirks

  • Default Processor Set 'default_processor' in config to avoid ProcessorNotFoundException.

  • Phase Skipping Disable phases via config:

    'phases' => [
        'prepare' => true,
        'validate' => false, // Skip validation
    ],
    
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