Skip to content

Commit ce7ead3

Browse files
committed
:octocat: DNS-over-HTTPS setter improvement
1 parent fbe8122 commit ce7ead3

File tree

2 files changed

+37
-7
lines changed

2 files changed

+37
-7
lines changed

src/HTTPOptionsTrait.php

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
namespace chillerlan\HTTP;
1616

17-
use function trim;
17+
use function parse_url, sprintf, strtolower, trim;
1818
use const CURLOPT_CAINFO, CURLOPT_CAPATH;
1919

2020
/**
@@ -143,16 +143,25 @@ protected function set_curl_options(array $curl_options):void{
143143
$this->curl_options = $curl_options;
144144
}
145145

146+
/**
147+
* @throws \chillerlan\HTTP\ClientException
148+
*/
146149
protected function set_dns_over_https(string|null $dns_over_https):void{
147-
$this->dns_over_https = null;
148150

149-
if($dns_over_https !== null){
150-
$dns_over_https = trim($dns_over_https);
151+
if($dns_over_https === null){
152+
$this->dns_over_https = null;
151153

152-
if(!empty($dns_over_https)){
153-
$this->dns_over_https = $dns_over_https;
154-
}
154+
return;
155155
}
156156

157+
$dns_over_https = trim($dns_over_https);
158+
$parsed = parse_url($dns_over_https);
159+
160+
if(empty($dns_over_https) || !isset($parsed['scheme'], $parsed['host']) || strtolower($parsed['scheme']) !== 'https'){
161+
throw new ClientException(sprintf('invalid DNS-over-HTTPS URL: "%s"', $dns_over_https));
162+
}
163+
164+
$this->dns_over_https = $dns_over_https;
157165
}
166+
158167
}

tests/HTTPOptionsTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,25 @@ public function testInvalidUserAgentException():void{
2828
new HTTPOptions(['user_agent' => '']);
2929
}
3030

31+
public function testSetDnsOverHttpsURL():void{
32+
$url = 'https://example.com';
33+
34+
$options = new HTTPOptions(['dns_over_https' => $url]);
35+
$this::assertSame($url, $options->dns_over_https);
36+
37+
// unset
38+
$options->dns_over_https = null;
39+
$this::assertNull($options->dns_over_https);
40+
41+
// via magic
42+
$options->dns_over_https = $url;
43+
$this::assertSame($url, $options->dns_over_https);
44+
}
45+
46+
public function testSetDnsOverHttpsURLException():void{
47+
$this->expectException(ClientExceptionInterface::class);
48+
$this->expectExceptionMessage('invalid DNS-over-HTTPS URL');
49+
50+
new HTTPOptions(['dns_over_https' => 'http://nope.whatever']);
51+
}
3152
}

0 commit comments

Comments
 (0)