Trabalhando com URLs

As classes Url, UrlImmutable e UrlScript permitem gerar, analisar e manipular URLs facilmente.

Instalação e requisitos

Url

A classe Nette\Http\Url permite trabalhar facilmente com URLs e os seus componentes individuais, que são capturados neste diagrama:

schema  user  password  host   port    path        query  fragment
  |      |      |        |      |       |            |       |
/--\   /--\ /------\ /-------\ /--\/----------\ /--------\ /----\
http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer
\______\__________________________/
    |               |
 hostUrl        authority

A geração de URLs é intuitiva:

use Nette\Http\Url;

$url = new Url;
$url->setScheme('https')
	->setHost('localhost')
	->setPath('/edit')
	->setQueryParameter('foo', 'bar');

echo $url; // 'https://localhost/edit?foo=bar'

Também é possível analisar uma URL e manipulá-la posteriormente:

$url = new Url(
	'http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer',
);

A classe Url implementa a interface JsonSerializable e possui o método __toString(), então o objeto pode ser impresso ou usado em dados passados para json_encode().

echo $url;
echo json_encode([$url]);

Componentes da URL

Para retornar ou alterar os componentes individuais da URL, estes métodos estão disponíveis:

Setter Getter Valor retornado
setScheme(string $scheme) getScheme(): string 'http'
setUser(string $user) getUser(): string 'john'
setPassword(string $password) getPassword(): string 'xyz*12'
setHost(string $host) getHost(): string 'nette.org'
setPort(int $port) getPort(): ?int 8080
  getDefaultPort(): ?int 80
setPath(string $path) getPath(): string '/en/download'
setQuery(string|array $query) getQuery(): string 'name=param'
setFragment(string $fragment) getFragment(): string 'footer'
  getAuthority(): string 'john:xyz%2A12@nette.org:8080'
  getHostUrl(): string 'http://john:xyz%2A12@nette.org:8080'
  getAbsoluteUrl(): string URL completa

Aviso: Ao trabalhar com uma URL obtida de uma requisição HTTP, lembre-se de que ela não conterá o fragmento, pois o navegador não o envia para o servidor.

Também podemos trabalhar com parâmetros de consulta individuais usando:

Setter Getter
setQuery(string|array $query) getQueryParameters(): array
setQueryParameter(string $name, $val) getQueryParameter(string $name)

getDomain (int $level = 2)string

Retorna a parte direita ou esquerda do host. Funciona assim se o host for www.nette.org:

getDomain(1) 'org'
getDomain(2) 'nette.org'
getDomain(3) 'www.nette.org'
getDomain(0) 'www.nette.org'
getDomain(-1) 'www.nette'
getDomain(-2) 'www'
getDomain(-3) ''

isEqual (string|Url $anotherUrl)bool

Verifica se duas URLs são idênticas.

$url->isEqual('https://nette.org');

Url::isAbsolute (string $url)bool

Verifica se a URL é absoluta. Uma URL é considerada absoluta se começa com um esquema (por exemplo, http, https, ftp) seguido por dois pontos.

Url::isAbsolute('https://nette.org');    // true
Url::isAbsolute('//nette.org');          // false

Url::removeDotSegments (string $path)string

Normaliza o caminho na URL removendo os segmentos especiais . e ... O método remove elementos de caminho redundantes da mesma forma que os navegadores web fazem.

Url::removeDotSegments('/path/../subtree/./file.txt');  // '/subtree/file.txt'
Url::removeDotSegments('/../foo/./bar');                // '/foo/bar'
Url::removeDotSegments('./today/../file.txt');          // 'file.txt'

UrlImmutable

A classe Nette\Http\UrlImmutable é uma alternativa imutável à classe Url (semelhante a como DateTimeImmutable do PHP é a alternativa imutável a DateTime). Em vez de setters, ela possui os chamados withers, que não alteram o objeto, mas retornam novas instâncias com o valor modificado:

use Nette\Http\UrlImmutable;

$url = new UrlImmutable(
	'http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer',
);

$newUrl = $url
	->withUser('')
	->withPassword('')
	->withPath('/cs/');

echo $newUrl; // 'http://john:xyz%2A12@nette.org:8080/cs/?name=param#footer'

