Skip to content

Commit

Permalink
Adding URI fragments
Browse files Browse the repository at this point in the history
  • Loading branch information
JustSteveKing committed Oct 12, 2020
1 parent fb3a6d8 commit a74edb1
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/Uri.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ class Uri
*/
private ParameterBag $query;

/**
* @var string|null
*/
private ?string $fragment = null;

/**
* @return self
*/
Expand All @@ -41,6 +46,8 @@ public static function build(): self
*/
public static function fromString(string $uri): self
{
$original = $uri;

$uri = parse_url($uri);

if (! is_array($uri)) {
Expand All @@ -59,6 +66,12 @@ public static function fromString(string $uri): self
$url->addQuery($uri['query']);
}

$fragment = parse_url($original, PHP_URL_FRAGMENT);

if (! is_null($fragment)) {
$url->addFragment($fragment);
}

return $url;
}

Expand Down Expand Up @@ -142,11 +155,40 @@ public function query(): ParameterBag
return $this->query;
}

/**
* @param string $fragment
* @return self
*/
public function addFragment(string $fragment): self
{
if (is_null($fragment)) {
return $this;
}

$this->fragment = (substr($fragment, 0, 1) === '#') ? $fragment : "#{$fragment}";

return $this;
}

/**
* @return string|null
*/
public function fragment():? string
{
return $this->fragment;
}

/**
* @return string
*/
public function __toString(): string
{
return $this->toString();
}

/**
* @return string
*/
public function toString(): string
{
$url = "{$this->scheme}://{$this->host}";
Expand All @@ -164,6 +206,10 @@ public function toString(): string
$url .= '?' . implode('&', $collection);
}

if (! is_null($this->fragment)) {
$url .= "{$this->fragment}";
}

return $url;
}
}
38 changes: 38 additions & 0 deletions tests/UriTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,30 @@ public function it_will_set_the_query()
);
}

/**
* @test
*/
public function it_will_set_the_fragment()
{
$url = Uri::build();

$this->assertNull($url->fragment());

$url->addFragment('test');

$this->assertEquals(
'#test',
$url->fragment()
);

$url->addFragment('#with-hash');

$this->assertEquals(
'#with-hash',
$url->fragment()
);
}

/**
* @test
* @throws RuntimeException
Expand Down Expand Up @@ -142,5 +166,19 @@ public function it_will_convert_to_a_string()
$this->url,
(string) $url
);

$newUrl = "{$this->url}#add-fragment";

$url = Uri::fromString($newUrl);

$this->assertEquals(
$newUrl,
$url->toString()
);

$this->assertEquals(
$newUrl,
(string) $url
);
}
}

0 comments on commit a74edb1

Please sign in to comment.