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

boson-php/uri

Boson URI is a small PHP library for parsing, building, normalizing, and comparing URIs. Provides immutable URI objects, convenient accessors for scheme/host/path/query/fragment, and helpers for resolving and manipulating URLs in a safe, standards-friendly way.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require boson-php/uri
    

    Add to composer.json if not auto-loaded:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Boson\\Uri\\": "vendor/boson-php/uri/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case Parse and manipulate a URI in a controller or service:

    use Boson\Uri\Uri;
    
    $uri = Uri::fromString('https://example.com/path?query=value#fragment');
    echo $uri->getScheme(); // 'https'
    echo $uri->getHost();   // 'example.com'
    
  3. Key Classes

    • Boson\Uri\Uri: Core URI manipulation.
    • Boson\Uri\UriBuilder: Construct URIs programmatically.
    • Boson\Uri\UriParser: Parse raw strings into Uri objects.

Implementation Patterns

Common Workflows

  1. Parsing and Validation

    $uri = Uri::fromString('https://example.com');
    if ($uri->isValid()) {
        // Proceed with logic
    }
    
  2. Building URIs Programmatically

    $builder = new UriBuilder();
    $uri = $builder
        ->scheme('https')
        ->host('api.example.com')
        ->path('/v1/users')
        ->query(['id' => 123])
        ->build();
    
  3. Modifying URIs

    $uri = Uri::fromString('https://example.com');
    $uri->setPort(8080); // Modify port
    $uri->addQueryParam('sort', 'desc'); // Append query param
    
  4. URL Generation in Laravel Integrate with Laravel’s URL helpers for consistency:

    use Boson\Uri\Uri;
    use Illuminate\Support\Facades\URL;
    
    $uri = Uri::fromString(URL::to('/dashboard'));
    $uri->addQueryParam('tab', 'reports');
    echo $uri->toString(); // /dashboard?tab=reports
    
  5. API Requests Use with HTTP clients (e.g., Guzzle) for request construction:

    $client = new \GuzzleHttp\Client();
    $uri = Uri::fromString('https://api.example.com/data');
    $response = $client->get($uri->toString(), [
        'query' => ['limit' => 10]
    ]);
    

Integration Tips

  • Laravel Service Providers: Bind the Uri class to Laravel’s container for dependency injection:
    $this->app->bind(Uri::class, function () {
        return Uri::fromString(request()->fullUrl());
    });
    
  • Form Requests: Validate and sanitize URIs in form requests:
    use Boson\Uri\Uri;
    use Illuminate\Validation\Rule;
    
    $validator->addRules([
        'redirect_url' => [
            'required',
            function ($attribute, $value, $fail) {
                $uri = Uri::fromString($value);
                if (!$uri->isValid() || !$uri->getScheme()) {
                    $fail('The '.$attribute.' must be a valid URI.');
                }
            }
        ]
    ]);
    

Gotchas and Tips

Pitfalls

  1. Case Sensitivity in Schemes The package normalizes schemes to lowercase (e.g., HTTPhttp). Ensure consistency when comparing schemes:

    if ($uri->getScheme() === 'https') { // Correct
        // ...
    }
    
  2. Query Parameter Handling Query parameters are parsed as arrays but may not handle edge cases like:

    $uri = Uri::fromString('https://example.com?key=value&key=other');
    // $uri->getQueryParams() returns ['key' => ['value', 'other']]
    

    Use getQueryParam('key') to get the first value or getQueryParams() for all.

  3. Relative Paths Relative paths (e.g., /path or ../path) are resolved relative to the base URI. Test edge cases:

    $uri = Uri::fromString('https://example.com/base');
    $relative = $uri->resolve('/path'); // 'https://example.com/path'
    
  4. Port Omission Ports are omitted in toString() unless explicitly set or default for the scheme (e.g., 80 for http). Force inclusion if needed:

    $uri->setPort(8080)->toString(); // 'https://example.com:8080'
    

Debugging

  • Validation Errors: Use isValid() to catch malformed URIs early:
    if (!$uri->isValid()) {
        throw new \InvalidArgumentException('Invalid URI: '.$uri->getRaw());
    }
    
  • Query Parsing: Inspect raw query strings with getRawQuery() if parsed results are unexpected.

Extension Points

  1. Custom Parsers Extend Boson\Uri\UriParser to handle non-standard URI formats:

    class CustomParser extends UriParser {
        protected function parseScheme($string) {
            // Custom logic
        }
    }
    
  2. Middleware for URI Sanitization Create middleware to validate/sanitize URIs in incoming requests:

    public function handle($request, Closure $next) {
        $uri = Uri::fromString($request->fullUrl());
        if (!$uri->isValid()) {
            abort(400, 'Invalid URI');
        }
        return $next($request);
    }
    
  3. URI Normalization Override toString() in a custom class to enforce specific formats (e.g., always include ports):

    class StrictUri extends Uri {
        public function toString() {
            $string = parent::toString();
            return preg_replace('/:\d+$/', '', $string); // Remove ports
        }
    }
    
  4. Integration with Laravel Routes Use the package to parse and validate route parameters:

    Route::get('/user/{id}', function (Uri $uri) {
        $uri = Uri::fromString(request()->path());
        $id = $uri->getPathSegments()[1]; // Extract ID
    })->middleware('validate.uri');
    
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
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
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