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

Php Domain Parser Laravel Package

jeremykendall/php-domain-parser

Parse, validate, and normalize domains, subdomains, and suffixes using the Public Suffix List. Extract registrable domain vs. subdomain, handle IDNs and edge cases, and keep parsing rules current via PSL updates—ideal for URL processing, cookies, and security checks.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer

    composer require jeremykendall/php-domain-parser
    
    • No additional configuration is required for basic usage.
  2. First Use Case: Parsing a Domain

    use JeremyKendall\DomainParser\DomainParser;
    
    $parser = new DomainParser();
    $domain = $parser->parse('example.co.uk');
    
    // Outputs:
    // [
    //   'domain' => 'example.co.uk',
    //   'subdomains' => ['example'],
    //   'mainDomain' => 'example.co.uk',
    //   'tld' => 'co.uk',
    //   'publicSuffix' => 'co.uk',
    //   'effectiveTld' => 'uk',
    //   'effectiveTldPlusOne' => 'co.uk',
    //   'isValid' => true,
    // ]
    
  3. Where to Look First

    • Documentation for advanced use cases.
    • DomainParser class for core functionality.
    • DomainParser::parse() method for basic parsing.
    • DomainParser::isValid() for validation checks.
    • New DomainName methods (withRootLabel, withoutRootLabel, isAbsolute, when) for advanced domain manipulation.

Implementation Patterns

Common Workflows

  1. Extracting Subdomains

    $subdomains = $parser->parse('sub.example.co.uk')['subdomains'];
    // ['sub', 'example']
    
  2. Public Suffix List (PSL) Integration

    • Automatically uses the latest PSL (Public Suffix List) for accurate parsing.
    • Update PSL manually via:
      $parser->updatePublicSuffixList();
      
  3. Validation & Sanitization

    if ($parser->isValid('invalid..domain')) {
        // Process valid domain
    }
    
  4. Extracting TLDs

    $tld = $parser->parse('blog.example.com')['effectiveTld']; // 'com'
    $tldPlusOne = $parser->parse('blog.example.com')['effectiveTldPlusOne']; // 'example.com'
    
  5. Batch Processing

    $domains = ['example.com', 'test.co.uk', 'invalid'];
    $results = array_map([$parser, 'parse'], $domains);
    
  6. Absolute Domain Handling (New in 6.4.0)

    use JeremyKendall\DomainParser\DomainName;
    
    $domainName = DomainName::fromString('example.com');
    if ($domainName->isAbsolute()) {
        // Handle absolute domain (e.g., 'example.com.')
    }
    
    $withRootLabel = $domainName->withRootLabel(); // 'example.com.'
    $withoutRootLabel = $domainName->withoutRootLabel(); // 'example.com'
    
  7. Conditional Domain Building (New in 6.4.0)

    $domain = DomainName::fromString('example.com')
        ->when($isSecure, fn($d) => $d->withScheme('https'))
        ->when($isSubdomain, fn($d) => $d->withSubdomain('app'));
    

Integration Tips

  • Laravel Request Handling Useful for extracting domains from Request objects:

    use Illuminate\Http\Request;
    
    $domain = $parser->parse(Request::server('HTTP_HOST'));
    
  • Middleware for Domain-Based Logic

    public function handle(Request $request, Closure $next) {
        $parsed = $parser->parse($request->getHost());
        if ($parsed['effectiveTld'] === 'com') {
            // Apply logic for .com domains
        }
        return $next($request);
    }
    
  • Caching Parsed Results Store parsed domains in cache to avoid reprocessing:

    $cacheKey = 'parsed:'.$domain;
    $parsed = cache()->remember($cacheKey, now()->addHours(1), function() use ($parser, $domain) {
        return $parser->parse($domain);
    });
    
  • Absolute Domain Resolution (New in 6.4.0)

    $domainName = DomainName::fromString('example.com.');
    $resolved = $domainName->resolve(); // Resolves absolute domains without throwing exceptions
    

Gotchas and Tips

Pitfalls

  1. PSL Updates

    • The package ships with a bundled PSL, but it may not always be the latest.
    • Fix: Manually update via updatePublicSuffixList() or configure auto-updates (if supported in future versions).
  2. Edge Cases in Parsing

    • Domains with unusual TLDs (e.g., example.xn--p1ai for example.рф) may require manual handling.
    • IP addresses (e.g., 192.168.1.1) will return isValid: false.
    • Absolute domains (e.g., example.com.) now resolve without exceptions (previously threw errors in older versions).
  3. Case Sensitivity

    • Parsing is case-insensitive, but output may vary (e.g., CO.UK vs co.uk). Normalize if needed:
      $normalized = strtolower($parsed['domain']);
      
  4. Performance with Large Batches

    • Parsing thousands of domains in a loop can be slow.
    • Optimization: Use array_map with parallel processing (e.g., Laravel’s parallel() helper).
  5. Private Suffix Resolution (Fixed in 6.4.0)

    • If using private suffixes (e.g., internal domains like *.example.local), ensure the cache is refreshed after upgrading:
      $parser->updatePublicSuffixList(); // Refresh cache for private suffix fixes
      

Debugging Tips

  • Verify PSL Version

    echo $parser->getPublicSuffixListVersion();
    
  • Check for Malformed Input

    if (!$parser->isValid($domain)) {
        log("Invalid domain: {$domain}");
    }
    
  • Inspect Full Parsed Data

    dd($parser->parse('complex.example.co.uk')); // Debug complex cases
    
  • Debug Absolute Domains (New in 6.4.0)

    $domain = DomainName::fromString('example.com.');
    dd($domain->isAbsolute(), $domain->resolve());
    

Extension Points

  1. Custom PSL Rules Override the default PSL by extending DomainParser:

    class CustomDomainParser extends DomainParser {
        protected function getPublicSuffixList(): string {
            return file_get_contents('path/to/custom-psl.txt');
        }
    }
    
  2. Adding Domain-Specific Logic Use parsed data to trigger custom logic:

    $parsed = $parser->parse($domain);
    if (in_array('shop', $parsed['subdomains'])) {
        // Redirect to shopping cart
    }
    
  3. Testing Edge Cases Write tests for:

    • Internationalized domain names (IDNs).
    • New TLDs (e.g., .ai, .tech).
    • Subdomains with special characters (if allowed).
    • Absolute domains (e.g., example.com.).
    • Private suffixes (e.g., *.example.local).
  4. Leveraging DomainName Methods (New in 6.4.0) Extend functionality with:

    $domain = DomainName::fromString('example.com')
        ->withSubdomain('app')
        ->withScheme('https')
        ->toString(); // 'app.example.com'
    
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.
likyly/sdk
tdt/input
coreation/php-shapefile
coreation/gisconverter
primix/widgets
primix/notifications
primix/actions
primix/tables
primix/details
primix/forms
primix/support
marcelgwerder/laravel-api-handler
firebrikdotcom/conveyor-laravel-broadcaster
kanata-php/conveyor-laravel-broadcaster
alish/short-message
sonrac/lumen-league-oauth2
pushery/sanctum-hardening-for-laravel
evanschleret/laravel-uuidable
yigit-serin/laravel-openvidu
adachsoft/command-executor-lib