Skip to content

Commit

Permalink
improved Domain class for parsing urls and hosts
Browse files Browse the repository at this point in the history
  • Loading branch information
otis22 committed Dec 19, 2020
1 parent 8625476 commit 0f4b759
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .idea/php.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 39 additions & 7 deletions src/Url/Part/Domain.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,55 @@ final class Domain implements Stringify
/**
* @var string
*/
private $domain;
private $urlDomainOrHostName;

/**
* Domain constructor.
*
* @param string $domain
* @param string $urlDomainOrHostName
*/
public function __construct(string $domain)
public function __construct(string $urlDomainOrHostName)
{
$this->domain = $domain;
$this->urlDomainOrHostName = $urlDomainOrHostName;
}

/**
* @return string
* @inheritDoc
*/
public function asString(): string
{
return $this->domain;
return $this->isUrl()
? $this->domainFromHost($this->hostFromUrl())
: $this->domainFromHost($this->urlDomainOrHostName);
}

/**
* @return bool
*/
private function isUrl(): bool
{
return strpos($this->urlDomainOrHostName, 'http') === 0
&& strpos($this->urlDomainOrHostName, '.') !== false;
}

/**
* @return string
*/
private function hostFromUrl(): string
{
$parsed = parse_url($this->urlDomainOrHostName);
if (is_array($parsed) && isset($parsed['host'])) {
return $parsed['host'];
}
throw new \UnexpectedValueException("Can't parse url or host string - " . $this->urlDomainOrHostName);
}

/**
* @param string $host
* @return string
*/
private function domainFromHost(string $host): string
{
$exploded = explode('.', $host);
return $exploded[0];
}
}
40 changes: 39 additions & 1 deletion tests/Url/Part/DomainTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,49 @@

class DomainTest extends TestCase
{
public function testDomainToString(): void
public function testSimpleDomainToString(): void
{
$this->assertEquals(
"test",
(new Domain("test"))->asString()
);
}

public function testDomainFromHttpUrlToString(): void
{
$this->assertEquals(
"test",
(
new Domain("http://test.vetmanager.ru")
)->asString()
);
}

public function testDomainFromHttpsUrlToString(): void
{
$this->assertEquals(
"test",
(
new Domain("https://test.vetmanager.ru")
)->asString()
);
}

public function testDomainFromHostNameToString(): void
{
$this->assertEquals(
"test",
(
new Domain("test.vetmanager.ru")
)->asString()
);
}

public function testInvalidUrlThrowExceptionToString(): void
{
$this->expectException(\UnexpectedValueException::class);
(
new Domain("httpfsdfsdtest.")
)->asString();
}
}

0 comments on commit 0f4b759

Please sign in to comment.