-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
dev: Provide a Url class to sanitize domains
- Loading branch information
1 parent
e8988c1
commit a5d7dcd
Showing
2 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |