1
0
mirror of https://github.com/danog/math.git synced 2025-01-22 13:41:12 +01:00

BigRational now implements Serializable

This allows for a more compact serialized representation.
This commit is contained in:
Benjamin Morel 2015-06-12 23:35:34 +02:00
parent b1239d9f44
commit 095ae53a9b
3 changed files with 52 additions and 3 deletions

View File

@ -753,8 +753,6 @@ class BigDecimal implements \Serializable
/**
* This method is required by interface Serializable and MUST NOT be accessed directly.
*
* Accessing this method directly would bypass consistency checks and break immutability.
*
* @internal
*
* @param string $value

View File

@ -7,7 +7,7 @@ namespace Brick\Math;
*
* This class is immutable.
*/
class BigRational
class BigRational implements \Serializable
{
/**
* The numerator.
@ -387,4 +387,37 @@ class BigRational
return $this->numerator . '/' . $this->denominator;
}
/**
* This method is required by interface Serializable and SHOULD NOT be accessed directly.
*
* @internal
*
* @return string
*/
public function serialize()
{
return $this->numerator . '/' . $this->denominator;
}
/**
* This method is required by interface Serializable and MUST NOT be accessed directly.
*
* @internal
*
* @param string $value
*
* @return void
*/
public function unserialize($value)
{
if ($this->numerator !== null || $this->denominator !== null) {
throw new \LogicException('unserialize() is an internal function, it must not be called directly.');
}
list ($numerator, $denominator) = explode('/', $value);
$this->numerator = BigInteger::of($numerator);
$this->denominator = BigInteger::of($denominator);
}
}

View File

@ -550,4 +550,22 @@ class BigRationalTest extends AbstractTestCase
['34327948737247817984738927598572389', '-1', '-34327948737247817984738927598572389'],
];
}
public function testSerialize()
{
$numerator = '-1234567890987654321012345678909876543210123456789';
$denominator = '347827348278374374263874681238374983729873401984091287439827467286';
$rational = BigRational::of($numerator, $denominator);
$this->assertBigRationalEquals($numerator, $denominator, unserialize(serialize($rational)));
}
/**
* @expectedException \LogicException
*/
public function testDirectCallToUnserialize()
{
BigRational::of(1, 2)->unserialize('123/456');
}
}