Parser y constructor de URL

Las clases Url, UrlImmutable y UrlScript facilitan el manejo, análisis y manipulación de URLs.

Instalación y requisitos

Url

La clase Nette\Http\Url facilita el trabajo con la URL y sus componentes individuales, que se esbozan en este diagrama:

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

La generación de URL es 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'

También puede analizar la URL y luego manipularla:

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

Los siguientes métodos están disponibles para obtener o cambiar componentes individuales de la URL:

Setter Getter Valor devuelto
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 'nette.org:8080'
  getHostUrl(): string 'http://nette.org:8080'
  getAbsoluteUrl(): string URL completa

También podemos operar con parámetros de consulta individuales utilizando:

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

El método getDomain(int $level = 2) devuelve la parte derecha o izquierda del host. Así funciona si el host es 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) ''

La clase Url implementa la interfaz JsonSerializable y tiene un método __toString() para que el objeto pueda imprimirse o utilizarse en datos pasados a json_encode().

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

El método isEqual(string|Url $anotherUrl): bool comprueba si las dos URL son idénticas.

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

UrlImmutable

La clase Nette\Http\UrlImmutable es una alternativa inmutable a la clase Url (al igual que en PHP DateTimeImmutable es una alternativa inmutable a DateTime). En lugar de setters, tiene los llamados withers, que no cambian el objeto, sino que devuelven nuevas instancias con un 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('/en/');

echo $newUrl; // 'http://nette.org:8080/en/?name=param#footer'

Los siguientes métodos están disponibles para obtener o cambiar componentes URL individuales:

Obtener Valor devuelto
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 'nette.org:8080'
  getHostUrl(): string 'http://nette.org:8080'
  getAbsoluteUrl(): string URL completa

También podemos operar con parámetros de consulta individuales utilizando:

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

El método getDomain(int $level = 2) funciona igual que el método en Url. El método withoutUserInfo() elimina user y password.

La clase UrlImmutable implementa la interfaz JsonSerializable y tiene un método __toString() para que el objeto pueda imprimirse o utilizarse en datos pasados a json_encode().

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

El método isEqual(string|Url $anotherUrl): bool comprueba si las dos URL son idénticas.

UrlScript

La clase Nette\Http\UrlScript es descendiente de UrlImmutable y distingue además estas partes lógicas de la URL:

     baseUrl    basePath  relativePath  relativeUrl
        |          |        |               |
/---------------/-----\/--------\---------------------------\
http://nette.org/admin/script.php/pathinfo/?name=param#footer
                \_______________/\________/
                       |              |
                  scriptPath       pathInfo

Los siguientes métodos están disponibles para obtener estas partes:

Getter Valor devuelto
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/'

No creamos el objeto UrlScript directamente, sino que el método Nette\Http\Request::getUrl() lo devuelve.

versión: 4.0