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

amphp/uri

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the package via Composer:
    composer require amphp/uri
    
  2. Basic Usage: Parse a URI string into an object:
    use Amp\Uri\Uri;
    
    $uri = Uri::fromString('https://example.com/path?query=value');
    
  3. Access Components: Extract parts of the URI:
    $scheme = $uri->getScheme(); // 'https'
    $host   = $uri->getHost();   // 'example.com'
    $path   = $uri->getPath();   // '/path'
    $query  = $uri->getQuery();  // 'query=value'
    

First Use Case

URL Validation: Quickly validate if a string is a well-formed URI:

if (Uri::isValid('https://example.com')) {
    // Process valid URI
}

Query Parameter Handling: Parse and manipulate query strings:

$queryParams = $uri->getQueryParameters(); // ['query' => 'value']
$uri->setQueryParameter('new_param', 'new_value');

Implementation Patterns

URI Parsing and Reconstruction

Workflow for Dynamic URIs:

  1. Parse a user-provided string into a Uri object.
  2. Validate/modify components (e.g., normalize host, sanitize path).
  3. Reconstruct the URI for use in HTTP requests or storage:
    $modifiedUri = $uri->withScheme('http')->withPath('/updated-path');
    $uriString = (string) $modifiedUri; // 'http://example.com/updated-path'
    

Integration with Laravel

Request Handling:

  • Parse incoming request URIs (e.g., from Request object):
    use Amp\Uri\Uri;
    use Illuminate\Http\Request;
    
    $requestUri = Uri::fromString(Request::fullUrl());
    
  • Useful for rewriting URLs, canonicalization, or API routing logic.

Form Data Processing:

  • Decode query parameters from form submissions:
    $queryParams = Uri::fromString($request->getUri())->getQueryParameters();
    

Resolving Relative URIs

Base URI Resolution:

  • Resolve relative paths against a base URI (e.g., for assets or redirects):
    $baseUri = Uri::fromString('https://example.com/base/');
    $relativeUri = Uri::fromString('subpath');
    $absoluteUri = $baseUri->resolve($relativeUri); // 'https://example.com/base/subpath'
    

Gotchas and Tips

Pitfalls

  1. Query Parameter Decoding:

    • The package uses urldecode() for query parameters (unlike rawurldecode() in older versions). Ensure your data is URL-encoded before parsing if you expect raw values.
    • Example:
      $uri = Uri::fromString('https://example.com?param=hello%20world');
      $param = $uri->getQueryParameter('param'); // 'hello world' (decoded)
      
  2. Hostname Validation:

    • Underscores (_) and trailing dots (.) in hostnames are allowed (e.g., for Docker). This may conflict with stricter validation rules in other parts of your app.
    • Validate manually if needed:
      if (!filter_var($uri->getHost(), FILTER_VALIDATE_DOMAIN)) {
          // Reject invalid hostnames
      }
      
  3. IPv4 Validation:

    • isIpV4() was fixed in v0.1.3. Ensure you’re using an updated version if relying on this method.
  4. Intl Extension:

    • If using ICU < 4.6, behavior may differ. Test with your PHP environment.

Debugging Tips

  • Inspect Components: Use getScheme(), getHost(), etc., to debug individual parts of a URI. For complex cases, dump the entire object:

    var_dump($uri->getScheme(), $uri->getHost(), $uri->getPath(), $uri->getQueryParameters());
    
  • String Reconstruction: Cast the Uri object to a string to verify changes:

    $uri->withQueryParameter('debug', 'true');
    echo (string) $uri; // Check output
    

Extension Points

  1. Custom Validation: Extend the Uri class or use composition to add validation logic:

    class ValidatedUri extends Uri {
        public function isValidForApp(): bool {
            return $this->getScheme() === 'https' && $this->getHost() === 'example.com';
        }
    }
    
  2. Query Parameter Handling: Override getQueryParameters() or setQueryParameter() for custom encoding/decoding:

    $uri->setQueryParameter('custom', 'value', function($value) {
        return strtoupper($value); // Custom transformation
    });
    
  3. URI Templates: Use the resolver to implement URI templates (e.g., for API endpoints):

    $baseUri = Uri::fromString('https://api.example.com/users/{id}');
    $userUri = $baseUri->resolve(Uri::fromString('123')); // 'https://api.example.com/users/123'
    

Laravel-Specific Quirks

  • Request URI Parsing: Laravel’s Request object already parses URIs, but amphp/uri can be used for additional validation or manipulation:

    $requestUri = Uri::fromString(Request::fullUrl());
    $canonicalUri = $requestUri->withScheme('https')->withPort(null);
    
  • Route Generation: Combine with Laravel’s URL::to() or route() for hybrid URI handling:

    $routeUri = Uri::fromString(route('profile', ['user' => 1]));
    
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