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

Uri Laravel Package

league/uri

League URI provides simple, intuitive PHP 8.1+ classes to parse, validate, normalize, and manipulate URIs and related components. Supports PSR-7 interoperability, IDN hosts (intl/polyfill), IPv4 conversion, and HTML URI handling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require league/uri
    

    Ensure PHP ≥ 8.1 and required extensions (intl, dom, GMP/BCMath for IPv4, or 64-bit PHP).

  2. First Use Case: Parse and manipulate a URI:

    use League\Uri\Uri;
    
    $uri = Uri::new('https://example.com/path?query=value#fragment');
    echo $uri->getScheme(); // "https"
    echo $uri->getHost();   // "example.com"
    
  3. Key Entry Points:

    • Uri::new(): Parse a string into a URI object.
    • Uri::fromComponents(): Build from components (e.g., scheme, host, path).
    • Uri::tryNew(): Safe parsing (returns null on failure).
    • Http class: PSR-7 compliant HTTP URIs (e.g., Http::new('https://api.example.com')).
  4. Documentation:


Implementation Patterns

Core Workflows

  1. URI Construction:

    // From string
    $uri = Uri::new('https://user:pass@example.com:8080/path?query=1');
    
    // From components
    $uri = Uri::fromComponents([
        'scheme' => 'https',
        'host'   => 'example.com',
        'port'   => 443,
        'path'   => '/api/v1',
    ]);
    
  2. URI Manipulation:

    // Immutable updates (returns new instance)
    $newUri = $uri->withPath('/new-path')->withQuery(['page' => 2]);
    
    // Conditional building
    $uri->when($uri->getScheme() === 'https', fn($u) => $u->withPort(443));
    
  3. Validation and Checks:

    if ($uri->isAbsolute()) {
        echo "Absolute URI";
    }
    if ($uri->isSameOrigin($otherUri)) {
        echo "Same origin";
    }
    
  4. URI Templates (for dynamic paths):

    $template = UriTemplate::new('https://api.example.com/{version}/users/{id}');
    $uri = $template->expand(['version' => 'v1', 'id' => '123']);
    
  5. PSR-7 Integration:

    use League\Uri\Http;
    $psr7Uri = Http::new('https://example.com')->toPsr7Uri();
    

Integration Tips

  • Laravel Requests: Use Uri::fromServer($_SERVER) to parse the current request URI.

    $uri = Uri::fromServer($_SERVER);
    $path = $uri->getPath(); // e.g., "/products/123"
    
  • Routing: Combine with Laravel’s router to validate or normalize incoming URIs:

    $requestUri = Uri::new(request()->getUri());
    if ($requestUri->isSameOrigin($baseUri)) {
        // Proceed with trusted request
    }
    
  • API Clients: Use Http for constructing absolute URLs from relative paths:

    $baseUri = Http::new('https://api.example.com');
    $relativeUri = Uri::new('/users/1');
    $absoluteUri = $baseUri->resolve($relativeUri);
    
  • File URIs: Handle local files with Uri::fromUnixPath('/var/www/file.txt') or Uri::fromWindowsPath('C:\\file.txt').

  • IDN (Internationalized Domain Names): Convert between ASCII and Unicode:

    $uri = Uri::new('https://例子.测试'); // Unicode
    $asciiUri = $uri->toAsciiString();   // "https://xn--fsq.xn--0zwm56d"
    

Gotchas and Tips

Pitfalls

  1. Immutable Objects:

    • All URI methods that modify components (e.g., withPath(), withQuery()) return a new instance. Avoid chaining without assignment:
      // ❌ Loses changes
      $uri->withPath('/new')->withQuery(['key' => 'value']);
      
      // ✅ Correct
      $uri = $uri->withPath('/new')->withQuery(['key' => 'value']);
      
  2. Path Normalization:

    • getPath() returns a normalized path (e.g., /a//b/a/b). Use toString() for raw output.
    • Leading slashes are preserved in withPath() only if the original path had them.
  3. Query Parameters:

    • Query strings are not parsed into arrays by default. Use getQuery() to get a raw string or withQuery() to set:
      $uri->withQuery(['page' => 2, 'sort' => 'asc']);
      
  4. IPv6 Hosts:

    • IPv6 addresses must be enclosed in [] (e.g., [2001:db8::1]). The library auto-compresses them (e.g., 2001:db8::12001:db8::).
    • Ensure your PHP environment supports IPv6 (64-bit or GMP/BCMath).
  5. Fragment Handling:

    • Fragments (#hash) are not included in isSameDocument() or equals() by default. Use equals() to compare including fragments.
  6. Deprecated Methods:

    • Avoid BaseUri (deprecated in favor of Uri or Modifier).
    • Use Uri::tryNew() instead of Uri::new() for safe parsing.
  7. IDN Requirements:

    • Internationalized domains (e.g., 例子.测试) require the intl extension or symfony/polyfill-intl-idn. Without it, parsing throws an exception.
  8. PSR-7 Compliance:

    • The Http class implements Psr\Http\Message\UriInterface, but not all methods are 100% compatible with other PSR-7 libraries. Test edge cases (e.g., authority components).

Debugging Tips

  1. Validation Errors:

    • Use Uri::tryNew() to catch invalid URIs gracefully:
      $uri = Uri::tryNew('invalid:uri');
      if (!$uri) {
          // Handle error
      }
      
  2. Component Inspection:

    • Dump components for debugging:
      dd([
          'scheme' => $uri->getScheme(),
          'host'   => $uri->getHost(),
          'port'   => $uri->getPort(),
          'path'   => $uri->getPath(),
          'query'  => $uri->getQuery(),
          'fragment' => $uri->getFragment(),
      ]);
      
  3. URI Template Issues:

    • Ensure variable names in templates are not numeric-only (e.g., {123} is invalid). Use {var123} instead.
    • Validate templates with expandOrFail() to catch errors early:
      try {
          $uri = $template->expandOrFail(['invalid' => 'value']);
      } catch (TemplateCanNotBeExpanded $e) {
          // Handle missing variables
      }
      
  4. Performance:

    • For high-throughput applications (e.g., parsing thousands of URIs), reuse Uri instances where possible or use Uri::parse() for one-off parsing.

Extension Points

  1. Custom URI Classes:

    • Extend Uri or Http to add domain-specific logic:
      class ApiUri extends Uri {
          public function isApiEndpoint(): bool {
              return $this->getPath() === '/api';
          }
      }
      
  2. URI Normalization:

    • Override normalize() to enforce project-specific rules (e.g., lowercase hosts):
      $normalized = $uri->normalize()->withHost(strtolower($uri->getHost()));
      
  3. URI Validation:

    • Combine with Laravel’s validation rules:
      use League\Uri\Uri;
      $validator->rule(function ($attribute, $value, $fail) {
          $uri = Uri::tryNew($value);
          if (!$uri || !$uri->isAbsolute()) {
              $fail('The :attribute must be a valid absolute URI.');
          }
      });
      
  4. URI Templates:

    • Create reusable templates for API endpoints:
      $userTemplate = UriTemplate::new('https://api.example.com/users/{id}');
      $uri = $userTemplate->expand(['id' => $user->id]);
      
  5. PSR-17 Factories:

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.
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
spatie/mailcoach-vapor