Skip to content

Commit

Permalink
dev: Provide a Url class to sanitize domains
Browse files Browse the repository at this point in the history
  • Loading branch information
marien-probesys committed Jun 20, 2024
1 parent e8988c1 commit a5d7dcd
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/Utils/Url.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

// This file is part of Bileto.
// Copyright 2022-2024 Probesys
// SPDX-License-Identifier: AGPL-3.0-or-later

namespace App\Utils;

class Url
{
public static function sanitizeDomain(string $domain): string
{
// idn_to_ascii allows to transform an unicode domain to an
// ASCII representation
// @see https://en.wikipedia.org/wiki/Punycode
// It also lowercases the string.
$domain = idn_to_ascii($domain, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46);

if ($domain === false) {
$domain = '';
}

$domain = trim($domain);

return $domain;
}
}
49 changes: 49 additions & 0 deletions tests/Utils/UrlTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

// This file is part of Bileto.
// Copyright 2022-2024 Probesys
// SPDX-License-Identifier: AGPL-3.0-or-later

namespace App\Tests\Utils;

use App\Utils\Url;
use PHPUnit\Framework\TestCase;

class UrlTest extends TestCase
{
public function testSanitizeDomain(): void
{
$domain = 'example.com';

$sanitizedDomain = Url::sanitizeDomain($domain);

$this->assertEquals('example.com', $sanitizedDomain);
}

public function testSanitizeDomainTrimsSpaces(): void
{
$domain = ' example.com ';

$sanitizedDomain = Url::sanitizeDomain($domain);

$this->assertEquals('example.com', $sanitizedDomain);
}

public function testSanitizeDomainLowercasesTheDomain(): void
{
$domain = 'EXAMPLE.com';

$sanitizedDomain = Url::sanitizeDomain($domain);

$this->assertEquals('example.com', $sanitizedDomain);
}

public function testSanitizeDomainConvertsDomainToAscii(): void
{
$domain = 'éxample.com';

$sanitizedDomain = Url::sanitizeDomain($domain);

$this->assertEquals('xn--xample-9ua.com', $sanitizedDomain);
}
}

0 comments on commit a5d7dcd

Please sign in to comment.