2022-09-13 15:13:11 +02:00
|
|
|
<?php
|
|
|
|
// EndPoint.php
|
|
|
|
// Created: 2021-04-30
|
2024-08-01 22:16:38 +00:00
|
|
|
// Updated: 2024-08-01
|
2022-09-13 15:13:11 +02:00
|
|
|
|
|
|
|
namespace Index\Net;
|
|
|
|
|
|
|
|
use InvalidArgumentException;
|
|
|
|
use JsonSerializable;
|
|
|
|
use Stringable;
|
|
|
|
use Index\IEquatable;
|
|
|
|
|
2024-08-01 22:16:38 +00:00
|
|
|
/**
|
|
|
|
* Represents a generic network end point.
|
|
|
|
*/
|
2022-09-13 15:13:11 +02:00
|
|
|
abstract class EndPoint implements JsonSerializable, Stringable, IEquatable {
|
|
|
|
abstract public function equals(mixed $other): bool;
|
|
|
|
abstract public function __toString(): string;
|
|
|
|
|
|
|
|
public function jsonSerialize(): mixed {
|
|
|
|
return (string)$this;
|
|
|
|
}
|
|
|
|
|
2024-08-01 22:16:38 +00:00
|
|
|
/**
|
|
|
|
* Attempts to parse a string into a known end point object.
|
|
|
|
*
|
|
|
|
* @param string $string String to parse.
|
|
|
|
* @throws InvalidArgumentException If $string does not contain a valid end point string.
|
|
|
|
* @return EndPoint Representation of the given string.
|
|
|
|
*/
|
|
|
|
public static function parse(string $string): EndPoint {
|
|
|
|
if($string === '')
|
|
|
|
throw new InvalidArgumentException('$string is not a valid endpoint string.');
|
|
|
|
|
|
|
|
$firstChar = $string[0];
|
|
|
|
|
|
|
|
if($firstChar === '/' || str_starts_with($string, 'unix:'))
|
|
|
|
$endPoint = UnixEndPoint::parse($string);
|
2022-09-13 15:13:11 +02:00
|
|
|
elseif($firstChar === '[') { // IPv6
|
2024-08-01 22:16:38 +00:00
|
|
|
if(str_contains($string, ']:'))
|
|
|
|
$endPoint = IPEndPoint::parse($string);
|
2022-09-13 15:13:11 +02:00
|
|
|
else
|
2024-08-01 22:16:38 +00:00
|
|
|
$endPoint = new IPEndPoint(IPAddress::parse(trim($string, '[]')), 0);
|
2022-09-13 15:13:11 +02:00
|
|
|
} elseif(is_numeric($firstChar)) { // IPv4
|
2024-08-01 22:16:38 +00:00
|
|
|
if(str_contains($string, ':'))
|
|
|
|
$endPoint = IPEndPoint::parse($string);
|
2022-09-13 15:13:11 +02:00
|
|
|
else
|
2024-08-01 22:16:38 +00:00
|
|
|
$endPoint = new IPEndPoint(IPAddress::parse($string), 0);
|
2022-09-13 15:13:11 +02:00
|
|
|
} else { // DNS
|
2024-08-01 22:16:38 +00:00
|
|
|
if(str_contains($string, ':'))
|
|
|
|
$endPoint = DnsEndPoint::parse($string);
|
2022-09-13 15:13:11 +02:00
|
|
|
else
|
2024-08-01 22:16:38 +00:00
|
|
|
$endPoint = new DnsEndPoint($string, 0);
|
2022-09-13 15:13:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return $endPoint;
|
|
|
|
}
|
|
|
|
}
|