index/src/Net/EndPoint.php

49 lines
1.5 KiB
PHP

<?php
// EndPoint.php
// Created: 2021-04-30
// Updated: 2022-02-28
namespace Index\Net;
use InvalidArgumentException;
use JsonSerializable;
use Stringable;
use Index\IEquatable;
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;
}
public static function parse(string $endPoint): EndPoint {
if($endPoint === '')
throw new InvalidArgumentException('$endPoint is not a valid endpoint string.');
$firstChar = $endPoint[0];
if($firstChar === '/' || str_starts_with($endPoint, 'unix:'))
$endPoint = UnixEndPoint::parse($endPoint);
elseif($firstChar === '[') { // IPv6
if(str_contains($endPoint, ']:'))
$endPoint = IPEndPoint::parse($endPoint);
else
$endPoint = new IPEndPoint(IPAddress::parse(trim($endPoint, '[]')), 0);
} elseif(is_numeric($firstChar)) { // IPv4
if(str_contains($endPoint, ':'))
$endPoint = IPEndPoint::parse($endPoint);
else
$endPoint = new IPEndPoint(IPAddress::parse($endPoint), 0);
} else { // DNS
if(str_contains($endPoint, ':'))
$endPoint = DnsEndPoint::parse($endPoint);
else
$endPoint = new DnsEndPoint($endPoint, 0);
}
return $endPoint;
}
}