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

Domain Parser Bundle Laravel Package

egyg33k/domain-parser-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require egyg33k/domain-parser-bundle
    

    Add the bundle to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3-):

    // config/bundles.php
    Egyg33k\DomainParserBundle\Egyg33kDomainParserBundle::class => ['all' => true],
    

    Or (Symfony 3-):

    // AppKernel.php
    new Egyg33k\DomainParserBundle\Egyg33kDomainParserBundle(),
    
  2. First Use Case: Inject the parser via dependency injection (recommended) or fetch from the container:

    use Egyg33k\DomainParserBundle\Parser\DomainParser;
    
    // In a controller/service:
    public function __construct(DomainParser $parser) {
        $this->parser = $parser;
    }
    
    // Parse a URL string:
    $url = $this->parser->parseUrl('https://user:pass@example.com/path?query=1#frag');
    

Implementation Patterns

Core Workflows

  1. URL Parsing in Controllers:

    public function handleRequest(Request $request, DomainParser $parser) {
        $url = $parser->parseUrl($request->getUri());
        $domain = $url->getHost(); // e.g., 'example.com'
        // Use domain for logic (e.g., routing, analytics).
    }
    
  2. Validation & Sanitization:

    $url = $parser->parseUrl($userInput);
    if (!$url->isValid()) {
        throw new \InvalidArgumentException('Invalid URL');
    }
    
  3. Extracting Components:

    $url = $parser->parseUrl('https://sub.example.com:8080/path/to/page');
    $components = [
        'scheme' => $url->getScheme(),      // 'https'
        'host'   => $url->getHost(),        // 'sub.example.com'
        'port'   => $url->getPort(),        // 8080
        'path'   => $url->getPath(),        // '/path/to/page'
        'query'  => $url->getQuery(),       // null
        'fragment' => $url->getFragment(), // null
    ];
    
  4. Rebuilding URLs:

    $url = $parser->parseUrl('https://example.com');
    $url->setPath('/new-path')->setQuery(['param' => 'value']);
    $rebuiltUrl = $url->__toString(); // 'https://example.com/new-path?param=value'
    

Integration Tips

  • Symfony Forms: Use the parser to validate URL fields:
    $builder->add('website', UrlType::class, [
        'constraints' => [
            new Url(),
            new Callback([$parser, 'validateUrl']),
        ],
    ]);
    
  • Event Listeners: Parse URLs in KernelEvents::REQUEST to inspect incoming requests:
    public function onKernelRequest(GetResponseEvent $event) {
        $url = $this->parser->parseUrl($event->getRequest()->getUri());
        // Log or modify request based on parsed components.
    }
    
  • API Responses: Normalize URLs in JSON responses:
    return $this->json([
        'url' => $this->parser->parseUrl($rawUrl)->__toString(),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony 3+:

    • The bundle was last updated in 2016 and may not support modern Symfony versions (4/5/6). Test thoroughly or fork the bundle.
    • Symfony Flex: The bundle lacks autoloading configuration for Flex. Manually add it to composer.json:
      "extra": {
          "symfony": {
              "allow-overload": true
          }
      }
      
  2. Underlying Library Limitations:

    • The original php-domain-parser has known issues:
      • IDN (Internationalized Domain Names): May not handle non-ASCII domains (e.g., 例子.测试) correctly.
      • Edge Cases: Malformed URLs (e.g., http:///, http://example.com:) may throw unexpected errors.
    • Workaround: Pre-validate URLs with a regex or use filter_var($url, FILTER_VALIDATE_URL).
  3. Container Access:

    • Avoid direct container access ($this->container->get()) in modern Symfony. Prefer dependency injection or the ContainerAware trait (deprecated in Symfony 4+).
  4. Performance:

    • Parsing is lightweight, but avoid parsing the same URL repeatedly. Cache results if needed:
      $cacheKey = 'url_'.$urlString;
      $parsedUrl = $cache->get($cacheKey) ?: $this->parser->parseUrl($urlString);
      

Debugging

  • Inspect Parsed Components:
    $url = $parser->parseUrl('http://user:pass@example.com:8080/path');
    var_dump([
        'scheme' => $url->getScheme(),
        'user'   => $url->getUser(),
        'pass'   => $url->getPass(),
        'host'   => $url->getHost(),
        'port'   => $url->getPort(),
        'path'   => $url->getPath(),
        'query'  => $url->getQuery(),
        'fragment' => $url->getFragment(),
    ]);
    
  • Check for null Values: The parser may return null for missing components (e.g., getPort() returns null for default ports like 80 or 443).

Extension Points

  1. Custom Parsing Logic: Extend the parser by creating a decorator:

    class CustomDomainParser implements DomainParserInterface {
        private $decorated;
    
        public function __construct(DomainParser $parser) {
            $this->decorated = $parser;
        }
    
        public function parseUrl($url) {
            $parsed = $this->decorated->parseUrl($url);
            // Add custom logic (e.g., normalize hostnames).
            return $parsed;
        }
    }
    

    Register the decorator in services.yaml:

    services:
        App\Service\CustomDomainParser:
            decorates: 'egyg33k.domainParser'
            arguments: ['@egyg33k.domainParser']
    
  2. Override Default Behavior: The bundle uses Egyg33k\DomainParserBundle\Parser\DomainParser, which wraps jeremykendall/php-domain-parser. Replace the service definition to use a custom implementation:

    services:
        egyg33k.domainParser:
            class: App\Parser\CustomDomainParser
            arguments:
                - '@service_id_if_needed'
    
  3. Testing: Mock the parser in tests to avoid external dependencies:

    $mockParser = $this->createMock(DomainParserInterface::class);
    $mockParser->method('parseUrl')->willReturn($expectedUrlObject);
    $this->container->set('egyg33k.domainParser', $mockParser);
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony