<?php
 declare(strict_types=1); namespace SpomkyLabs\Pki\ASN1\Type\Primitive; use Brick\Math\BigInteger; use InvalidArgumentException; use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\PrimitiveType; use SpomkyLabs\Pki\ASN1\Type\UniversalClass; use SpomkyLabs\Pki\ASN1\Util\BigInt; use function gettype; use function is_int; use function is_scalar; use function is_string; use function sprintf; use function strval; abstract class Number extends Element { use UniversalClass; use PrimitiveType; private readonly BigInt $number; protected function __construct(int $tag, BigInteger|int|string $number) { parent::__construct($tag); if (! self::validateNumber($number)) { $var = is_scalar($number) ? strval($number) : gettype($number); throw new InvalidArgumentException(sprintf('"%s" is not a valid number.', $var)); } $this->number = BigInt::create($number); } abstract public static function create(BigInteger|int|string $number): self; public function number(): string { return $this->number->base10(); } public function getValue(): BigInteger { return $this->number->getValue(); } public function intNumber(): int { return $this->number->toInt(); } protected function encodedAsDER(): string { return $this->number->signedOctets(); } private static function validateNumber(mixed $num): bool { if (is_int($num)) { return true; } if (is_string($num) && preg_match('/-?\d+/', $num) === 1) { return true; } if ($num instanceof BigInteger) { return true; } return false; } } 