A classe UrlImmutable implementa a interface JsonSerializable e possui o método __toString(), então o objeto pode ser impresso ou usado em dados passados para json_encode().

echo $url;
echo json_encode([$url]);

Componentes da URL

Para retornar ou alterar os componentes individuais da URL, servem os métodos:

Wither Getter Valor retornado
withScheme(string $scheme) getScheme(): string 'http'
withUser(string $user) getUser(): string 'john'
withPassword(string $password) getPassword(): string 'xyz*12'
withHost(string $host) getHost(): string 'nette.org'
withPort(int $port) getPort(): ?int 8080
  getDefaultPort(): ?int 80
withPath(string $path) getPath(): string '/en/download'
withQuery(string|array $query) getQuery(): string 'name=param'
withFragment(string $fragment) getFragment(): string 'footer'
  getAuthority(): string 'john:xyz%2A12@nette.org:8080'
  getHostUrl(): string 'http://john:xyz%2A12@nette.org:8080'
  getAbsoluteUrl(): string URL completa

O método withoutUserInfo() remove user e password.

Também podemos trabalhar com parâmetros de consulta individuais usando:

Wither Getter
withQuery(string|array $query) getQueryParameters(): array
withQueryParameter(string $name, $val) getQueryParameter(string $name)

getDomain (int $level = 2)string

Retorna a parte direita ou esquerda do host. Funciona assim se o host for www.nette.org:

getDomain(1) 'org'
getDomain(2) 'nette.org'
getDomain(3) 'www.nette.org'
getDomain(0) 'www.nette.org'
getDomain(-1) 'www.nette'
getDomain(-2) 'www'
getDomain(-3) ''

resolve (string $reference): UrlImmutable

Deriva uma URL absoluta da mesma forma que um navegador processa links numa página HTML:

  • se o link for uma URL absoluta (contém esquema), ele é usado sem alterações
  • se o link começar com //, apenas o esquema da URL atual é adotado
  • se o link começar com /, um caminho absoluto da raiz do domínio é criado
  • em outros casos, a URL é construída relativamente ao caminho atual
$url = new UrlImmutable('https://example.com/path/page');
echo $url->resolve('../foo');           // 'https://example.com/foo'
echo $url->resolve('/bar');             // 'https://example.com/bar'
echo $url->resolve('sub/page.html');    // 'https://example.com/path/sub/page.html'

isEqual (string|Url $anotherUrl)bool

Verifica se duas URLs são idênticas.

$url->isEqual('https://nette.org');

UrlScript

A classe Nette\Http\UrlScript é descendente de UrlImmutable e a estende com outros componentes virtuais da URL, como o diretório raiz do projeto, etc. Assim como a classe pai, é um objeto imutável.

O diagrama a seguir mostra os componentes que UrlScript reconhece:

     baseUrl    basePath  relativePath  relativeUrl
        |          |        |               |
/---------------/-----\/--------\---------------------------\
http://nette.org/admin/script.php/pathinfo/?name=param#footer
                \_______________/\________/
                       |              |
                  scriptPath       pathInfo
  • baseUrl é o endereço URL base da aplicação, incluindo o domínio e a parte do caminho para o diretório raiz da aplicação
  • basePath é a parte do caminho para o diretório raiz da aplicação
  • scriptPath é o caminho para o script atual
  • relativePath é o nome do script (eventualmente outros segmentos do caminho) relativo a basePath
  • relativeUrl é toda a parte da URL após baseUrl, incluindo a query string e o fragmento.
  • pathInfo hoje em dia é uma parte da URL pouco utilizada após o nome do script

Para retornar partes da URL, estão disponíveis os métodos:

Getter Valor retornado
getScriptPath(): string '/admin/script.php'
getBasePath(): string '/admin/'
getBaseUrl(): string 'http://nette.org/admin/'
getRelativePath(): string 'script.php'
getRelativeUrl(): string 'script.php/pathinfo/?name=param#footer'
getPathInfo(): string '/pathinfo/'

Objetos UrlScript geralmente não são criados diretamente, mas são retornados pelo método Nette\Http\Request::getUrl() com os componentes já configurados corretamente para a requisição HTTP atual.

versão: 4.0