diff --git a/src/ASN1/Universal/Integer.php b/src/ASN1/Universal/Integer.php index bef2891..a799846 100644 --- a/src/ASN1/Universal/Integer.php +++ b/src/ASN1/Universal/Integer.php @@ -19,8 +19,8 @@ class Integer extends ASN1Object { - /** @var int */ - public $value; + /** @var \GMP */ + private $gmpValue; /** * @param Identifier $identifier @@ -88,7 +88,29 @@ public static function encodeValue($value): string public function __toString(): string { - return (string)$this->value; + return gmp_strval($this->gmpValue); + } + + public function toGMP(): \GMP + { + return $this->gmpValue; + } + + /** + * Magic getter for backward compatibility. + * TODO remove in the next major release + * Allows access to the old public $value property. + * + * @param string $name + * @return string|null + */ + public function __get(string $name) + { + if ($name === 'value') { + return gmp_strval($this->gmpValue); + } + + return null; } public function setValue(Content $content) @@ -107,9 +129,7 @@ public function setValue(Content $content) $number = gmp_sub($number, gmp_pow(2, 8 * $contentLength - 1)); } - $value = gmp_strval($number); - - $this->value = $value; + $this->gmpValue = $number; } public static function create($integer, $options = []): self diff --git a/tests/ASN1/Universal/IntegerTest.php b/tests/ASN1/Universal/IntegerTest.php index b8c3be0..53f0019 100644 --- a/tests/ASN1/Universal/IntegerTest.php +++ b/tests/ASN1/Universal/IntegerTest.php @@ -247,4 +247,46 @@ public function testFromBinaryWithOffset() $this->assertEquals($originalObject2, $parsedObject); $this->assertEquals(9, $offset); } + + public function testToGMP() + { + $object = Integer::create(123); + $gmp = $object->toGMP(); + $this->assertInstanceOf(\GMP::class, $gmp); + $this->assertEquals('123', gmp_strval($gmp)); + + $object = Integer::create(-456); + $gmp = $object->toGMP(); + $this->assertInstanceOf(\GMP::class, $gmp); + $this->assertEquals('-456', gmp_strval($gmp)); + + $object = Integer::create(0); + $gmp = $object->toGMP(); + $this->assertInstanceOf(\GMP::class, $gmp); + $this->assertEquals('0', gmp_strval($gmp)); + + // Test with big integer + $bigint = gmp_strval(gmp_pow(2, 128)); + $object = Integer::create($bigint); + $gmp = $object->toGMP(); + $this->assertInstanceOf(\GMP::class, $gmp); + $this->assertEquals($bigint, gmp_strval($gmp)); + } + + public function testBackwardCompatibilityValueProperty() + { + $object = Integer::create(123); + $this->assertEquals('123', $object->value); + + $object = Integer::create(-456); + $this->assertEquals('-456', $object->value); + + $object = Integer::create(0); + $this->assertEquals('0', $object->value); + + // Test with big integer + $bigint = gmp_strval(gmp_pow(2, 128)); + $object = Integer::create($bigint); + $this->assertEquals($bigint, $object->value); + } }