From e431f75ad49de92706fd9d5a30c9dc5ed4ee7246 Mon Sep 17 00:00:00 2001 From: Nabeel S Date: Tue, 28 Jan 2020 12:42:46 -0500 Subject: [PATCH] Add getRootDomain() to Utils (#514) --- app/Support/Utils.php | 26 ++++++++++++++++++++++++++ tests/UtilsTest.php | 18 ++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/app/Support/Utils.php b/app/Support/Utils.php index 69ceccd7..6889e2bb 100644 --- a/app/Support/Utils.php +++ b/app/Support/Utils.php @@ -3,6 +3,7 @@ namespace App\Support; use Illuminate\Contracts\Container\BindingResolutionException; +use Illuminate\Support\Str; use Nwidart\Modules\Facades\Module; /** @@ -47,4 +48,29 @@ class Utils return $installer->isEnabled(); } + + /** + * Get the domain from a URL + * + * @param string $url + * + * @return string + */ + public static function getRootDomain(string $url): string + { + if (!Str::contains($url, ['https://', 'http://'])) { + $url = 'http://'.$url; + } + + $domain = parse_url($url, PHP_URL_HOST); + $domain = explode('.', $domain); + $len = count($domain); + if ($len == 1) { + return $domain[0]; + } + + $domain = $domain[$len - 2].'.'.$domain[$len - 1]; + + return $domain; + } } diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php index 6c0f4003..7c27e4dc 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -69,4 +69,22 @@ class UtilsTest extends TestCase $hex_code = \App\Support\ICAO::createHexCode(); $this->assertNotNull($hex_code); } + + public function testGetDomain() + { + $tests = [ + 'http://phpvms.net', + 'https://phpvms.net', + 'phpvms.net', + 'https://phpvms.net/index.php', + 'https://demo.phpvms.net', + 'https://demo.phpvms.net/file/index.php', + ]; + + foreach ($tests as $case) { + $this->assertEquals('phpvms.net', \App\Support\Utils::getRootDomain($case)); + } + + $this->assertEquals('phpvms', \App\Support\Utils::getRootDomain('http://phpvms')); + } }