From 2e2b9d57c0a06246cb8fc5fc45c6e04b5b7e2c88 Mon Sep 17 00:00:00 2001 From: PJ Dietz Date: Tue, 21 Apr 2015 15:15:53 -0400 Subject: [PATCH] Uri parses string on construction --- src/Message/Uri.php | 38 +++++++++++++++++++++- test/tests/unit/Message/UriTest.php | 49 +++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) diff --git a/src/Message/Uri.php b/src/Message/Uri.php index 43c318f..5231082 100644 --- a/src/Message/Uri.php +++ b/src/Message/Uri.php @@ -26,6 +26,42 @@ class Uri implements UriInterface /** @var string */ 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. * @@ -79,6 +115,7 @@ class Uri implements UriInterface // Host $authority .= $host; + // Port: Include only if set AND non-standard. $port = $this->getPort(); if ($port !== null) { @@ -468,7 +505,6 @@ class Uri implements UriInterface } return $string; - } /** diff --git a/test/tests/unit/Message/UriTest.php b/test/tests/unit/Message/UriTest.php index 809b04f..ec9e63b 100644 --- a/test/tests/unit/Message/UriTest.php +++ b/test/tests/unit/Message/UriTest.php @@ -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" + ], + [ + "*", + "*" + ] + ]; + } }