PSR-7 UriInterface Adapter Class
The Url
class does not support immutability as it is required by the
PSR-7 UriInterface.
But the package provides an adapter class Crwlr\Url\Psr\Uri
which has an
instance of the Url
class in a private property and thus assures immutability.
Usage Example
$url = 'https://user:password@www.example.com:1234/foo/bar?some=query#fragment';
$uri = Url::parsePsr7($url); // Or instead: new Crwlr\Url\Psr\Uri($url);
var_dump($uri->getScheme()); // => 'https'
var_dump($uri->getAuthority()); // => 'user:password@www.example.com:1234'
var_dump($uri->getUserInfo()); // => 'user:password'
var_dump($uri->getHost()); // => 'www.example.com'
var_dump($uri->getPort()); // => 1234
var_dump($uri->getPath()); // => '/foo/bar'
var_dump($uri->getQuery()); // => 'some=query'
var_dump($uri->getFragment()); // => 'fragment'
// Keep in mind an instance of Uri is immutable and all the methods that change
// state (method names starting with "with") return a new instance:
$newUri = $uri->withScheme('http');
var_dump($uri->getScheme()); // => 'https'
var_dump($newUri->getScheme()); // => 'http'
$uri = $newUri->withUserInfo('u', 'p');
var_dump($uri->getUserInfo()); // => 'u:p'
$uri = $uri->withHost('foo.bar.com');
var_dump($uri->getHost()); // => 'foo.bar.com'
$uri = $uri->withPort(666);
var_dump($uri->getPort()); // => 666
$uri = $uri->withPath('/path');
var_dump($uri->getPath()); // => '/path'
$uri = $uri->withQuery('foo=bar');
var_dump($uri->getQuery()); // => 'foo=bar
$uri = $uri->withFragment('baz');
var_dump($uri->getFragment()); // => 'baz'
var_dump($uri->__toString());
// => 'http://u:p@foo.bar.com:666/path?foo=bar#baz'
If you're already having a Url
instance, the fastest and easiest way to get a PSR-7 compatible object from it, is the toPsr7()
method.
use Crwlr\Url\Url;
$url = Url::parse('https://www.example.com/foo');
$uri = $url->toPsr7();