<?php
 declare(strict_types=1); namespace SpomkyLabs\Pki\X509\GeneralName; use LogicException; use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString; use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType; use SpomkyLabs\Pki\ASN1\Type\TaggedType; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; use UnexpectedValueException; use function mb_strlen; abstract class IPAddress extends GeneralName { protected function __construct( protected string $ip, protected ?string $mask = null ) { parent::__construct(self::TAG_IP_ADDRESS); } public static function fromChosenASN1(UnspecifiedType $el): GeneralName { $octets = $el->asOctetString() ->string(); return match (mb_strlen($octets, '8bit')) { 4, 8 => IPv4Address::fromOctets($octets), 16, 32 => IPv6Address::fromOctets($octets), default => throw new UnexpectedValueException('Invalid octet length for IP address.'), }; } public function string(): string { return $this->ip . (isset($this->mask) ? '/' . $this->mask : ''); } public function address(): string { return $this->ip; } public function hasMask(): bool { return isset($this->mask); } public function mask(): string { if (! $this->hasMask()) { throw new LogicException('mask is not set.'); } return $this->mask; } abstract protected function octets(): string; protected function choiceASN1(): TaggedType { return ImplicitlyTaggedType::create($this->tag, OctetString::create($this->octets())); } } 