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

Php Matcher Laravel Package

coduo/php-matcher

Flexible PHP pattern-matching library for testing and validating complex data structures. Compare arrays, JSON and objects against readable expectations, with rich mismatch descriptions to pinpoint differences. Useful for API response assertions and custom validation rules.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add via Composer (PHP 8.3+ required):

    composer require coduo/php-matcher
    

    No additional configuration is needed—it’s a drop-in package.

  2. Basic Usage Import the Matcher class and define a pattern:

    use Coduo\Matcher\Matcher;
    
    $matcher = new Matcher();
    $pattern = [
        'name' => 'John Doe',
        'age'  => 30,
        'address' => [
            'street' => '123 Main St',
            'city'   => 'Anywhere'
        ]
    ];
    
    $data = [
        'name' => 'John Doe',
        'age'  => 30,
        'address' => [
            'street' => '123 Main St',
            'city'   => 'New York'
        ]
    ];
    
    $result = $matcher->match($pattern, $data);
    
  3. First Use Case: Validation Quickly validate API responses or form submissions:

    if ($matcher->match($expectedStructure, $actualData)) {
        // Data matches expected structure
    }
    

Implementation Patterns

Common Workflows

  1. Structural Validation Use match() to verify nested arrays/objects:

    $pattern = [
        'user' => [
            'id' => 1,
            'roles' => ['admin', 'editor']
        ]
    ];
    
  2. Partial Matching Use partialMatch() to ignore extra fields:

    $matcher->partialMatch($pattern, $data); // Only checks if $pattern keys exist in $data
    
  3. Dynamic Patterns Combine with Laravel’s collect() for reusable validation:

    $pattern = collect($expected)
        ->only(['id', 'name', 'metadata'])
        ->toArray();
    
  4. Integration with Laravel Requests Validate incoming requests:

    public function store(Request $request) {
        $pattern = [
            'title' => 'string',
            'price' => 'float',
            'tags'  => ['string']
        ];
        if (!$matcher->match($pattern, $request->all())) {
            return response()->json(['error' => 'Invalid data'], 400);
        }
    }
    
  5. Testing Assert data structures in PHPUnit:

    $this->assertTrue($matcher->match($expected, $actual));
    

Gotchas and Tips

Pitfalls & Debugging

  1. Strict vs. Loose Matching

    • Default behavior is strict (types and values must match).
    • Use looseMatch() to ignore types (e.g., 30 vs "30").
  2. Nested Arrays

    • Patterns must mirror the exact structure of the data.
    • Example: If $data has ['items' => [1, 2]], the pattern must include ['items' => [int, int]].
  3. Wildcards

    • Use '*' to match any value (e.g., ['name' => '*']).
    • Overuse can make patterns too permissive.
  4. Performance

    • Avoid deeply nested patterns in loops (pre-compile patterns if reused).
  5. PHP Version Compatibility

    • Breaking Change: PHP 8.3+ is now required. Ensure your Laravel project (or environment) meets this requirement.

Extension Points

  1. Custom Matchers Extend Matcher to add domain-specific rules:

    class CustomMatcher extends Matcher {
        public function matchEmail($pattern, $data) {
            return filter_var($data, FILTER_VALIDATE_EMAIL) !== false;
        }
    }
    
  2. Laravel Service Provider Bind Matcher globally:

    $this->app->singleton(Matcher::class, function () {
        return new Matcher();
    });
    

    Then inject via constructor:

    public function __construct(private Matcher $matcher) {}
    
  3. Error Handling Use getErrors() to debug mismatches:

    $matcher->match($pattern, $data);
    if ($matcher->hasErrors()) {
        dd($matcher->getErrors());
    }
    

Pro Tips

  • Combine with Laravel Validation: Use php-matcher for structural checks, then Validator for business rules.
  • Document Patterns: Store patterns in a config/matcher.php file for reusability.
  • Test Edge Cases: Validate empty arrays, null values, and mixed types explicitly.
  • Symfony 8.0 Compatibility: The package now supports Symfony 8.0 components, which may be useful if you integrate with Symfony-based tools or libraries.
  • PHP 8.5 Features: Leverage PHP 8.5 features (e.g., new attributes, typed class constants) if extending the package further.
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky