Skip to content

Commit 57ee5ad

Browse files
Merge pull request #27 from michael-rubel/feat/underlying-object-forwarding
Forward methods to underlying object in `Number`
2 parents c35a24e + a119662 commit 57ee5ad

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/Collection/Primitive/Number.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,17 @@
2929
* @method static static from(int|string $number, int $scale = 2)
3030
* @method static static makeOrNull(int|string|null $number, int $scale = 2)
3131
*
32+
* @method string abs()
33+
* @method string add(float|int|string $value)
34+
* @method string divide(float|int|string $value)
35+
* @method string multiply(float|int|string $value)
36+
* @method string mod(float|int|string $value)
37+
* @method string pow(int|string $value)
38+
* @method string sqrt()
39+
* @method string subtract(float|int|string $value)
40+
*
41+
* @see \PHP\Math\BigNumber\BigNumber
42+
*
3243
* @extends ValueObject<TKey, TValue>
3344
*/
3445
class Number extends ValueObject
@@ -86,4 +97,32 @@ public function asFloat(): float
8697
{
8798
return (float) $this->bigNumber->getValue();
8899
}
100+
101+
/**
102+
* Get the underlying `BigNumber` object.
103+
*
104+
* @return BigNumber
105+
*/
106+
public function asBigNumber(): BigNumber
107+
{
108+
return $this->bigNumber;
109+
}
110+
111+
/**
112+
* Forward call to underlying object if the method
113+
* doesn't exist in `Number` and doesn't have a macro.
114+
*
115+
* @param string $method
116+
* @param array $parameters
117+
*
118+
* @return mixed
119+
*/
120+
public function __call($method, $parameters)
121+
{
122+
if (static::hasMacro($method)) {
123+
return parent::__call($method, $parameters);
124+
}
125+
126+
return $this->bigNumber->{$method}(...$parameters)->getValue();
127+
}
89128
}

tests/Unit/Primitive/NumberTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,21 @@
2222
$this->assertSame(36000.50, $valueObject->asFloat());
2323
});
2424

25+
test('number as a big number', function () {
26+
$number = new Number('20000.793', 3);
27+
$this->assertEquals(new BigNumber('20000.793', 3, false), $number->asBigNumber());
28+
});
29+
30+
test('number can be divided using magic call', function () {
31+
$number = new Number('20000.793', 4);
32+
$this->assertSame('10000.3965', $number->divide(2));
33+
});
34+
35+
test('number can be multiplied using magic call', function () {
36+
$number = new Number('20000.793', 3);
37+
$this->assertSame('40001.586', $number->multiply(2));
38+
});
39+
2540
test('number can accept string', function () {
2641
$valueObject = new Number('1');
2742
$this->assertSame('1.00', $valueObject->value());

0 commit comments

Comments
 (0)