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

Technical Evaluation

Architecture Fit

  • Laravel Compatibility: The package’s stateless, regex-focused design aligns well with Laravel’s testing ecosystem (PestPHP, PHPUnit, Factories). It can be wrapped in a Laravel service or integrated into custom test helpers without violating Laravel’s conventions.
    • Example: Create a RegexDataGenerator facade or service that extends Laravel’s Factory class, enabling syntax like:
      $user = User::factory()->for($company)->create([
          'phone' => RegexDataGenerator::generate('04\d{8}'),
      ]);
      
  • Component-Based: The Lexer, Parser, and Generator classes are loosely coupled, allowing for custom randomness strategies (e.g., seeded generation for deterministic tests) or extended regex support via middleware.
  • Unicode and Edge-Case Support: Fills gaps in Laravel’s native tools (e.g., Faker lacks \X{####} Unicode support), critical for internationalized apps or domain-specific validation (e.g., Australian postcodes).
  • Test Data Isolation: Ideal for unit/integration tests where data must strictly adhere to regex rules (e.g., API payloads, database constraints) without leaking into production logic.

Integration Feasibility

  • Low Friction: Requires only Composer installation and minimal boilerplate (e.g., Lexer, Parser instantiation). Can be hidden behind a fluent interface (e.g., Regex::generate('pattern')->times(10)).
  • Laravel Service Provider: Can be bootstrapped as a singleton in AppServiceProvider, exposing a global helper:
    // config/regex.php
    'generators' => [
        'phone' => '04\d{8}',
        'postcode' => '\d{4}',
    ];
    
    // Helper function
    function regex_generate(string $pattern, int $seed = null): string {
        $lexer = new \ReverseRegex\Lexer($pattern);
        $parser = new \ReverseRegex\Parser($lexer, new \ReverseRegex\Generator\Scope(), new \ReverseRegex\Generator\Scope());
        $gen = $seed ? new \ReverseRegex\Random\SeededRandom($seed) : new \ReverseRegex\Random\SimpleRandom();
        return $parser->parse()->getResult()->generate('', $gen);
    }
    
  • PestPHP Integration: Plugs into Pest’s beforeEach or afterEach for automated test data generation:
    beforeEach(function () {
        $this->testData = [
            'valid_phone' => regex_generate('04\d{8}'),
            'invalid_phone' => regex_generate('[^04]\d{8}'),
        ];
    });
    
  • Factory Macros: Extend Laravel’s factories to support regex patterns:
    User::factory()->state(function (array $attributes) {
        return [
            'phone' => regex_generate('04\d{8}'),
        ];
    });
    

Technical Risk

Risk Mitigation Strategy Impact
PHP 8.1+ Requirement Laravel 10+ and PHP 8.1+ are now standard; upgrade path is well-documented. Low (if using LTS)
Unsupported Regex Features Document unsupported features (e.g., \p{L}, lookarounds) and provide workarounds. Medium (edge cases)
Performance Overhead Benchmark generation speed; cache compiled parsers for repeated patterns. Low (microseconds)
PHPStan Strictness Adopt phpstan-baseline incrementally; exclude non-critical files if needed. Medium (dev workflow)
Low GitHub Activity Fork and contribute fixes; treat as a vendor dependency with minimal updates. High (long-term)
Thread Safety Stateless design makes it safe for parallel test execution (e.g., Pest’s --parallel). None
Unicode Edge Cases Test with \X{####} patterns early; fall back to manual generation if needed. Medium (i18n apps)

Key Questions for Stakeholders

  1. Validation Needs:
    • "What regex patterns are critical for your test suite? Can they be expressed with this package’s supported syntax?"
    • "Are there domain-specific rules (e.g., financial formats, legal IDs) that require unsupported regex features?"
  2. PHP Version:
    • "Is upgrading to PHP 8.1+ feasible for your team? If not, would a fork with PHP 7.4 support be justified?"
  3. Testing Strategy:
    • "How do you currently generate test data? Would this replace Faker, custom scripts, or both?"
    • "Do you need deterministic (seeded) or truly random generation for CI/CD?"
  4. Maintenance:
    • "Who would own long-term maintenance (e.g., updating the fork, handling PHPStan issues)?"
    • "Are there budget/resources to contribute fixes upstream or adopt phpstan-baseline?"
  5. Performance:
    • "Will this be used for high-volume generation (e.g., load testing)? If so, have you benchmarked the parser?"
  6. Alternatives:
    • "Have you considered custom solutions (e.g., a Laravel macro) or other packages like fzaninotto/Faker with extensions?"
  7. Compliance:
    • "Are there regulatory requirements (e.g., GDPR, HIPAA) that mandate specific test data formats?"

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • PestPHP: Replace Faker in test data generation with regex-driven alternatives.
    • PHPUnit: Use in DataProvider methods or setUp() for deterministic test data.
    • Factories: Extend Illuminate\Database\Eloquent\Factories\Factory with regex macros.
    • API Testing (Pest/PHPUnit): Generate valid/invalid payloads for Laravel Sanctum, Passport, or custom API validation.
  • PHP Extensions:
    • Symfony Components: Works alongside symfony/polyfill-mbstring (already a dependency).
    • Doctrine: Compatible with Doctrine’s Lexer (used internally).
  • CI/CD:
    • GitHub Actions: Leverage existing phpstan and cs-check workflows to enforce quality gates.
    • Composer Scripts: Add post-autoload-dump hooks to validate regex patterns in test files.

Migration Path

Phase Action Items Dependencies
Assessment Audit existing test data generation (Faker, custom scripts, hardcoded values). Identify regex patterns that could be automated. QA Team, Dev Leads
Proof of Concept Implement a minimal wrapper (e.g., RegexDataGenerator service) and test with 3–5 critical patterns (e.g., phone numbers, postcodes). Compare output with current methods. 1–2 Devs, Test Suite
Integration 1. Add to composer.json and update php.ini for PHP 8.1+. 2. Create a Laravel service provider to expose helpers. 3. Replace Faker calls in factories/tests with regex equivalents. Laravel, Composer, CI Pipeline
Quality Gates Run composer phpstan and composer cs-check; address issues incrementally. Add phpstan-baseline to .gitignore if needed. PHPStan, Facile.it Coding Standard
Testing 1. Validate generated data against existing test cases. 2. Add edge-case tests (e.g., max-length strings, Unicode). 3. Benchmark performance in CI. PestPHP/PHPUnit, Load Testing Tools
Documentation Update internal wiki with: - Supported regex patterns. - Migration guide from Faker/custom scripts. - Troubleshooting (e.g., unsupported features). Tech Writers, Dev Leads
Rollout 1. Feature flag regex generation in factories (optional). 2. Deprecate old test data scripts. 3. Train team on new syntax (e.g., regex_generate()). Release Manager, DevOps

Compatibility

Component Compatibility Workarounds
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