Skip to content

Commit 9f52edd

Browse files
committed
add UrlHelper::getSiteUrl
1 parent 94901f2 commit 9f52edd

File tree

2 files changed

+55
-2
lines changed

2 files changed

+55
-2
lines changed

src/Helpers/UrlHelper.php

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,6 @@ public static function url2Link(string $url, array $protocols = ['http', 'https'
182182
}
183183

184184

185-
186185
/**
187186
* 获取域名
188187
* @param string $url
@@ -257,4 +256,37 @@ public static function getUri(array $server = []): string {
257256
}
258257

259258

259+
/**
260+
* 获取站点URL
261+
* @param string $url 网址
262+
* @param array $server server信息
263+
* @return string
264+
*/
265+
public static function getSiteUrl(string $url, array $server = []): string {
266+
if (empty($url)) {
267+
$url = self::getUrl($server);
268+
}
269+
270+
if (!stripos($url, '://')) {
271+
$url = 'http://' . $url;
272+
}
273+
274+
if (!ValidateHelper::isUrl($url)) {
275+
return '';
276+
}
277+
278+
$arr = parse_url($url);
279+
$port = $arr['port'] ?? null;
280+
$scheme = $arr['scheme'] ?? null;
281+
if (!empty($port) && !in_array($port, [80, 443])) {
282+
$url = "{$scheme}://{$arr['host']}:{$port}/";
283+
} else {
284+
$url = "{$scheme}://{$arr['host']}/";
285+
}
286+
287+
$url = strtolower($url);
288+
289+
return self::formatUrl($url);
290+
}
291+
260292
}

tests/Unit/UrlHelperTest.php

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public function testCnUrlencodeDecode() {
2424
$res1 = UrlHelper::cnUrlencode($url);
2525
$res2 = UrlHelper::cnUrldecode($res1);
2626

27-
$str = '©℗';
27+
$str = '©℗';
2828
$str2 = StringHelper::escape($str);
2929
$res3 = UrlHelper::cnUrldecode($str2);
3030

@@ -119,4 +119,25 @@ public function testGetDomainUrlUri() {
119119
$this->assertEmpty($res9);
120120
}
121121

122+
123+
public function testGetSiteUrl() {
124+
$server = OsHelperTest::$server;
125+
$str = 'hello world!';
126+
$url1 = 'http://www.test.loc/index.php?name=hello&age=20&from=world';
127+
$url2 = 'rpc.test.com:8899/hello';
128+
129+
$res1 = UrlHelper::getSiteUrl($str);
130+
$this->assertEmpty($res1);
131+
132+
$res2 = UrlHelper::getSiteUrl('', $server);
133+
$this->assertNotEmpty($res2);
134+
135+
$res3 = UrlHelper::getSiteUrl($url1);
136+
$this->assertNotEmpty($res3);
137+
138+
$res4 = UrlHelper::getSiteUrl($url2);
139+
$this->assertNotEmpty($res4);
140+
}
141+
142+
122143
}

0 commit comments

Comments
 (0)