Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 26 additions & 6 deletions src/ASN1/Universal/Integer.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@

class Integer extends ASN1Object
{
/** @var int */
public $value;
/** @var \GMP */
private $gmpValue;

/**
* @param Identifier $identifier
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
42 changes: 42 additions & 0 deletions tests/ASN1/Universal/IntegerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}