Uri parses string on construction

This commit is contained in:
PJ Dietz 2015-04-21 15:15:53 -04:00
parent 0fabbc5cb1
commit 2e2b9d57c0
2 changed files with 86 additions and 1 deletions

View File

@ -26,6 +26,42 @@ class Uri implements UriInterface
/** @var string */ /** @var string */
private $fragment = ""; private $fragment = "";
/**
* @param string $uri A string representation of a URI.
*/
public function __construct($uri = "")
{
if (is_string($uri) && $uri !== "") {
$parsed = parse_url($uri);
if ($parsed !== false) {
if (isset($parsed["scheme"])) {
$this->scheme = $parsed["scheme"];
}
if (isset($parsed["host"])) {
$this->host = $parsed["host"];
}
if (isset($parsed["port"])) {
$this->port = $parsed["port"];
}
if (isset($parsed["user"])) {
$this->user = $parsed["user"];
}
if (isset($parsed["pass"])) {
$this->password = $parsed["pass"];
}
if (isset($parsed["path"])) {
$this->path = $parsed["path"];
}
if (isset($parsed["query"])) {
$this->query = $parsed["query"];
}
if (isset($parsed["fragment"])) {
$this->fragment = $parsed["fragment"];
}
}
}
}
/** /**
* Retrieve the scheme component of the URI. * Retrieve the scheme component of the URI.
* *
@ -79,6 +115,7 @@ class Uri implements UriInterface
// Host // Host
$authority .= $host; $authority .= $host;
// Port: Include only if set AND non-standard. // Port: Include only if set AND non-standard.
$port = $this->getPort(); $port = $this->getPort();
if ($port !== null) { if ($port !== null) {
@ -468,7 +505,6 @@ class Uri implements UriInterface
} }
return $string; return $string;
} }
/** /**

View File

@ -648,4 +648,53 @@ class UriTest extends \PHPUnit_Framework_TestCase
], ],
]; ];
} }
/**
* @covers WellRESTed\Message\Uri::__construct()
* @covers WellRESTed\Message\Uri::__toString()
* @dataProvider stringUriProvider
*/
public function testUriCreatedFromStringNormalizesString($expected, $input)
{
$uri = new Uri($input);
$this->assertSame($expected, (string) $uri);
}
public function stringUriProvider()
{
return [
[
"http://localhost/path",
"http://localhost:80/path"
],
[
"https://localhost/path",
"https://localhost:443/path"
],
[
"https://my.sub.sub.domain.com/path",
"https://my.sub.sub.domain.com/path"
],
[
"https://user:password@localhost:4430/path?cat=molly&dog=bear#fragment",
"https://user:password@localhost:4430/path?cat=molly&dog=bear#fragment"
],
[
"/path",
"/path"
],
[
"//double/slash",
"//double/slash"
],
[
"no/slash",
"no/slash"
],
[
"*",
"*"
]
];
}
} }