| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace SpomkyLabs\Pki\X509\GeneralName; |
| 6 |
|
| 7 |
use LogicException; |
| 8 |
use function mb_strlen; |
| 9 |
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString; |
| 10 |
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType; |
| 11 |
use SpomkyLabs\Pki\ASN1\Type\TaggedType; |
| 12 |
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; |
| 13 |
use UnexpectedValueException; |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
abstract class IPAddress extends GeneralName |
| 23 |
{ |
| 24 |
protected function __construct( |
| 25 |
protected string $ip, |
| 26 |
protected ?string $mask = null |
| 27 |
) { |
| 28 |
parent::__construct(self::TAG_IP_ADDRESS); |
| 29 |
} |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
public static function fromChosenASN1(UnspecifiedType $el): GeneralName |
| 35 |
{ |
| 36 |
$octets = $el->asOctetString() |
| 37 |
->string(); |
| 38 |
return match (mb_strlen($octets, '8bit')) { |
| 39 |
4, 8 => IPv4Address::fromOctets($octets), |
| 40 |
16, 32 => IPv6Address::fromOctets($octets), |
| 41 |
default => throw new UnexpectedValueException('Invalid octet length for IP address.'), |
| 42 |
}; |
| 43 |
} |
| 44 |
|
| 45 |
public function string(): string |
| 46 |
{ |
| 47 |
return $this->ip . (isset($this->mask) ? '/' . $this->mask : ''); |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
public function address(): string |
| 54 |
{ |
| 55 |
return $this->ip; |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
public function hasMask(): bool |
| 62 |
{ |
| 63 |
return isset($this->mask); |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
public function mask(): string |
| 70 |
{ |
| 71 |
if (! $this->hasMask()) { |
| 72 |
throw new LogicException('mask is not set.'); |
| 73 |
} |
| 74 |
return $this->mask; |
| 75 |
} |
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
abstract protected function octets(): string; |
| 81 |
|
| 82 |
protected function choiceASN1(): TaggedType |
| 83 |
{ |
| 84 |
return ImplicitlyTaggedType::create($this->tag, OctetString::create($this->octets())); |
| 85 |
} |
| 86 |
} |