Skip to content

Commit

Permalink
Merge pull request #4 from epignosis/add-url-type
Browse files Browse the repository at this point in the history
Introduce URL type
  • Loading branch information
yrizos authored Jan 31, 2025
2 parents 56a2cb7 + 828e766 commit 5295cc4
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/String/Url.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Epignosis\Types\String;

use InvalidArgumentException;

use const FILTER_NULL_ON_FAILURE;
use const FILTER_SANITIZE_URL;
use const FILTER_VALIDATE_URL;

class Url extends NonEmptyString
{
public function __construct(string $value)
{
/** @var string|null $value */
$value = filter_var($value, FILTER_SANITIZE_URL, FILTER_NULL_ON_FAILURE);

if (!is_string($value) || !filter_var($value, FILTER_VALIDATE_URL)) {
throw new InvalidArgumentException('Url is invalid');
}

parent::__construct($value);
}
}
66 changes: 66 additions & 0 deletions tests/String/UrlTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace Epignosis\Types\Tests\String;

use Epignosis\Types\String\Url;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;

class UrlTest extends TestCase
{
public function test_CanBeCreatedByUrl(): void
{
$url = new Url('https://www.example.com');

$this->assertEquals('https://www.example.com', $url->getValue());
}

public function test_UrlIsTrimmed(): void
{
$url = new Url(' https://www.example.com ');

$this->assertEquals('https://www.example.com', $url->getValue());
}

public function test_CanBeCreatedByUrlWithTrailingSlash(): void
{
$url = new Url('https://www.example.com/');

$this->assertEquals('https://www.example.com/', $url->getValue());
}

public function test_CanBeCreatedByUrlWithQuery(): void
{
$url = new Url('https://www.example.com/?query=1');

$this->assertEquals('https://www.example.com/?query=1', $url->getValue());
}

public function test_CanBeCreatedByUrlWithFragment(): void
{
$url = new Url('https://www.example.com/#fragment');

$this->assertEquals('https://www.example.com/#fragment', $url->getValue());
}

public function test_CanBeCreatedByUrlWithQueryAndFragment(): void
{
$url = new Url('https://www.example.com/?query=1#fragment');

$this->assertEquals('https://www.example.com/?query=1#fragment', $url->getValue());
}

public function test_CanBeCreatedByUrlWithPort(): void
{
$url = new Url('https://www.example.com:8080');

$this->assertEquals('https://www.example.com:8080', $url->getValue());
}

public function test_CannotBeCreatedByInvalidUrl(): void
{
$this->expectException(InvalidArgumentException::class);

new Url('www.example.com');
}
}

0 comments on commit 5295cc4

Please sign in to comment.