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

Bdf Dsn Laravel Package

b2pweb/bdf-dsn

Simple PHP DSN parser for database connection strings. Parse URL-style (mysql://user:pass@host/db?timeout=3) and PDO DSN format (mysql:host=...;dbname=...;timeout=...) into an easy-to-use object/array.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require b2pweb/bdf-dsn
    

    Add the package to your composer.json under require.

  2. First Use Case Parse a DSN string into an array for further processing:

    use Bdf\Dsn\Dsn;
    
    $parsedDsn = Dsn::parse('mysql://username:password@localhost:3306/database');
    $arrayOutput = $parsedDsn->toArray();
    // Output: ['scheme' => 'mysql', 'user' => 'username', 'pass' => 'password', 'host' => 'localhost', 'port' => 3306, 'path' => 'database']
    
  3. Where to Look First

    • README: For basic usage examples and supported formats.
    • Source Code: src/Dsn.php to understand parsing logic and available methods.
    • Tests: tests/DsnTest.php for examples of supported DSN formats and edge cases.

Implementation Patterns

Usage Patterns

  1. Parsing DSNs for Dynamic Database Connections Use the package to parse DSNs from environment variables or user input, then dynamically configure Laravel’s database connections:

    $dsnString = env('CUSTOM_DB_DSN');
    $parsedDsn = Dsn::parse($dsnString);
    
    $connectionConfig = [
        'driver'   => str_replace('://', '', $parsedDsn->getScheme()),
        'host'     => $parsedDsn->getHost(),
        'port'     => $parsedDsn->getPort(),
        'database' => ltrim($parsedDsn->getPath(), '/'),
        'username' => $parsedDsn->getUser(),
        'password' => $parsedDsn->getPass(),
    ];
    
    config(['database.connections.custom_db' => $connectionConfig]);
    
  2. Validation of User-Provided DSNs Validate DSNs submitted via forms or APIs before processing:

    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make(['dsn' => $request->input('dsn')], [
        'dsn' => function ($attribute, $value, $fail) {
            try {
                Dsn::parse($value);
            } catch (\InvalidArgumentException $e) {
                $fail('The DSN format is invalid.');
            }
        },
    ]);
    
  3. Normalizing DSN Formats Convert between different DSN formats (e.g., mysql:// to mysql:host=...) for consistency:

    $urlStyleDsn = 'mysql://user:pass@localhost/db';
    $parsedUrlDsn = Dsn::parse($urlStyleDsn);
    
    $pdoStyleDsn = sprintf(
        '%s:host=%s;port=%d;dbname=%s',
        $parsedUrlDsn->getScheme(),
        $parsedUrlDsn->getHost(),
        $parsedUrlDsn->getPort(),
        ltrim($parsedUrlDsn->getPath(), '/')
    );
    
  4. Extracting DSN Components for Custom Logic Use parsed components to build custom configurations or workflows:

    $dsn = Dsn::parse('postgres://user:pass@localhost:5432/mydb');
    
    if ($dsn->getScheme() === 'postgres') {
        // Custom logic for PostgreSQL connections
        $this->configurePostgresConnection($dsn);
    }
    

Workflows

  1. Environment-Based Configuration Parse DSNs from environment variables in your .env file and dynamically configure Laravel’s database connections:

    $dsn = Dsn::parse(env('DB_DSN'));
    config(['database.connections.mysql' => [
        'driver'   => 'mysql',
        'host'     => $dsn->getHost(),
        'port'     => $dsn->getPort(),
        'database' => ltrim($dsn->getPath(), '/'),
        'username' => $dsn->getUser(),
        'password' => $dsn->getPass(),
    ]]);
    
  2. Admin Panel for Database Configuration Allow administrators to input DSNs in a form, parse and validate them, then save to the database:

    $request->validate([
        'dsn' => 'required|dsn', // Custom validation rule
    ]);
    
    $parsedDsn = Dsn::parse($request->input('dsn'));
    $databaseConfig = $this->mapDsnToConfig($parsedDsn);
    DatabaseConfig::create($databaseConfig);
    
  3. Migration Scripts Parse DSNs from migration files or legacy configurations to update them to a standardized format:

    $legacyDsn = 'mysql:host=oldhost;dbname=mydb';
    $parsedLegacyDsn = Dsn::parse($legacyDsn);
    
    $updatedDsn = sprintf(
        '%s://%s:%s@%s/%s',
        $parsedLegacyDsn->getScheme(),
        $parsedLegacyDsn->getUser() ?? 'root',
        $parsedLegacyDsn->getPass() ?? '',
        $parsedLegacyDsn->getHost(),
        ltrim($parsedLegacyDsn->getPath(), '/')
    );
    

Integration Tips

  1. Combine with Laravel’s parseDSN Use this package for initial parsing and validation, then fall back to Laravel’s native parseDSN for advanced features:

    use Illuminate\Database\Connectors\ConnectionFactory;
    
    $factory = new ConnectionFactory();
    $config = $factory->parseDSN($dsnString); // Laravel's native parser
    
  2. Custom Validation Rules Create a reusable validation rule for DSNs:

    use Illuminate\Validation\Rule;
    
    Validator::extend('dsn', function ($attribute, $value, $parameters, $validator) {
        try {
            Dsn::parse($value);
            return true;
        } catch (\InvalidArgumentException $e) {
            return false;
        }
    });
    
    // Usage
    $request->validate(['dsn' => 'required|dsn']);
    
  3. Service Provider Integration Register a service provider to handle DSN parsing across your application:

    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Bdf\Dsn\Dsn;
    
    class DsnServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton('dsn.parser', function () {
                return new class {
                    public function parse(string $dsn): array
                    {
                        return Dsn::parse($dsn)->toArray();
                    }
                };
            });
        }
    }
    
  4. Testing DSN Parsing Write tests to ensure DSNs are parsed correctly in your application:

    use Bdf\Dsn\Dsn;
    use PHPUnit\Framework\TestCase;
    
    class DsnParserTest extends TestCase
    {
        public function testParseMysqlDsn()
        {
            $dsn = Dsn::parse('mysql://user:pass@localhost:3306/db');
            $this->assertEquals('mysql', $dsn->getScheme());
            $this->assertEquals('user', $dsn->getUser());
            $this->assertEquals('pass', $dsn->getPass());
            $this->assertEquals('localhost', $dsn->getHost());
            $this->assertEquals(3306, $dsn->getPort());
            $this->assertEquals('db', ltrim($dsn->getPath(), '/'));
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Limited DSN Format Support

    • The package primarily supports URL-style DSNs (e.g., mysql://user:pass@host/db) and basic PDO-style DSNs (e.g., mysql:host=host).
    • Gotcha: It may not fully support all PDO DSN components like unix_socket, charset, or advanced options.
    • Workaround: Pre-process DSNs or use Laravel’s parseDSN for unsupported formats.
  2. No Built-in Error Handling

    • The package throws InvalidArgumentException for malformed DSNs, but it lacks detailed error messages.
    • Gotcha: Catching exceptions may require additional logic to provide user-friendly feedback.
    • Workaround: Wrap parsing in a try-catch block and handle errors gracefully:
      try {
          $dsn = Dsn::parse($dsnString);
      } catch (\InvalidArgumentException $e) {
          throw new \Exception('Invalid DSN format. Expected format: mysql://user:pass@host/db or mysql:host=host;dbname=db');
      }
      
  3. Case Sensitivity in Scheme Parsing

    • The scheme (e.g., mysql, postgres)
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.
cadot.eu/make
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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