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

Dsn Laravel Package

enqueue/dsn

Parse and work with Enqueue DSNs (connection strings) for message queue transports. Lightweight PHP utility to read DSN options and parameters, used across the Enqueue ecosystem. MIT licensed.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require enqueue/dsn
    

    Add to composer.json if not using autoloading:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Enqueue\\Dsn\\": "vendor/enqueue/dsn/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case Parse a DSN string (e.g., amqp://guest:guest@localhost:5672/%2f):

    use Enqueue\Dsn\AmqpDsn;
    use Enqueue\Dsn\Dsn;
    
    $dsn = new Dsn('amqp://guest:guest@localhost:5672/%2f');
    $parsed = $dsn->parse(); // Returns an array of parsed components
    
  3. Where to Look First

    • README for basic usage.
    • src/Enqueue/Dsn/ for core classes (AmqpDsn, Dsn, SqsDsn, etc.).
    • Tests in tests/ for edge cases and validation.

Implementation Patterns

Usage Patterns

  1. Parsing DSNs

    $dsn = new Dsn('redis://user:pass@host:6379/0');
    $parsed = $dsn->parse();
    // Returns: ['scheme' => 'redis', 'user' => 'user', 'pass' => 'pass', ...]
    
  2. Protocol-Specific Parsing Use protocol-specific classes for stricter validation:

    $amqpDsn = new AmqpDsn('amqp://guest:guest@localhost:5672/%2f');
    $parsed = $amqpDsn->parse(); // Validates AMQP-specific rules (e.g., vhost)
    
  3. Integration with Enqueue Clients Combine with php-enqueue/amqp-ext or php-enqueue/sqs for broker connections:

    use Enqueue\AmqpExt\AmqpConnectionFactory;
    use Enqueue\Client\Producer;
    
    $dsn = new Dsn('amqp://guest:guest@localhost:5672/%2f');
    $connectionFactory = new AmqpConnectionFactory($dsn->parse());
    $producer = new Producer($connectionFactory->createConnection());
    
  4. Dynamic DSN Handling Parse DSNs from config (e.g., .env):

    $dsnString = env('QUEUE_CONNECTION_DSN');
    $dsn = new Dsn($dsnString);
    $config = $dsn->parse(); // Use in Laravel's queue config
    
  5. Validation and Error Handling Catch parsing errors gracefully:

    try {
        $dsn = new Dsn('invalid-dsn');
        $parsed = $dsn->parse();
    } catch (\InvalidArgumentException $e) {
        Log::error("Invalid DSN: " . $e->getMessage());
    }
    

Workflows

  1. Laravel Queue Configuration Replace hardcoded DSNs in config/queue.php with dynamic parsing:

    $dsn = new Dsn(env('QUEUE_CONNECTION_DSN'));
    $config['connections']['amqp'] = [
        'driver' => 'amqp',
        'dsn' => $dsn->parse(),
    ];
    
  2. Environment-Specific DSNs Use different DSNs per environment (e.g., local, staging, production):

    $env = env('APP_ENV');
    $dsnString = config("queue.dsn.{$env}");
    $dsn = new Dsn($dsnString);
    
  3. Testing Mock DSN parsing in unit tests:

    $mockDsn = $this->createMock(Dsn::class);
    $mockDsn->method('parse')->willReturn(['scheme' => 'amqp', 'host' => 'localhost']);
    
  4. CLI Tools Build CLI tools to validate DSNs before deployment:

    php artisan queue:validate-dsn --dsn="amqp://user:pass@host:5672/vhost"
    

Integration Tips

  1. Leverage Laravel Service Providers Bind the DSN parser in a service provider:

    $this->app->singleton(Dsn::class, function ($app) {
        return new Dsn(env('QUEUE_CONNECTION_DSN'));
    });
    
  2. Extend for Custom Protocols Create a custom DSN class by extending Enqueue\Dsn\Dsn:

    class CustomDsn extends Dsn {
        protected function parseSchemeSpecificPart($schemeSpecificPart) {
            // Custom parsing logic
        }
    }
    
  3. Combine with Laravel Queues Use parsed DSNs to configure Laravel's queue drivers dynamically:

    $parsed = (new Dsn(env('QUEUE_CONNECTION_DSN')))->parse();
    Queue::extend('custom', function () use ($parsed) {
        return new CustomQueueDriver($parsed);
    });
    
  4. Logging and Monitoring Log parsed DSNs for debugging:

    Log::debug('Parsed DSN', $dsn->parse());
    

Gotchas and Tips

Pitfalls

  1. Deprecated Protocol Support

    • The package was last updated in 2018 and may not support newer protocols (e.g., RabbitMQ 3.10+ features).
    • Workaround: Extend the parser or use a community fork if needed.
  2. URL Encoding Issues

    • DSNs with encoded characters (e.g., %2f for /) may not parse correctly in all cases.
    • Fix: Manually decode or use rawurldecode():
      $dsnString = rawurldecode($dsnString);
      
  3. No Built-in Connection Testing

    • The package parses DSNs but doesn’t validate connectivity.
    • Tip: Use Enqueue\AmqpExt\AmqpConnectionFactory or php-amqplib to test connections post-parsing.
  4. Limited Error Messages

    • Parsing errors may lack context (e.g., "Invalid DSN" without specifying which part failed).
    • Debugging Tip: Log the raw DSN and parsed components for troubleshooting:
      try {
          $parsed = $dsn->parse();
      } catch (\Exception $e) {
          Log::error("DSN: {$dsn->getDsn()}, Error: " . $e->getMessage());
      }
      
  5. No Support for TLS/SSL Options

    • The parser doesn’t handle ?tls or ?ssl query parameters natively.
    • Workaround: Parse manually or extend the class:
      $query = parse_url($dsn->getDsn(), PHP_URL_QUERY);
      parse_str($query, $queryParams);
      if (isset($queryParams['tls'])) {
          $parsed['tls'] = filter_var($queryParams['tls'], FILTER_VALIDATE_BOOLEAN);
      }
      

Debugging

  1. Validate DSN Structure Use parse_url() to inspect the DSN before parsing:

    $parts = parse_url('amqp://user:pass@host:5672/vhost?heartbeat=30');
    // Debug each part: $parts['scheme'], $parts['host'], etc.
    
  2. Check for Typos Common typos in DSNs:

    • Missing :// (e.g., amqp:user@host → invalid).
    • Incorrect port format (e.g., host:5672 vs. host:5672/).
    • Fix: Use a regex to validate basic structure:
      if (!preg_match('/^[a-z]+:\/\/.+$/', $dsnString)) {
          throw new \InvalidArgumentException("Invalid DSN format");
      }
      
  3. Protocol-Specific Quirks

    • AMQP: Vhosts must be URL-encoded (e.g., %2f for /).
    • Redis: Ports are often omitted (e.g., redis://host defaults to 6379).
    • SQS: Regions are part of the host (e.g., sqs.us-east-1.amazonaws.com).

Config Quirks

  1. Default Values The parser doesn’t provide defaults for missing components (e.g., user, pass, port).
    • Tip: Set defaults post-parsing:
      $parsed = $dsn->parse();
      $parsed['port'] = $parsed['port'] ?? (($parsed['scheme'] === 'redis') ?
      
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.
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed