Weave 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

nyholm/dsn

PHP DSN parser and value object for working with connection strings. Parse and normalize DSNs for common schemes, access components like scheme, host, port, user and path, and build DSNs safely for databases, queues, mailers and more.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nyholm/dsn
    

    No additional configuration is required—just autoload the package.

  2. First Use Case: Parse a DSN (Data Source Name) string into a structured array:

    use Nyholm\Dsn\Dsn;
    
    $dsn = Dsn::fromString('amqp://user:pass@host:5672/vhost?option=value');
    $parsed = $dsn->toArray();
    // Returns:
    // [
    //     'scheme' => 'amqp',
    //     'user' => 'user',
    //     'pass' => 'pass',
    //     'host' => 'host',
    //     'port' => 5672,
    //     'path' => '/vhost',
    //     'query' => ['option' => 'value'],
    // ]
    
  3. Where to Look First:

    • Source Code (minimal, ~100 lines).
    • Nyholm\Dsn\Dsn class methods: fromString(), toArray(), toString().
    • Test cases (tests/ folder) for edge cases.

Implementation Patterns

Common Workflows

  1. Parsing DSNs in Config:

    // config/broadcasting.php
    'connections' => [
        'amqp' => [
            'dsn' => env('AMQP_DSN'),
            'options' => [],
        ],
    ],
    

    Parse in a service provider:

    $dsn = Dsn::fromString(config('broadcasting.connections.amqp.dsn'));
    $config = $dsn->toArray();
    
  2. Dynamic DSN Generation:

    $dsn = (new Dsn())
        ->setScheme('redis')
        ->setHost('127.0.0.1')
        ->setPort(6379)
        ->setUser('user')
        ->setPass('pass');
    $connectionString = $dsn->toString(); // "redis://user:[email protected]:6379"
    
  3. Validation + Parsing:

    use Nyholm\Dsn\Exception\InvalidDsnException;
    
    try {
        $dsn = Dsn::fromString($input);
        // Proceed with validated DSN.
    } catch (InvalidDsnException $e) {
        abort(422, 'Invalid DSN format.');
    }
    
  4. Query Parameter Handling:

    $dsn = Dsn::fromString('postgres://user:pass@host/db?sslmode=require&connect_timeout=10');
    $query = $dsn->getQuery(); // ['sslmode' => 'require', 'connect_timeout' => '10']
    $dsn->setQuery(['sslmode' => 'disable']); // Override.
    

Integration Tips

  • Laravel Service Providers: Bind the parsed DSN to the container for reuse:
    $this->app->singleton('amqp.dsn', function () {
        return Dsn::fromString(config('amqp.dsn'));
    });
    
  • Environment Variables: Use with Laravel’s env() helper:
    $dsn = Dsn::fromString(env('RABBITMQ_DSN'));
    
  • Testing: Mock DSN parsing in unit tests:
    $mockDsn = \Mockery::mock(Dsn::class);
    $mockDsn->shouldReceive('toArray')->andReturn(['host' => 'test']);
    

Gotchas and Tips

Pitfalls

  1. Empty Components:

    • Dsn::fromString('postgres://@host') will set user and pass to null, not empty strings.
    • Fix: Explicitly check for null if your logic requires empty strings.
  2. Port Parsing:

    • Missing ports default to null (e.g., postgres://host → port = null).
    • Tip: Validate ports exist before use:
      if ($dsn->getPort() === null) {
          throw new \RuntimeException('Port is required.');
      }
      
  3. Query Parameter Overwriting:

    • setQuery() replaces all existing query parameters. Use addQuery() (if available in future versions) or merge manually:
      $query = $dsn->getQuery();
      $query['new_param'] = 'value';
      $dsn->setQuery($query);
      
  4. Scheme-Specific Validation:

    • The package parses DSNs but doesn’t validate scheme-specific rules (e.g., Redis vs. PostgreSQL).
    • Tip: Add custom validation post-parsing:
      if ($dsn->getScheme() === 'redis' && $dsn->getPort() !== 6379) {
          throw new \InvalidArgumentException('Redis must use port 6379.');
      }
      

Debugging

  • Invalid DSN Errors:

    • Catch Nyholm\Dsn\Exception\InvalidDsnException for malformed input.
    • Use Dsn::fromString() with a known valid DSN to test parsing logic.
  • Query Parameter Issues:

    • Ensure query strings use = for key-value pairs (e.g., ?key=value, not ?key).
    • URL-encode special characters (e.g., ?param=hello%20world).

Extension Points

  1. Custom DSN Schemes:

    • Extend the parser by subclassing Nyholm\Dsn\Dsn and overriding parse():
      class CustomDsn extends Dsn {
          protected function parse(string $dsn): void {
              parent::parse($dsn);
              // Add scheme-specific logic.
          }
      }
      
  2. Additional Components:

    • Add custom properties (e.g., setTls()) by extending the class:
      class ExtendedDsn extends Dsn {
          private $tls;
      
          public function setTls(bool $enabled): self {
              $this->tls = $enabled;
              return $this;
          }
      
          public function getTls(): ?bool {
              return $this->tls;
          }
      }
      
  3. Query Parameter Normalization:

    • Override getQuery() to normalize values (e.g., cast strings to booleans):
      public function getQuery(): array {
          $query = parent::getQuery();
          return array_map(function ($value) {
              return $value === 'true' ? true : $value;
          }, $query);
      }
      

Performance Tips

  • Reuse Instances: Parse DSNs once and reuse the object (e.g., in a singleton service):
    $dsn = Dsn::fromString($config['dsn']);
    // Reuse $dsn->toArray() across requests.
    
  • Avoid Repeated Parsing: Cache parsed DSNs if they’re static (e.g., in a config loader).
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.
laravel2580/idehelpers
delatbabel/viewpages
anavel/gettext
muhamadrezaar/highcharts
delatbabel/keylists
frankkessler/salesforce-laravel-oauth2-rest
anavel/foundation
wdmtech/enviricons
eii/laravel-captcha
muka/shape-reader
tdt/json
refinery29/php-cs-fixer-config
hotmeteor/eco-env
mvaliolahi/hydrate
wearede/tbcpay-php
parsnick/steak
thibaud-dauce/mattermost-php
multilinguals/apollo-client
antaresbr/collection
kr0lik/phpstan-rules