index/src/Net/EndPoint.php

59 lines
1.8 KiB
PHP
Raw Normal View History

2022-09-13 15:13:11 +02:00
<?php
// EndPoint.php
// Created: 2021-04-30
// Updated: 2024-08-01
2022-09-13 15:13:11 +02:00
namespace Index\Net;
use InvalidArgumentException;
use JsonSerializable;
use Stringable;
use Index\IEquatable;
/**
* 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;
}
/**
* 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
if(str_contains($string, ']:'))
$endPoint = IPEndPoint::parse($string);
2022-09-13 15:13:11 +02:00
else
$endPoint = new IPEndPoint(IPAddress::parse(trim($string, '[]')), 0);
2022-09-13 15:13:11 +02:00
} elseif(is_numeric($firstChar)) { // IPv4
if(str_contains($string, ':'))
$endPoint = IPEndPoint::parse($string);
2022-09-13 15:13:11 +02:00
else
$endPoint = new IPEndPoint(IPAddress::parse($string), 0);
2022-09-13 15:13:11 +02:00
} else { // DNS
if(str_contains($string, ':'))
$endPoint = DnsEndPoint::parse($string);
2022-09-13 15:13:11 +02:00
else
$endPoint = new DnsEndPoint($string, 0);
2022-09-13 15:13:11 +02:00
}
return $endPoint;
}
}