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

Pattern Matcher Laravel Package

alexeyshockov/pattern-matcher

Lightweight PHP pattern-matching utility by Alexey Shockov. Helps compare values against defined patterns and execute matching logic, enabling cleaner conditional flows than nested if/switch statements. Suitable for small libraries and framework-agnostic use.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require alexeyshockov/pattern-matcher
    

    No additional configuration is required—just autoload the package.

  2. First Use Case: Match a simple string pattern (e.g., for validation or routing):

    use AlexeyShockov\PatternMatcher\PatternMatcher;
    
    $matcher = new PatternMatcher();
    $result = $matcher->match('user/{id}', '/user/123'); // Returns ['id' => '123']
    
  3. Where to Look First:

    • Source Code (if available) for edge cases.
    • PatternMatcher class docs (if any) for syntax nuances.
    • Test cases (if provided) for real-world examples.

Implementation Patterns

Core Workflows

  1. Dynamic Route Matching:

    $routes = [
        'user/{id}' => 'UserController@show',
        'posts/{id}/comments/{comment_id}' => 'CommentController@show',
    ];
    
    $matcher = new PatternMatcher();
    foreach ($routes as $pattern => $handler) {
        if ($matcher->match($pattern, $requestUri)) {
            return $handler; // Resolve with captured params
        }
    }
    
  2. Data Validation:

    $matcher = new PatternMatcher();
    $isValid = $matcher->match('email-{user}-{domain}.com', 'email-john@example.com');
    // Returns ['user' => 'john', 'domain' => 'example'] if matched.
    
  3. Template Rendering:

    $template = 'Hello, {name}! Your ID is {id}.';
    $data = ['name' => 'Alice', 'id' => 42];
    $rendered = str_replace(
        array_keys($data),
        $matcher->extract($template, $data),
        $template
    );
    

Integration Tips

  • Laravel Routes: Extend Illuminate\Routing\Router to use PatternMatcher for custom route patterns:
    $router->matchPattern('user/{id}', function ($id) {
        return view('user.profile', compact('id'));
    });
    
  • Form Input Parsing: Sanitize and parse user input against expected patterns:
    $matcher->match('YYYY-MM-DD', $userInputDate);
    
  • API Request Validation: Validate URL paths or query strings before processing:
    $matcher->match('api/v1/{resource}/{id}', $request->path());
    

Gotchas and Tips

Pitfalls

  1. Greedy Matching: Patterns like {var*} (zero or more) may consume unintended segments. Use {var+} (one or more) or {var?} (optional) for precision.

    // Avoid:
    $matcher->match('file.{ext}', 'file.tar.gz'); // May match 'tar.gz' as {ext}
    // Fix:
    $matcher->match('file.{ext}', 'file.tar.gz', ['ext' => 'tar.gz']); // Explicit
    
  2. Case Sensitivity: The matcher is case-sensitive by default. Use strtolower() on inputs if needed:

    $matcher->match(strtolower($pattern), strtolower($input));
    
  3. Backslashes in Patterns: Escape literal { or } with \:

    $matcher->match('literal\\{curly\\}', '{curly}'); // Matches exactly
    
  4. Performance: Avoid overusing complex patterns in loops (e.g., thousands of routes). Cache compiled patterns if possible.

Debugging

  • Enable Verbose Output: Extend the class to log matches:

    $matcher = new class extends PatternMatcher {
        public function match($pattern, $input) {
            $result = parent::match($pattern, $input);
            logger()->debug("Pattern: $pattern | Input: $input | Result: " . print_r($result, true));
            return $result;
        }
    };
    
  • Test Edge Cases:

    • Empty segments: /{} vs {}.
    • Special characters: !@#$% in patterns or inputs.
    • Unicode characters (if supported).

Extension Points

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

    class EmailMatcher extends PatternMatcher {
        public function match($pattern, $input) {
            if (!filter_var($input, FILTER_VALIDATE_EMAIL)) {
                return false;
            }
            return parent::match($pattern, $input);
        }
    }
    
  2. Pre/Post-Processing: Hook into the matching logic to transform inputs/outputs:

    $matcher->match($pattern, preg_replace('/[^a-z0-9]/', '', $input));
    
  3. Integration with Laravel: Publish a config file to centralize pattern rules:

    // config/pattern-matcher.php
    'reserved' => ['admin', 'api'],
    

    Then validate against these in your matcher logic.

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