### Template Expansion Examples Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri-template.md Examples demonstrating path segment and query parameter expansion. ```php $tpl = new UriTemplate('https://example.com{/path*}/file{.ext}'); // Expands to: https://example.com/a/b/c/file.json $tpl = new UriTemplate('https://example.com{?query*}'); // Expands with query=['a' => 1, 'b' => 2] to: ?a=1&b=2 ``` -------------------------------- ### Create BaseUri Instances Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/base-uri.md Examples of creating a BaseUri wrapper from different URI types. ```php use League\Uri\BaseUri; use League\Uri\Uri; // From League Uri $uri = Uri::new('https://example.com/path'); $base = BaseUri::from($uri); // From string $base = BaseUri::from('https://example.com/path'); // From PSR-7 Uri $base = BaseUri::from($psr7Uri); ``` -------------------------------- ### Initialize Builder Instance Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/builder.md Example of creating a new Builder instance with specific URI components. ```php use League\Uri\Builder; $builder = new Builder( scheme: 'https', host: 'example.com', path: '/api/v1' ); ``` -------------------------------- ### Complete URN Usage Examples Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/urn.md Demonstrates parsing, building, and conditional modification of URN objects. ```php use League\Uri\Urn; // Parse ISBN URN $urn = Urn::new('urn:isbn:0451450523'); echo $urn->getNid(); // 'isbn' echo $urn->getNss(); // '0451450523' // Parse URN with all optional components $urn = Urn::parse('urn:example:resource?+http://example.org/resolve?=version?=2#section-1'); if ($urn) { echo $urn->getNid(); // 'example' echo $urn->getNss(); // 'resource' echo $urn->getRComponent(); // 'http://example.org/resolve?version?=2' echo $urn->getFComponent(); // 'section-1' } // Build URN using modification chain $urn = Urn::new('urn:example:old') ->withNss('new-value') ->withFComponent('intro'); echo $urn->toString(); // 'urn:example:new-value#intro' // Use conditional modification $urn = Urn::new('urn:isbn:0451450523') ->when( fn ($u) => strlen($u->getNss()) < 10, fn ($u) => $u->withNss('0451450523') ); // Validate before using if ($urn = Urn::parse($userInput)) { // Process valid URN processUrn($urn); } ``` -------------------------------- ### Install League URI via Composer Source: https://github.com/thephpleague/uri/blob/master/README.md Use this command to add the package to your project dependencies. ```bash $ composer require league/uri ``` -------------------------------- ### Initialize Urn from Components Array Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/urn.md Example of constructing an Urn instance using a components array. ```php $urn = Urn::fromComponents([ 'scheme' => 'urn', 'path' => 'isbn:0451450523' ]); ``` -------------------------------- ### Get Unicode Host Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Retrieves the host in Unicode form, decoding IDN. ```php $uri = Http::new('https://例え.jp/path'); echo $uri->getUnicodeHost(); // '例え.jp' ``` -------------------------------- ### Get Host Component Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Retrieves the host component of the URI as a string. ```php public function getHost(): string ``` -------------------------------- ### Get User Info Component Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Retrieves the user info component of the URI as a string. ```php public function getUserInfo(): string ``` -------------------------------- ### Get Windows filesystem path Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/base-uri.md Returns the Windows path from a file URI, or null if the URI is not a file URI. ```php $base = BaseUri::from('file:///C:/Users/User/document.txt'); echo $base->windowsPath(); // 'C:\\Users\\User\\document.txt' ``` -------------------------------- ### Integrate HttpFactory with Guzzle Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http-factory.md Demonstrates creating a URI instance and using it to perform a GET request via the Guzzle HTTP client. ```php use League\/Uri\\HttpFactory; use GuzzleHttp\\Client; \/\/ Create factory $uriFactory = new HttpFactory(); \/\/ Create URI $uri = $uriFactory->createUri('https:\/\/api.example.com\/users\/123'); \/\/ Use with Guzzle $client = new Client(); $response = $client->get($uri->__toString()); \/\/ Access URI components echo $uri->getScheme(); \/\/ 'https' echo $uri->getHost(); \/\/ 'api.example.com' echo $uri->getPath(); \/\/ '\/users\/123' ``` -------------------------------- ### Get Fragment Component Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Retrieves the fragment component of the URI as a string. ```php public function getFragment(): string ``` -------------------------------- ### Get Query Component Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Retrieves the query component of the URI as a string. ```php public function getQuery(): string ``` -------------------------------- ### Create URI instances Source: https://github.com/thephpleague/uri/blob/master/_autodocs/getting-started.md Demonstrates various ways to instantiate a URI object from strings, components, files, or filesystem paths. ```php use League\Uri\Uri; // Parse from string $uri = Uri::new('https://user:pass@example.com:8080/path?query=value#fragment'); // Create from components $uri = Uri::fromComponents([ 'scheme' => 'https', 'host' => 'example.com', 'path' => '/api/users', 'query' => 'filter=active' ]); // From file $fileUri = Uri::fromFileContents('/path/to/image.png'); // From data $dataUri = Uri::fromData('Hello World', 'text/plain'); // From filesystem path $fileUri = Uri::fromUnixPath('/home/user/file.txt'); ``` -------------------------------- ### Get Path Component Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Retrieves the path component of the URI as a string. ```php public function getPath(): string ``` -------------------------------- ### Construct URIs with Builder Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/builder.md Demonstrates initialization, fluent method chaining, validation, relative path resolution, and conditional building. ```php use League\Uri\Builder; use League\Uri\Uri; // Method 1: Constructor initialization $builder = new Builder( scheme: 'https', host: 'api.example.com', path: '/v2/resources' ); // Method 2: Fluent builder pattern $builder = (new Builder()) ->scheme('https') ->userInfo('admin', 'secret') ->host('api.example.com') ->port(8443) ->path('/api/users') ->query('filter=active&page=1') ->fragment('results'); // Validate before building if ($builder->validate()) { $uri = $builder->build(); echo $uri->toString(); } // Build from relative URI $baseUri = 'https://example.com/api/v1/'; $builder = (new Builder()) ->path('../docs/guide.html'); $uri = $builder->build($baseUri); // Resolves relative path // Conditional building $isSecure = true; $uri = (new Builder()) ->when( $isSecure, fn ($b) => $b->scheme('https')->port(443), fn ($b) => $b->scheme('http')->port(80) ) ->host('example.com') ->build(); ``` -------------------------------- ### Get Authority Component Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Retrieves the authority component of the URI as a string. ```php public function getAuthority(): string ``` ```php echo $uri->getAuthority(); // 'user:pass@example.com:8080' ``` -------------------------------- ### Compare Http::new() and HttpFactory Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http-factory.md Demonstrates the difference between direct instantiation and the PSR-17 factory pattern. ```php use League\Uri\Http; use League\Uri\HttpFactory; // Direct method $uri1 = Http::new('https://example.com/path'); // Factory method $factory = new HttpFactory(); $uri2 = $factory->createUri('https://example.com/path'); // Both create equivalent Http instances echo $uri1->__toString() === $uri2->__toString(); // true ``` -------------------------------- ### Get Scheme Component Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Retrieves the scheme component of the URI as a string. ```php public function getScheme(): string ``` ```php echo $uri->getScheme(); // 'https' or '' ``` -------------------------------- ### Get URN string representation Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/urn.md Converts the URN object to its string representation. ```php $urn = Urn::new('urn:isbn:0451450523'); echo (string) $urn; // 'urn:isbn:0451450523' ``` -------------------------------- ### Create Http instance safely Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Use tryNew() to attempt URI creation, returning null instead of throwing an exception on failure. ```php $uri = Http::tryNew('https://example.com'); if ($uri === null) { echo "Invalid URI format"; } ``` -------------------------------- ### Create Http instance from template Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Expand an RFC 6570 URI template with provided variables to create an Http instance. ```php $uri = Http::fromTemplate( 'https://example.com/api/{version}/users{?page,limit}', ['version' => 'v2', 'page' => 1, 'limit' => 50] ); ``` -------------------------------- ### Get Port Component Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Retrieves the port component of the URI as an integer or null. ```php public function getPort(): ?int ``` -------------------------------- ### Check if URI is an absolute-path reference Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/base-uri.md Determines if the URI starts with a forward slash. ```php BaseUri::from('/api/users')->isAbsolutePath(); // true BaseUri::from('https://example.com/path')->isAbsolutePath(); // false ``` -------------------------------- ### withQComponent() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/urn.md Returns a new instance with an updated q-component. ```APIDOC ## withQComponent() ### Description Return new instance with updated q-component. ### Parameters - **$qComponent** (BackedEnum|Stringable|string|null) - Required - Query component or null to remove ### Return Type `Urn` — New instance ``` -------------------------------- ### Perform complete URI operations Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Demonstrates URI creation, component access, immutable modification, and template expansion. ```php use League\Uri\Http; // Create from string $uri = Http::new('https://user:pass@api.example.com:8443/v1/users?limit=10#results'); // Access components echo $uri->getScheme(); // 'https' echo $uri->getUserInfo(); // 'user:pass' echo $uri->getHost(); // 'api.example.com' echo $uri->getPort(); // 8443 echo $uri->getPath(); // '/v1/users' echo $uri->getQuery(); // 'limit=10' echo $uri->getFragment(); // 'results' // Immutable modification $newUri = $uri ->withScheme('http') ->withPort(8080) ->withPath('/v2/posts') ->withQuery('offset=20'); // Use with PSR-7 clients $httpClient = new GuzzleHttp\Client(); $response = $httpClient->get($uri->__toString()); // Normalize for comparison $normalized = Http::new('HTTP://EXAMPLE.COM:443/Path'); echo $normalized->normalize(); // 'https://example.com/Path' // Use in templates $templated = Http::fromTemplate( 'https://api.example.com/v{major}/users{?page,limit}', ['major' => '1', 'page' => 2, 'limit' => 50] ); ``` -------------------------------- ### Expand a basic URI template Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri-template.md Demonstrates standard template expansion with key-value pairs. ```php use League\Uri\UriTemplate; $template = new UriTemplate( 'https://api.github.com/repos/{owner}/{repo}/issues{?state,labels,sort}' ); $uri = $template->expand([ 'owner' => 'thephpleague', 'repo' => 'uri', 'state' => 'closed', 'sort' => 'updated' ]); echo $uri->toString(); // https://api.github.com/repos/thephpleague/uri/issues?state=closed&sort=updated ``` -------------------------------- ### Check if URI is a relative-path reference Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/base-uri.md Determines if the URI is a relative path or starts with ./. ```php BaseUri::from('path/to/resource')->isRelativePath(); // true BaseUri::from('../other/file')->isRelativePath(); // true BaseUri::from('/absolute/path')->isRelativePath(); // false ``` -------------------------------- ### Project Documentation File Structure Source: https://github.com/thephpleague/uri/blob/master/_autodocs/README.md Displays the directory layout of the documentation files within the output folder. ```text output/ ├── README.md # This file ├── INDEX.md # Master index & quick reference ├── getting-started.md # Quick start guide ├── types.md # Type definitions & enums ├── errors.md # Exception reference └── api-reference/ # Complete class documentation ├── uri.md # Uri class (1,539 lines) ├── http.md # Http class (731 lines) ├── urn.md # Urn class (634 lines) ├── builder.md # Builder class (629 lines) ├── base-uri.md # BaseUri class (625 lines) ├── uri-template.md # UriTemplate class (522 lines) └── http-factory.md # HttpFactory class (313 lines) ``` -------------------------------- ### Convert Native URI Types Source: https://github.com/thephpleague/uri/blob/master/_autodocs/types.md Demonstrates how to instantiate a library URI object from various native URI types when ext-uri is available. ```php $uri = Uri::new($rfc3986Uri); // From RFC 3986 $uri = Uri::new($whatWgUrl); // From WHATWG $uri = Uri::new($urn); // From URN ``` -------------------------------- ### League\Uri\Builder::__construct Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/builder.md Initializes a new Builder instance with optional URI components. ```APIDOC ## __construct() ### Description Create a new Builder instance with optional initial components. ### Signature `public function __construct(BackedEnum|Stringable|string|null $scheme = null, BackedEnum|Stringable|string|null $username = null, BackedEnum|Stringable|string|null $password = null, BackedEnum|Stringable|string|null $host = null, BackedEnum|int|null $port = null, BackedEnum|Stringable|string|null $path = null, BackedEnum|Stringable|string|null $query = null, BackedEnum|Stringable|string|null $fragment = null)` ### Parameters - **$scheme** (BackedEnum|Stringable|string|null) - Optional - URI scheme - **$username** (BackedEnum|Stringable|string|null) - Optional - Username component - **$password** (BackedEnum|Stringable|string|null) - Optional - Password component - **$host** (BackedEnum|Stringable|string|null) - Optional - Host component - **$port** (BackedEnum|int|null) - Optional - Port number - **$path** (BackedEnum|Stringable|string|null) - Optional - Path component - **$query** (BackedEnum|Stringable|string|null) - Optional - Query string - **$fragment** (BackedEnum|Stringable|string|null) - Optional - Fragment identifier ### Example ```php use League\Uri\Builder; $builder = new Builder( scheme: 'https', host: 'example.com', path: '/api/v1' ); ``` ``` -------------------------------- ### Instantiate Uri safely Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Attempts to create a new Uri instance, returning null instead of throwing an exception on failure. ```php $uri = Uri::tryNew('https://example.com'); if ($uri === null) { echo "Invalid URI"; } else { echo $uri->getHost(); // 'example.com' } ``` -------------------------------- ### Create Http instance from components Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Construct an Http object using an associative array of URI components. ```php $uri = Http::fromComponents([ 'scheme' => 'https', 'host' => 'example.com', 'path' => '/api', 'query' => 'v=1' ]); echo $uri->__toString(); // 'https://example.com/api?v=1' ``` -------------------------------- ### Create and expand URIs with UriTemplate Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri-template.md Demonstrates creating a URI from a template and using a template object as a builder component. ```php use League\Uri\Uri; use League\Uri\UriTemplate; // Create template-based URI directly $uri = Uri::fromTemplate( 'https://api.example.com/v{major}.{minor}/{resource}', ['major' => '2', 'minor' => '0', 'resource' => 'posts'] ); // Use as complex builder component $baseTemplate = new UriTemplate( '{scheme}://{host}{:port}/api/v{version}', ['scheme' => 'https', 'version' => '1'] ); $uri = $baseTemplate->expand([ 'host' => 'example.com', 'port' => '8080' ]); ``` -------------------------------- ### Get Unix filesystem path Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/base-uri.md Returns the Unix path from a file URI, or null if the URI is not a file URI. ```php $base = BaseUri::from('file:///home/user/document.txt'); echo $base->unixPath(); // '/home/user/document.txt' ``` -------------------------------- ### Parse URN with Null Check Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/urn.md Example of using the parse() method to safely handle potentially invalid URN strings. ```php $urn = Urn::parse('urn:isbn:0451450523'); if ($urn !== null) { echo "Valid URN: " . $urn->getNss(); } ``` -------------------------------- ### Http::fromTemplate() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Creates an Http instance by expanding an RFC 6570 URI template. ```APIDOC ## Http::fromTemplate() ### Description Creates an Http instance by expanding a provided URI template with variables. ### Signature `public static function fromTemplate(BackedEnum|UriTemplate|Stringable|string $template, iterable $variables = []): self` ### Parameters - **$template** (BackedEnum|UriTemplate|Stringable|string) - Required - RFC 6570 template - **$variables** (iterable) - Optional - Template variables ### Throws - **TemplateCanNotBeExpanded** - If template or variables are invalid. ``` -------------------------------- ### Get URI string representations Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Methods for retrieving various string formats of the URI, including ASCII, Unicode, and human-readable versions. ```php public function toString(): string ``` ```php public function toAsciiString(): string ``` ```php public function toUnicodeString(): string ``` ```php public function toDisplayString(): string ``` ```php public function __toString(): string ``` ```php public function jsonSerialize(): string ``` -------------------------------- ### BaseUri::from() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/base-uri.md Creates a new BaseUri wrapper instance from a PSR-7 URI, League URI, or string. ```APIDOC ## BaseUri::from() ### Description Creates a BaseUri wrapper from a PSR-7 or League URI. ### Signature `public static function from(Stringable|string $uri, ?UriFactoryInterface $uriFactory = null): static` ### Parameters - **$uri** (Psr7UriInterface|UriInterface|Stringable|string) - Required - URI to wrap - **$uriFactory** (UriFactoryInterface|null) - Optional - Optional PSR-17 factory ### Return Type `BaseUri` - New wrapper instance ``` -------------------------------- ### Work with PSR-7 Source: https://github.com/thephpleague/uri/blob/master/_autodocs/INDEX.md Initialize an HTTP URI object compatible with PSR-7 interfaces. ```php $uri = Http::new('https://example.com/api'); // Use with PSR-7 clients, middleware, etc. ``` -------------------------------- ### Retrieve Default Port Source: https://github.com/thephpleague/uri/blob/master/_autodocs/types.md Use the port() method to get the default port for a specific scheme, returning null if no default is defined. ```php $scheme = UriScheme::Http; echo $scheme->port(); // 80 $scheme = UriScheme::Https; echo $scheme->port(); // 443 $scheme = UriScheme::About; echo $scheme->port(); // null ``` -------------------------------- ### build() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/builder.md Finalizes the builder configuration and returns a new Uri instance. ```APIDOC ## public function build(Rfc3986Uri|WhatWgUrl|BackedEnum|Stringable|string|null $baseUri = null) ### Description Build and return a Uri instance. ### Parameters - **$baseUri** (Rfc3986Uri|WhatWgUrl|BackedEnum|Stringable|string|null) - Optional - Base URI for resolving relative URIs ### Return Type `Uri` — New Uri instance ### Throws - **SyntaxError** - If builder state is invalid ``` -------------------------------- ### Project File Structure Source: https://github.com/thephpleague/uri/blob/master/_autodocs/INDEX.md Visual representation of the project directory layout. ```text /workspace/home/output/ ├── INDEX.md # This file ├── getting-started.md # Quick start guide ├── types.md # Type definitions ├── errors.md # Exception reference └── api-reference/ ├── uri.md # Uri class ├── http.md # Http class ├── urn.md # Urn class ├── builder.md # Builder class ├── base-uri.md # BaseUri class ├── http-factory.md # HttpFactory class └── uri-template.md # UriTemplate class ``` -------------------------------- ### Use URI Templates Source: https://github.com/thephpleague/uri/blob/master/_autodocs/INDEX.md Expand URI templates with provided variables. ```php $template = new UriTemplate('https://api.example.com/v{version}/users{?id}'); $uri = $template->expand(['version' => '2', 'id' => '123']); ``` -------------------------------- ### Instantiate UriTemplate Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri-template.md Create a new instance with a template string and default variable values. ```php use League\Uri\UriTemplate; $template = new UriTemplate( 'https://api.example.com/v{version}/users{?page,limit}', ['version' => 'v1', 'page' => 1] ); ``` -------------------------------- ### Http::fromComponents() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Creates an Http instance from an array of URI components. ```APIDOC ## Http::fromComponents() ### Description Creates an Http instance using an associative array of URI components. ### Signature `public static function fromComponents(array $components = []): self` ### Parameters - **$components** (array) - Optional - URI components: scheme, user, pass, host, port, path, query, fragment ``` -------------------------------- ### Uri::fromWindowsPath() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Creates a file URI from a Windows filesystem path. ```APIDOC ## Uri::fromWindowsPath() ### Description Create a file URI from a Windows filesystem path. ### Parameters - **$path** (BackedEnum|Stringable|string) - Required - Windows filesystem path ### Return Type Uri ``` -------------------------------- ### Set User Info Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/builder.md Sets the username and optional password components. Throws a SyntaxError if components are invalid. ```php public function userInfo( BackedEnum|Stringable|string|null $user, BackedEnum|Stringable|string|null $password = null ): static ``` ```php $builder->userInfo('admin', 'secret123'); // Creates URI with "admin:secret123@" in authority ``` -------------------------------- ### Initialize and Access URN Components Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/urn.md Usage of the new() method to parse URNs and retrieve NID and NSS components. ```php use League\Uri\Urn; // Basic URN $urn = Urn::new('urn:isbn:0451450523'); echo $urn->getNid(); // 'isbn' echo $urn->getNss(); // '0451450523' // URN with r-component, q-component, and fragment $urn = Urn::new('urn:example:foo/bar?+param=value?=query#section'); ``` -------------------------------- ### withHost() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Returns a new instance of the Http object with the specified host. ```APIDOC ## withHost(string $host) ### Description Returns a new instance with the updated host. ### Parameters - **$host** (string) - Required - New hostname ### Return Type Http ``` -------------------------------- ### expandToUri() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri-template.md Expands the template into a native RFC 3986 Uri instance. ```APIDOC ## expandToUri() ### Description Expand to native RFC 3986 Uri (if ext-uri available). ### Parameters - **$variables** (iterable) - Default: [] - Variables to expand - **$baseUri** (Rfc3986Uri|WhatWgUrl|BackedEnum|Stringable|string|null) - Default: null - Base URI ### Returns - **Rfc3986Uri** - Native URI from ext-uri ### Throws - **MissingFeature** - If ext-uri is not available - **TemplateCanNotBeExpanded** - If variables invalid ``` -------------------------------- ### Instantiate Uri from string Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Creates a new Uri instance from a string. Throws a SyntaxError if the provided URI is invalid. ```php use League\Uri\Uri; $uri = Uri::new('https://user@example.com:8080/path?query=value#fragment'); echo $uri->getScheme(); // 'https' echo $uri->getUsername(); // 'user' echo $uri->getHost(); // 'example.com' echo $uri->getPort(); // 8080 ``` -------------------------------- ### Set Host Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/builder.md Defines the host component. Throws a SyntaxError if the host is invalid. ```php public function host( BackedEnum|Stringable|string|null $host ): self ``` ```php $builder->host('api.example.com'); ``` -------------------------------- ### expandToUrl() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri-template.md Expands the template into a WHATWG Url instance. ```APIDOC ## expandToUrl() ### Description Expand to WHATWG Url (if ext-uri available). ### Parameters - **$variables** (iterable) - Default: [] - Variables to expand - **$baseUri** (Rfc3986Uri|WhatWgUrl|BackedEnum|Stringable|string|null) - Default: null - Base URI ### Returns - **WhatWgUrl** ``` -------------------------------- ### HttpFactory::__construct Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http-factory.md Initializes a new instance of the HttpFactory class. ```APIDOC ## __construct() ### Description Creates a new HttpFactory instance. ### Signature `public function __construct()` ``` -------------------------------- ### Build URI Instance Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/builder.md Constructs and returns a new Uri instance based on the current builder state. ```php $uri = (new Builder()) ->scheme('https') ->host('api.example.com') ->path('/v1/users') ->query('limit=10') ->build(); echo $uri->toString(); // 'https://api.example.com/v1/users?limit=10' ``` -------------------------------- ### Uri::fromUnixPath() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Creates a file URI from a Unix filesystem path. ```APIDOC ## Uri::fromUnixPath() ### Description Create a file URI from a Unix filesystem path. ### Parameters - **$path** (BackedEnum|Stringable|string) - Required - Unix filesystem path ### Return Type Uri ``` -------------------------------- ### Instantiate HttpFactory Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http-factory.md Create a new instance of the HttpFactory class. ```php use League\/Uri\/HttpFactory; $factory = new HttpFactory(); ``` -------------------------------- ### Create a file URI from a Windows path Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Converts a Windows filesystem path into a file URI, handling backslashes appropriately. ```php $uri = Uri::fromWindowsPath('C:\\Users\\User\\Documents\\file.txt'); echo $uri->toString(); // 'file:///C:/Users/User/Documents/file.txt' ``` -------------------------------- ### Uri::fromServer() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Creates a Uri from PHP's $_SERVER superglobal array. ```APIDOC ## Uri::fromServer() ### Description Create a Uri from PHP's $_SERVER superglobal array. ### Parameters - **$server** (array) - Required - Server environment array (usually $_SERVER) ### Return Type Uri ``` -------------------------------- ### Update Hostname Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Returns a new instance with the updated host. ```php public function withHost(string $host): Http ``` -------------------------------- ### Http::tryNew() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Creates an Http instance or returns null if the URI is invalid. ```APIDOC ## Http::tryNew() ### Description Attempts to create an Http instance from a URI string, returning null instead of throwing an exception on failure. ### Signature `public static function tryNew(Rfc3986Uri|WhatwgUrl|Stringable|string $uri = ''): ?self` ### Parameters - **$uri** (Rfc3986Uri|WhatwgUrl|Stringable|string) - Optional - URI string ``` -------------------------------- ### Http::new() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Creates a new Http instance from a URI string. ```APIDOC ## Http::new() ### Description Creates a new Http instance from a URI string. This method validates the URI against PSR-7 requirements. ### Signature `public static function new(Rfc3986Uri|WhatwgUrl|Stringable|string $uri = ''): self` ### Parameters - **$uri** (Rfc3986Uri|WhatwgUrl|Stringable|string) - Optional - URI string to parse ### Throws - **SyntaxError** - If URI is invalid, lacks a scheme/authority, or has an invalid port. ``` -------------------------------- ### Uri::fromComponents() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Creates a Uri from a hash array of URI components. ```APIDOC ## static Uri::fromComponents(array $components) ### Description Create a Uri from a hash array of URI components. ### Parameters - **$components** (array) - Optional - Hash of components with keys: scheme, user, pass, host, port, path, query, fragment. Defaults to []. ### Returns - **Uri** - New Uri instance. ### Example ```php $uri = Uri::fromComponents(['scheme' => 'https', 'host' => 'example.com', 'path' => '/api/users']); ``` ``` -------------------------------- ### withUserInfo() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Returns a new instance of the Http object with the specified user info. ```APIDOC ## withUserInfo(string $user, ?string $password = null) ### Description Returns a new instance with the updated user info. ### Parameters - **$user** (string) - Required - Username - **$password** (string|null) - Optional - Password ### Return Type Http ``` -------------------------------- ### Create URI Builder Source: https://github.com/thephpleague/uri/blob/master/_autodocs/types.md The builder() method initializes a new URI builder instance pre-configured with the current scheme. ```php $uri = UriScheme::Https ->builder() ->host('example.com') ->path('/api') ->build(); ``` -------------------------------- ### Update Path Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Returns a new instance with the updated path. ```php public function withPath(string $path): Http ``` -------------------------------- ### Create Uri from components Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Constructs a Uri instance from an associative array of URI components. ```php $uri = Uri::fromComponents([ 'scheme' => 'https', 'host' => 'example.com', 'path' => '/api/users', 'query' => 'filter=active', ]); echo $uri->toString(); // 'https://example.com/api/users?filter=active' ``` -------------------------------- ### Catching MissingFeature Exception Source: https://github.com/thephpleague/uri/blob/master/_autodocs/errors.md Demonstrates how to catch the MissingFeature exception and implement a fallback strategy when a required extension like ext-fileinfo is missing. ```php use League\Uri\Exceptions\MissingFeature; use League\Uri\Uri; try { // Requires ext-fileinfo $uri = Uri::fromFileContents('/path/to/image.png'); } catch (MissingFeature $e) { echo "Feature unavailable: " . $e->getMessage(); // Install extension or use fallback if (str_contains($e->getMessage(), 'fileinfo')) { echo "Install ext-fileinfo: sudo apt install php-fileinfo"; // Fallback: manually create data URI $data = file_get_contents('/path/to/image.png'); $mime = 'image/png'; $uri = Uri::fromData($data, $mime); } } ``` -------------------------------- ### getQComponent() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/urn.md Retrieves the q-component (query string) from the URN. ```APIDOC ## public function getQComponent(): ?string ### Description Get the q-component (query string) as a percent-encoded string or null if not present. ### Return Type ?string ### Example ```php $urn = Urn::new('urn:example:foo?=version'); echo $urn->getQComponent(); // 'version' ``` ``` -------------------------------- ### userInfo() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/builder.md Sets the username and password components of the URI. ```APIDOC ## userInfo(BackedEnum|Stringable|string|null $user, BackedEnum|Stringable|string|null $password = null) ### Description Sets username and password components. ### Parameters - **$user** (BackedEnum|Stringable|string|null) - Required - Username or null - **$password** (BackedEnum|Stringable|string|null) - Optional - Password or null ### Returns - **Builder** ### Throws - **SyntaxError** - If components are invalid ``` -------------------------------- ### Build URIs incrementally Source: https://github.com/thephpleague/uri/blob/master/_autodocs/getting-started.md Use the Builder class to construct a URI step-by-step. ```php use League\Uri\Builder; $uri = (new Builder()) ->scheme('https') ->host('api.example.com') ->path('/v1/users') ->query('limit=10&offset=20') ->build(); echo $uri->toString(); // https://api.example.com/v1/users?limit=10&offset=20 ``` -------------------------------- ### Retrieve All URI Components Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Export all URI components into an associative array. ```php $components = $uri->toComponents(); // [ // 'scheme' => 'https', // 'user' => 'admin', // 'pass' => 'secret', // 'host' => 'example.com', // 'port' => 8080, // 'path' => '/api', // 'query' => 'key=value', // 'fragment' => 'section' // ] ``` -------------------------------- ### Create Urn from Components Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/urn.md Method signature for creating an Urn instance from an array of URI components. ```php public static function fromComponents(array $components = []): self ``` -------------------------------- ### Uri::tryNew() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Creates a new Uri instance or returns null if parsing fails. ```APIDOC ## static Uri::tryNew(mixed $uri) ### Description Creates a new Uri instance or returns null on failure. ### Parameters - **$uri** (Rfc3986Uri|WhatWgUrl|Urn|Stringable|string) - Optional - URI string or URI object to parse. Defaults to ''. ### Returns - **?Uri** - New Uri instance or null if parsing fails. ### Example ```php $uri = Uri::tryNew('https://example.com'); ``` ``` -------------------------------- ### Demonstrate URI Immutability Source: https://github.com/thephpleague/uri/blob/master/_autodocs/INDEX.md Modification methods return new instances, leaving the original object unchanged. ```php $original = Uri::new('https://example.com/path'); $modified = $original->withPath('/newpath'); // $original is unchanged ``` -------------------------------- ### Integrate HttpFactory with Dependency Injection Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http-factory.md Register the factory in a container and inject it into PSR-7 aware libraries. ```php use League\/Uri\/HttpFactory; use Psr\/Http\/Message\/MessageFactoryInterface; $uriFactory = new HttpFactory(); \/\/ Use in dependency injection containers $container['psr7.uri_factory'] = function() { return new HttpFactory(); }; \/\/ Inject into PSR-7 aware libraries $httpClient = new SomeHttpClient( uriFactory: $container['psr7.uri_factory'] ); \/\/ Clients use the factory $uri = $httpClient->getUriFactory()->createUri('https:\/\/example.com\/api'); ``` -------------------------------- ### Validate URI Construction Source: https://github.com/thephpleague/uri/blob/master/_autodocs/errors.md Shows how to validate a URI builder state before building or use guard() to throw a SyntaxError. ```php use League\Uri\Builder; use League\Uri\Exceptions\SyntaxError; $builder = new Builder() ->scheme('https') ->host('example.com') ->port(8080); // Check validity before building if ($builder->validate()) { $uri = $builder->build(); } else { echo "Cannot build URI with current state"; } // Or use guard() to throw try { $uri = $builder->guard()->build(); } catch (SyntaxError $e) { handleError($e); } ``` -------------------------------- ### withScheme() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Returns a new instance of the Http object with the specified scheme. ```APIDOC ## withScheme(string $scheme) ### Description Returns a new instance with the updated scheme. ### Parameters - **$scheme** (string) - Required - New scheme ### Return Type Http - New immutable instance ### Throws - **SyntaxError** - If scheme is invalid ``` -------------------------------- ### host() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/builder.md Sets the host component of the URI. ```APIDOC ## host(BackedEnum|Stringable|string|null $host) ### Description Sets the host component. ### Parameters - **$host** (BackedEnum|Stringable|string|null) - Required - Hostname or null ### Returns - **Builder** ### Throws - **SyntaxError** - If host is invalid ``` -------------------------------- ### Expand simple variables Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri-template.md Replaces placeholders with provided values in a standard URI path. ```php $template = new UriTemplate('https://example.com/{username}/{repo}'); $uri = $template->expand([ 'username' => 'octocat', 'repo' => 'Hello-World' ]); // https://example.com/octocat/Hello-World ``` -------------------------------- ### Build URIs Programmatically Source: https://github.com/thephpleague/uri/blob/master/_autodocs/INDEX.md Construct a URI using the Builder pattern. ```php $uri = (new Builder()) ->scheme('https') ->host('api.example.com') ->path('/users') ->query('page=1&limit=50') ->build(); ``` -------------------------------- ### Create Urn Instance Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/urn.md Method signature for creating a new Urn instance from a string or object. ```php public static function new( Rfc3986Uri|WhatWgUrl|Stringable|string $urn ): self ``` -------------------------------- ### Update Query String Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Returns a new instance with the updated query string. ```php public function withQuery(string $query): Http ``` ```php $uri = $http->withQuery('filter=active&sort=name'); ``` -------------------------------- ### withQuery() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Returns a new instance of the Http object with the specified query string. ```APIDOC ## withQuery(string $query) ### Description Returns a new instance with the updated query. ### Parameters - **$query** (string) - Required - New query string ### Return Type Http ``` -------------------------------- ### getHost() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Retrieves the host component of the URI. ```APIDOC ## getHost() ### Description Get the host component. ### Signature `public function getHost(): string` ### Return Type `string` — Host or empty string ``` -------------------------------- ### Integrate PSR-7 and PSR-17 Source: https://github.com/thephpleague/uri/blob/master/_autodocs/getting-started.md Use Http for PSR-7 compliance and HttpFactory for PSR-17 factory support. ```php use League\/Uri\/Http; \/\/ Create PSR-7 compliant URI $uri = Http::new('https:\/\/example.com\/path?query=value'); \/\/ Works with any PSR-7 client $response = $httpClient->get((string) $uri); \/\/ Immutable modification $modified = $uri ->withScheme('http') ->withPath('\/api\/v2') ->withQuery('limit=50'); ``` ```php use League\/Uri\/HttpFactory; $factory = new HttpFactory(); $uri = $factory->createUri('https:\/\/example.com\/api'); \/\/ Inject into PSR-17 aware libraries $client = new SomeClient(uriFactory: $factory); ``` -------------------------------- ### withNss() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/urn.md Returns a new instance with an updated namespace-specific string. ```APIDOC ## withNss() ### Description Return new instance with updated namespace-specific string. ### Parameters - **$nss** (BackedEnum|Stringable|string) - Required - New NSS ### Return Type `Urn` — New instance with updated NSS ### Throws - **SyntaxError** - If NSS is invalid ``` -------------------------------- ### Create a file URI from a Unix path Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Converts a standard Unix filesystem path into a file URI. ```php $uri = Uri::fromUnixPath('/home/user/documents/file.txt'); echo $uri->toString(); // 'file:///home/user/documents/file.txt' ``` -------------------------------- ### Check same document in PHP Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Determines if the provided URI refers to the same document as the current instance. ```php public function isSameDocument( Rfc3986Uri|WhatWgUrl|UriInterface|Stringable|Urn|string $uri ): bool ``` -------------------------------- ### Create URI with HttpFactory Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http-factory.md Generate a PSR-7 UriInterface object from a string or an empty URI, and use it with HTTP clients. ```php use League\/Uri\/HttpFactory; $factory = new HttpFactory(); \/\/ Create from string $uri = $factory->createUri('https:\/\/user:pass@example.com:8080\/path?query=value#frag'); \/\/ Create empty URI $empty = $factory->createUri(); \/\/ Use with PSR-7 clients $httpClient = new GuzzleHttp\/Client(); $response = $httpClient->get($uri->__toString()); ``` -------------------------------- ### Create Http instance from string Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Use the new() method to parse a URI string into an Http object. Throws SyntaxError for invalid URIs or PSR-7 requirement violations. ```php use League\Uri\Http; $uri = Http::new('https://user:pass@example.com:8080/path?query=value#frag'); echo $uri->getScheme(); // 'https' echo $uri->getHost(); // 'example.com' echo $uri->getPort(); // 8080 ``` -------------------------------- ### Handle Template Expansion Source: https://github.com/thephpleague/uri/blob/master/_autodocs/errors.md Compares lenient expansion with strict expansion that throws TemplateCanNotBeExpanded. ```php use League\Uri\UriTemplate; use League\Uri\UriTemplate\TemplateCanNotBeExpanded; $template = new UriTemplate('{scheme}://{host}/{path}'); // Lenient: missing vars become empty $uri = $template->expand($vars); // Strict: missing vars throw exception try { $uri = $template->expandOrFail($vars); } catch (TemplateCanNotBeExpanded $e) { echo "Missing: " . implode(', ', $e->getMissingVariables()); } ``` -------------------------------- ### Catching SyntaxError in League URI Source: https://github.com/thephpleague/uri/blob/master/_autodocs/errors.md Demonstrates how to catch SyntaxError exceptions and inspect the error message to handle specific URI validation failures. ```php use League\Uri\Exceptions\SyntaxError; use League\Uri\Uri; try { $uri = Uri::new('http://invalid..host/path'); } catch (SyntaxError $e) { echo "Syntax error: " . $e->getMessage(); // Can differentiate error types by message inspection if (str_contains($e->getMessage(), 'host')) { handleInvalidHost(); } } ``` -------------------------------- ### toComponents() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Retrieves all URI components as an associative array. ```APIDOC ## toComponents() ### Description Returns an associative array containing all URI components. ### Signature `public function toComponents(): array` ### Return Keys scheme, user, pass, host, port, path, query, fragment ``` -------------------------------- ### Set Path Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/builder.md Sets the path component. Throws a SyntaxError if the path contains invalid characters. ```php public function path( BackedEnum|Stringable|string|null $path ): self ``` ```php $builder->path('/users/123/profile'); ``` -------------------------------- ### Safe URI Parsing Source: https://github.com/thephpleague/uri/blob/master/_autodocs/errors.md Demonstrates parsing a URI safely by either checking for null or catching exceptions. ```php use League\Uri\Uri; // Returns null on error $uri = Uri::tryNew($userInput); if ($uri === null) { echo "Invalid URI format"; return; } // Or catch exception try { $uri = Uri::new($userInput); } catch (Exception $e) { logError($e); exit(400); } ``` -------------------------------- ### Builder Constructor Signature Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/builder.md The constructor accepts optional URI components as arguments. ```php public function __construct( BackedEnum|Stringable|string|null $scheme = null, BackedEnum|Stringable|string|null $username = null, BackedEnum|Stringable|string|null $password = null, BackedEnum|Stringable|string|null $host = null, BackedEnum|int|null $port = null, BackedEnum|Stringable|string|null $path = null, BackedEnum|Stringable|string|null $query = null, BackedEnum|Stringable|string|null $fragment = null ) ``` -------------------------------- ### withRComponent() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/urn.md Returns a new instance with an updated r-component. ```APIDOC ## withRComponent() ### Description Return new instance with updated r-component. ### Parameters - **$rComponent** (BackedEnum|Stringable|string|null) - Required - Resolution component or null to remove ### Return Type `Urn` — New instance ### Throws - **SyntaxError** - If r-component is invalid ``` -------------------------------- ### Uri::fromData() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/uri.md Creates a data URI from raw data with an optional MIME type and additional parameters. ```APIDOC ## Uri::fromData() ### Description Creates a data URI from raw data with optional MIME type and parameters. ### Parameters - **$data** (BackedEnum|Stringable|string) - Required - Data content - **$mimetype** (string) - Optional - MIME type (defaults to 'text/plain') - **$parameters** (string) - Optional - Additional parameters (e.g., 'charset=utf-8') ### Return Type Uri ### Throws - **SyntaxError** - If the MIME type is invalid ``` -------------------------------- ### withPath() Source: https://github.com/thephpleague/uri/blob/master/_autodocs/api-reference/http.md Returns a new instance of the Http object with the specified path. ```APIDOC ## withPath(string $path) ### Description Returns a new instance with the updated path. ### Parameters - **$path** (string) - Required - New path ### Return Type Http ```