Skip to content

Commit 20b6f36

Browse files
committed
Improve HostRecord class
1 parent 7693c25 commit 20b6f36

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

HostRecord.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
use function is_object;
3232
use function preg_match;
3333
use function rawurldecode;
34+
use function strpos;
3435
use function strtolower;
3536
use function substr;
3637

@@ -120,6 +121,8 @@ final class HostRecord implements JsonSerializable
120121
private ?string $hostAsUnicode = null;
121122
private bool $isIpVersionLoaded = false;
122123
private ?string $ipVersion = null;
124+
private bool $isIpValueLoaded = false;
125+
private ?string $ipValue = null;
123126

124127
private function __construct(
125128
public readonly ?string $value,
@@ -190,6 +193,36 @@ public function ipVersion(): ?string
190193
return $this->ipVersion;
191194
}
192195

196+
public function ipValue(): ?string
197+
{
198+
if (!$this->isIpValueLoaded) {
199+
$this->isIpValueLoaded = true;
200+
$this->ipValue = (function (): ?string {
201+
if (HostType::RegisteredName === $this->type) {
202+
return null;
203+
}
204+
205+
if (HostType::Ipv4 === $this->type) {
206+
return $this->value;
207+
}
208+
209+
$ip = substr((string) $this->value, 1, -1);
210+
if (HostType::Ipv6 !== $this->type) {
211+
return substr($ip, (int) strpos($ip, '.') + 1);
212+
}
213+
214+
$pos = strpos($ip, '%');
215+
if (false === $pos) {
216+
return $ip;
217+
}
218+
219+
return substr($ip, 0, $pos).'%'.rawurldecode(substr($ip, $pos + 3));
220+
})();
221+
}
222+
223+
return $this->ipValue;
224+
}
225+
193226
public static function isValid(Stringable|string|null $host): bool
194227
{
195228
try {

0 commit comments

Comments
 (0)