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.
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.
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'
Key Classes
Boson\Uri\Uri: Core URI manipulation.Boson\Uri\UriBuilder: Construct URIs programmatically.Boson\Uri\UriParser: Parse raw strings into Uri objects.Parsing and Validation
$uri = Uri::fromString('https://example.com');
if ($uri->isValid()) {
// Proceed with logic
}
Building URIs Programmatically
$builder = new UriBuilder();
$uri = $builder
->scheme('https')
->host('api.example.com')
->path('/v1/users')
->query(['id' => 123])
->build();
Modifying URIs
$uri = Uri::fromString('https://example.com');
$uri->setPort(8080); // Modify port
$uri->addQueryParam('sort', 'desc'); // Append query param
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
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]
]);
Uri class to Laravel’s container for dependency injection:
$this->app->bind(Uri::class, function () {
return Uri::fromString(request()->fullUrl());
});
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.');
}
}
]
]);
Case Sensitivity in Schemes
The package normalizes schemes to lowercase (e.g., HTTP → http). Ensure consistency when comparing schemes:
if ($uri->getScheme() === 'https') { // Correct
// ...
}
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.
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'
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'
isValid() to catch malformed URIs early:
if (!$uri->isValid()) {
throw new \InvalidArgumentException('Invalid URI: '.$uri->getRaw());
}
getRawQuery() if parsed results are unexpected.Custom Parsers
Extend Boson\Uri\UriParser to handle non-standard URI formats:
class CustomParser extends UriParser {
protected function parseScheme($string) {
// Custom logic
}
}
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);
}
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
}
}
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');
How can I help you explore Laravel packages today?