Permalink
Browse files

added Url::format()

  • Loading branch information...
1 parent 2435a55 commit da0e1085aba3c8006cf38495285b0b6c82edfae2 @kriswallsmith committed Mar 24, 2012
Showing with 60 additions and 5 deletions.
  1. +39 −5 lib/Buzz/Util/Url.php
  2. +21 −0 test/Buzz/Test/Util/UrlTest.php
View
44 lib/Buzz/Util/Url.php
@@ -39,11 +39,6 @@ public function __construct($url)
$this->components = $components;
}
- public function getUrl()
- {
- return $this->url;
- }
-
public function getScheme()
{
return $this->parseUrl('scheme');
@@ -127,6 +122,45 @@ public function getResource()
return $resource;
}
+ /**
+ * Returns a formatted URL.
+ */
+ public function format($pattern)
+ {
+ static $map = array(
+ 's' => 'getScheme',
+ 'u' => 'getUser',
+ 'a' => 'getPassword',
+ 'h' => 'getHostname',
+ 'o' => 'getPort',
+ 'p' => 'getPath',
+ 'q' => 'getQueryString',
+ 'f' => 'getFragment',
+ 'H' => 'getHost',
+ 'R' => 'getResource',
+ );
+
+ $url = '';
+
+ $parts = str_split($pattern);
+ while ($part = current($parts)) {
+ if (isset($map[$part])) {
+ $method = $map[$part];
+ $url .= $this->$method();
+ } elseif ('\\' == $part) {
+ $url .= next($parts);
+ } elseif (!ctype_alpha($part)) {
+ $url .= $part;
+ } else {
+ throw new \InvalidArgumentException(sprintf('The format character "%s" is invalid.', $part));
+ }
+
+ next($parts);
+ }
+
+ return $url;
+ }
+
private function parseUrl($component = null, $default = null)
{
if (null === $component) {
View
21 test/Buzz/Test/Util/UrlTest.php
@@ -33,4 +33,25 @@ public function testInvalidUrl()
$this->setExpectedException('InvalidArgumentException');
new Url('http://localhost:123456');
}
+
+ /**
+ * @dataProvider providePattern
+ */
+ public function testFormat($input, $pattern, $expected)
+ {
+ $url = new Url($input);
+ $this->assertEquals($expected, $url->format($pattern));
+ }
+
+ public function providePattern()
+ {
+ $full = 'http://foo:bar@example.com:123/asdf?tweedle=dee#dum';
+ $host = 'example.com';
+
+ return array(
+ array($full, 's://u:a@h:op?q#f', 'http://foo:bar@example.com:123/asdf?tweedle=dee#dum'),
+ array($full, 'HR', 'http://example.com:123/asdf?tweedle=dee'),
+ array($host, 'HR', 'http://example.com/'),
+ );
+ }
}

0 comments on commit da0e108

Please sign in to comment.