Naify\Psr\Message\Uri クラス

implements Naify\Psr\Contract\UriInterface, Stringable

PSR-7 URI 実装 — UriInterface

URL 文字列を parse_url() でパースし、各コンポーネントへのアクセスを提供する。 すべての with*() メソッドは不変(clone して返す)。

使用例

$uri = new Uri('https://example.com:8080/path?q=1#frag');
echo $uri->getScheme();   // "https"
echo $uri->getHost();     // "example.com"
echo $uri->getPort();     // 8080
echo $uri->getPath();     // "/path"
echo $uri->getQuery();    // "q=1"
echo $uri;                // "https://example.com:8080/path?q=1#frag"

設計意図

Uri
readonly 化は各 with メソッドの PHP 8.5 clone with 対応と初期化経路の確認を前提とする。 PHP 8.3 の再初期化は __clone() 内だけであり、clone 後の代入には使えない。

プロパティ

名前型説明
private $scheme string スキーム(http / https 等、小文字)
private $userInfo string user[:password] 形式の userInfo
private $host string ホスト名(小文字)
private $port ?int 非標準ポートのみ保持する。標準ポートは null
private $path string パス部分
private $query string ? を除いたクエリ文字列
private $fragment string # を除いたフラグメント

メソッド

メソッド説明
public __construct(string $uri = ): URI 文字列を parse して各コンポーネントへ分解する
public getScheme(): string URI のスキームを返す
public getAuthority(): string URI の authority 部分を返す
public getUserInfo(): string URI に含まれる user info を返す
public getHost(): string URI のホスト名を返す
public getPort(): ?int URI のポート番号を返す
public getPath(): string URI のパス部分を返す
public getQuery(): string URI のクエリ文字列を返す
public getFragment(): string URI のフラグメントを返す
public withScheme(string $scheme): static スキームを変更した新しいインスタンスを返す 8.5 → clone with
public withUserInfo(string $user, ?string $password): static ユーザー情報を変更した新しいインスタンスを返す 8.5 → clone with
public withHost(string $host): static ホスト名を変更した新しいインスタンスを返す 8.5 → clone with
public withPort(?int $port): static ポート番号を変更した新しいインスタンスを返す 8.5 → clone with
public withPath(string $path): static パスを変更した新しいインスタンスを返す 8.5 → clone with
public withQuery(string $query): static クエリ文字列を変更した新しいインスタンスを返す 8.5 → clone with
public withFragment(string $fragment): static フラグメントを変更した新しいインスタンスを返す 8.5 → clone with
private encodeComponent(string $value, string $delimiters): string 部品で使用できない文字と不完全な % をエンコードする。既存の %HH は保持する。
private encodeUserInfo(string $user, ?string $password): string ユーザー名とパスワード内の区切り文字を保護して連結する。
private filterPort(?int $port): ?int ポート番号をフィルタする(標準ポートは null にする)