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

Reverse Regex Laravel Package

ilario-pierbattista/reverse-regex

Generate example strings from regular expressions in PHP—useful for test data for forms, databases, and regex validation. Includes lexer/parser and random generators, supports literals, groups, classes, ranges, and quantifiers (with some Unicode/PCRE limits).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ilario-pierbattista/reverse-regex
    

    Ensure your project uses PHP 8.1+ (hard requirement).

  2. Basic Usage:

    use ReverseRegex\Lexer;
    use ReverseRegex\Random\SimpleRandom;
    use ReverseRegex\Parser;
    use ReverseRegex\Generator\Scope;
    
    $lexer = new Lexer('[A-Z]{5}-\d{4}'); // Example: "ABCDE-1234"
    $random = new SimpleRandom(12345);    // Seed for reproducibility
    $parser = new Parser($lexer, new Scope(), new Scope());
    $result = $parser->parse()->getResult()->generate('', $random);
    
    echo $result; // Outputs: "G7HJK-9012" (varies with seed)
    
  3. First Use Case: Generate test data for Laravel validation rules. For example, if your User model validates license_number as /^[A-Z]{3}-\d{4}$/, use:

    $licenseRegex = new Lexer('^[A-Z]{3}-\\d{4}$');
    $licenseData = $parser->parse()->getResult()->generate('', $random);
    

Where to Look First

  • Examples: Pre-built use cases (e.g., Australian phone numbers, postcodes).
  • Regex Support Table: Verify if your regex syntax is compatible.
  • SimpleRandom Class: For seeded reproducibility in tests.

Implementation Patterns

Core Workflow

  1. Define Regex: Escape meta-characters (e.g., \d for digits, \[ for literal [). Use supported quantifiers ({n}, {n,m}).

    $regex = new Lexer('\\d{3}-\\d{2}-\\d{4}'); // SSN-like format
    
  2. Configure Generator:

    • Use SimpleRandom for reproducibility (seed with a constant).
    • For unbounded quantifiers (e.g., *, +), ensure SimpleRandom is updated (fixed in v0.6.0).
  3. Generate Data:

    $parser = new Parser($regex, new Scope(), new Scope());
    $result = $parser->parse()->getResult()->generate('', $random);
    
  4. Integrate with Laravel:

    • Factories: Extend DatabaseFactory to generate regex-compliant data:
      use ReverseRegex\Lexer;
      use ReverseRegex\Random\SimpleRandom;
      
      public function definition()
      {
          $lexer = new Lexer('[A-Za-z0-9]{10}');
          $random = new SimpleRandom(42);
          return [
              'token' => (new Parser($lexer, new Scope(), new Scope()))
                  ->parse()
                  ->getResult()
                  ->generate('', $random),
          ];
      }
      
    • PestPHP: Use in test setups:
      beforeEach(function () {
          $this->testData = (new Parser(
              new Lexer('\\d{4}-\\d{2}-\\d{2}'),
              new Scope(),
              new Scope()
          ))->parse()->getResult()->generate('', new SimpleRandom(123));
      });
      

Advanced Patterns

  1. Unicode Support: Generate emojis or non-ASCII text:

    $lexer = new Lexer('\\X{1F600}-\\X{1F64F}'); // Emoji range
    
  2. Nested Groups: Handle complex patterns like:

    $lexer = new Lexer('([A-Za-z]{3}-)?\\d{5}'); // Optional prefix
    
  3. Custom Randomness: Extend SimpleRandom for domain-specific logic (e.g., biased distributions):

    class BiasedRandom extends SimpleRandom {
        public function generate(int $min, int $max): int {
            // Custom logic (e.g., 70% chance for min value)
            return $min === 0 ? 0 : parent::generate($min, $max);
        }
    }
    
  4. Batch Generation: Loop to generate multiple values:

    $results = [];
    for ($i = 0; $i < 10; $i++) {
        $results[] = $parser->parse()->getResult()->generate('', $random);
    }
    
  5. Integration with Laravel Testing: Create a helper trait for reusable generation:

    trait GeneratesRegexData {
        protected function generate(string $regex, int $seed = 12345): string {
            $lexer = new Lexer($regex);
            $random = new SimpleRandom($seed);
            return (new Parser($lexer, new Scope(), new Scope()))
                ->parse()
                ->getResult()
                ->generate('', $random);
        }
    }
    

    Use in tests:

    use GeneratesRegexData;
    
    it('validates license numbers', function () {
        $license = $this->generate('^[A-Z]{3}-\\d{4}$');
        // Assertions...
    });
    

Gotchas and Tips

Pitfalls

  1. Unsupported Regex Features:

    • Avoid: \p{L} (Unicode properties), lookarounds, backreferences, or conditional regex.
    • Workaround: Pre-process regex to remove unsupported parts or use simpler patterns.
  2. Quantifier Behavior:

    • * and + can generate extremely long strings (up to PHP_INT_MAX). Use explicit bounds (e.g., {0,10}) for safety.
    • Fix: Update SimpleRandom to handle unbounded quantifiers (resolved in v0.6.0).
  3. Meta-Character Escaping:

    • Always escape regex meta-characters twice (e.g., \\d for literal d). The package expects regex syntax, not string literals.
    • Example: To match a literal [, use \\\[.
  4. Unicode Limitations:

    • \p{...} (Unicode properties) are not supported. Use \X{####} for specific codepoints.
    • Workaround: Manually construct ranges (e.g., [\X{0041}-\X{005A}] for [A-Z]).
  5. PHP 8.1+ Requirement:

    • Blocker: Projects on PHP 7.4/8.0 cannot use this package. Plan a migration if needed.
  6. Seeding Issues:

    • SimpleRandom uses a fixed seed for reproducibility. If tests fail intermittently, ensure the seed is consistent across runs.
  7. Performance:

    • Complex regex with deep nesting may slow down generation. Benchmark for large batches (e.g., 10,000+ items).

Debugging Tips

  1. Validate Regex First: Test your regex in a tool like Regex101 to ensure it matches expected patterns before using the package.

  2. Check Parser Output: Use var_dump($parser->parse()) to inspect the parsed structure if generation fails.

  3. Handle Exceptions: Wrap generation in a try-catch for unsupported syntax:

    try {
        $result = $parser->parse()->getResult()->generate('', $random);
    } catch (\Exception $e) {
        // Fallback to default data or rethrow
    }
    
  4. CI/CD Integration: Add Composer scripts to enforce code quality (as in the package):

    {
        "scripts": {
            "test:regex": "vendor/bin/phpunit --filter RegexTest",
            "cs-check": "vendor/bin/php-cs-fixer fix --dry-run"
        }
    }
    

Extension Points

  1. Custom Random Generators: Extend SimpleRandom to implement domain-specific logic (e.g., biased distributions, custom probability maps).

  2. Post-Processing: Chain generation with Laravel’s Str::of() or Str::random() for additional transformations:

    $generated = $parser->parse()->getResult()->generate('', $random);
    $processed = Str::upper($generated); // Example: Force uppercase
    
  3. Laravel Service Provider: Bind the package to the container for global access:

    $this->app->bind(GeneratorInterface::class, function ($app) {
        return (new Parser(
            new Lexer('[A-Za-z0-9]{10}'),
            new Scope(),
            new Scope()
        ))->parse()->getResult();
    });
    
  4. Testing Utilities: Create a PestPHP plugin or PHPUnit extension to auto-generate regex data in test methods:

    // In Pest.php
    Pest::
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata