Skip to content

Forward methods to underlying object in Number #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 23, 2022
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
39 changes: 39 additions & 0 deletions src/Collection/Primitive/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@
* @method static static from(int|string $number, int $scale = 2)
* @method static static makeOrNull(int|string|null $number, int $scale = 2)
*
* @method string abs()
* @method string add(float|int|string $value)
* @method string divide(float|int|string $value)
* @method string multiply(float|int|string $value)
* @method string mod(float|int|string $value)
* @method string pow(int|string $value)
* @method string sqrt()
* @method string subtract(float|int|string $value)
*
* @see \PHP\Math\BigNumber\BigNumber
*
* @extends ValueObject<TKey, TValue>
*/
class Number extends ValueObject
Expand Down Expand Up @@ -86,4 +97,32 @@ public function asFloat(): float
{
return (float) $this->bigNumber->getValue();
}

/**
* Get the underlying `BigNumber` object.
*
* @return BigNumber
*/
public function asBigNumber(): BigNumber
{
return $this->bigNumber;
}

/**
* Forward call to underlying object if the method
* doesn't exist in `Number` and doesn't have a macro.
*
* @param string $method
* @param array $parameters
*
* @return mixed
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return parent::__call($method, $parameters);
}

return $this->bigNumber->{$method}(...$parameters)->getValue();
}
}
15 changes: 15 additions & 0 deletions tests/Unit/Primitive/NumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@
$this->assertSame(36000.50, $valueObject->asFloat());
});

test('number as a big number', function () {
$number = new Number('20000.793', 3);
$this->assertEquals(new BigNumber('20000.793', 3, false), $number->asBigNumber());
});

test('number can be divided using magic call', function () {
$number = new Number('20000.793', 4);
$this->assertSame('10000.3965', $number->divide(2));
});

test('number can be multiplied using magic call', function () {
$number = new Number('20000.793', 3);
$this->assertSame('40001.586', $number->multiply(2));
});

test('number can accept string', function () {
$valueObject = new Number('1');
$this->assertSame('1.00', $valueObject->value());
Expand Down