Creating a Custom Rule Parser

Implement RuleParserInterface to support application-specific rule syntax. This parser adds a contact_email shorthand and delegates other strings and arrays to the built-in parser:

namespace App\DataProcessor;

use Derafu\DataProcessor\Contract\RuleParserInterface;
use Derafu\DataProcessor\RuleParser;

final class ContactRuleParser implements RuleParserInterface
{
    public function parse(string|array $rules): array
    {
        return (new RuleParser())->parse(
            $rules === 'contact_email'
                ? 't(lowercase) s(trim) required|email'
                : $rules
        );
    }
}

Dependency Injection

Import the package YAML, then replace the parser under its interface ID:

imports:
    - { resource: '../vendor/derafu/data-processor/resources/config/data-processor-services.yaml' }

services:
    Derafu\DataProcessor\Contract\RuleParserInterface:
        class: App\DataProcessor\ContactRuleParser

The configured ProcessorInterface receives this parser. In a service that receives that processor, the shorthand works directly:

$result = $processor->process(' [email protected] ', 'contact_email');
// '[email protected]'

The parser returns categories (cast, transform, sanitize, validate) with the same structure expected by the processor. It changes how rules are expressed, not the order of the processing phases.

Explicit Construction

Without a container, supply the parser through the processor constructor:

use App\DataProcessor\ContactRuleParser;
use Derafu\DataProcessor\Processor;
use Derafu\DataProcessor\Registrar\DefaultRuleRegistrar;
use Derafu\DataProcessor\RuleRegistry;
use Derafu\DataProcessor\RuleResolver;

$registry = new RuleRegistry();
(new DefaultRuleRegistrar())->register($registry);
$processor = new Processor(new RuleResolver($registry), new ContactRuleParser());

$result = $processor->process(' [email protected] ', 'contact_email');
// '[email protected]'

Last updated on 30/10/2026 by Anonymous