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

sabre/uri

Lightweight, RFC3986-compliant PHP URI utility library. Resolve relative URLs, normalize for comparisons, parse/build (like parse_url with Windows path edge cases), and split URIs into dirname/basename. Fully unit tested and inspired by Node’s URL APIs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require sabre/uri
    

    Target 3.0.3 (PHP 7.4–8.5) for Laravel compatibility.

  2. First Use Case: Resolve a relative URL against a base:

    use Sabre\Uri\Uri;
    
    $base = Uri::parse('https://example.com/base/');
    $relative = Uri::resolve($base, 'subpath');
    echo $relative; // Output: https://example.com/base/subpath
    
  3. Key Entry Points:

    • Uri::parse(): Replace parse_url() for RFC3986 compliance (handles Windows paths, Unicode).
    • Uri::resolve(): Join base + relative URLs (e.g., /api + users/api/users).
    • Uri::normalize(): Canonicalize URLs for comparison (e.g., /path///path/).

Where to Look First

  • Usage Docs for function signatures and examples.
  • Sabre\Uri\Uri class (static methods only; no instantiation needed).
  • Test suite (GitHub) for edge cases (e.g., Windows paths, Unicode).

Implementation Patterns

Core Workflows

1. URL Resolution (Base + Relative)

$base = Uri::parse('https://example.com/api/');
$resolved = Uri::resolve($base, '../users'); // Resolves to: https://example.com/users
  • Laravel Integration: Use in route generation or API client libraries to handle relative paths (e.g., /api/v1 + users).
  • File URIs: Works with file:///C:/path (Windows) or s3://bucket/path (custom schemes).

2. Normalization for Comparison

$url1 = Uri::parse('https://example.com/path//');
$url2 = Uri::parse('https://example.com/path');
$normalized1 = Uri::normalize($url1);
$normalized2 = Uri::normalize($url2);
assert($normalized1 === $normalized2); // True (both become `/path`)
  • Use Case: Validate redirects, canonicalize database URLs, or deduplicate links.

3. Parsing and Rebuilding

$parsed = Uri::parse('https://user:pass@example.com:8080/path?query=1#frag');
$rebuilt = Uri::build($parsed);
assert($parsed['scheme'] === 'https');
  • Laravel Tip: Use Uri::parse() to extract query params or fragments before passing to Laravel’s Request or Url::to().

4. Splitting Paths

$uri = Uri::parse('https://example.com/foo/bar/baz');
list($dirname, $basename) = Uri::split($uri);
// $dirname = 'https://example.com/foo/bar/'
// $basename = 'baz'
  • Use Case: Implement custom URL rewriting or path-based routing logic.

Integration Tips

Laravel-Specific Patterns

  1. Route Generation: Replace route('name') with Uri::resolve() for dynamic paths:

    $base = Uri::parse(route('api.base'));
    $userUrl = Uri::resolve($base, 'users/123');
    
  2. Request Handling: Parse incoming URLs with Uri::parse() to validate structure before Laravel’s Request processing:

    $uri = Uri::parse(request()->getUri());
    if ($uri['scheme'] !== 'https') {
        abort(403, 'Insecure scheme');
    }
    
  3. File System Abstraction: Normalize file:// URIs for cross-platform storage:

    $path = Uri::normalize(Uri::parse('file:///C:/Users/Path With Spaces'));
    
  4. API Clients: Use Uri::resolve() to join API base URLs with endpoints:

    $apiBase = Uri::parse(config('services.api.base_url'));
    $endpoint = Uri::resolve($apiBase, 'v1/users');
    

Performance Considerations

  • Avoid Overhead: The package is lightweight (~10KB). Cache parsed URIs if reused (e.g., in route middleware).
  • Batch Processing: Use Uri::parse() in bulk for URL validation (e.g., user-uploaded links).

Testing

  • Assertions: Use Uri::normalize() to compare URLs in tests:
    $this->assertEquals(
        Uri::normalize(Uri::parse('/path//')),
        Uri::normalize(Uri::parse('/path'))
    );
    
  • Edge Cases: Test Windows paths (file:///C:/), Unicode (https://例子.测试), and relative URLs (../).

Gotchas and Tips

Pitfalls

  1. Windows Path Handling:

    • Issue: file:///C:/path may parse differently across versions (see #81).
    • Fix: Stick to 3.0.3 (stable) or explicitly test Windows paths:
      $windowsUri = Uri::parse('file:///C:/Users/Path');
      assert($windowsUri['host'] === ''); // Host is empty for Windows file URIs
      
  2. Relative Resolution Quirks:

    • Issue: Uri::resolve() may not behave like browsers for certain edge cases (e.g., ./ or ../ in paths).
    • Fix: Test with:
      $base = Uri::parse('https://example.com/');
      $resolved = Uri::resolve($base, './relative');
      // Output: https://example.com/relative (not https://example.com//relative)
      
  3. Fragment Handling:

    • Issue: Fragments (#hash) are preserved but may cause issues in build() if not handled.
    • Fix: Explicitly check for fragments:
      $uri = Uri::parse('https://example.com#hash');
      if (isset($uri['fragment'])) {
          // Handle fragment separately
      }
      
  4. Unicode Normalization:

    • Issue: Non-ASCII characters (e.g., https://例子.测试) may not normalize as expected.
    • Fix: Use Uri::normalize() and verify with:
      $normalized = Uri::normalize(Uri::parse('https://例子.测试'));
      assert(strpos($normalized, '%E4') !== false); // Should be percent-encoded
      

Debugging Tips

  1. Invalid URIs:

    • Uri::parse() throws Sabre\Uri\InvalidUriException for malformed inputs. Catch and log:
      try {
          Uri::parse('invalid:uri');
      } catch (InvalidUriException $e) {
          Log::error('Malformed URI', ['uri' => $e->getUri()]);
      }
      
  2. Unexpected Output:

    • Use var_export(Uri::parse($uri), true) to inspect parsed components.
  3. CI/CD Failures:

    • If PHPStan flags issues, update to 3.0.3 (includes PHPStan 2+ fixes via #124).

Extension Points

  1. Custom Schemes:

    • Extend Sabre\Uri\Uri by copying the class and overriding parse()/build() for non-standard schemes (e.g., s3://).
  2. Validation Rules:

    • Create a Laravel validator rule:
      use Sabre\Uri\Uri;
      
      class ValidUri implements Rule
      {
          public function passes($attribute, $value)
          {
              try {
                  Uri::parse($value);
                  return true;
              } catch (InvalidUriException) {
                  return false;
              }
          }
      }
      
  3. Performance Optimization:

    • For high-volume parsing, pre-compile regex patterns from the library’s source (e.g., Uri::parse() uses regex for scheme/host detection).

Configuration Quirks

  • No Config: The package is stateless. No config/uri.php or service provider needed.
  • Laravel Facade: Create a helper:
    // app/Helpers/UriHelper.php
    use Sabre\Uri\Uri;
    
    if (!function_exists('uri_parse')) {
        function uri_parse($uri) {
            return Uri::parse($uri);
        }
    }
    

Laravel-Specific Gotchas

  1. Route Caching:
    • If using Uri::resolve() in route generation, clear route cache after changes:
      php artisan route:
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport