Skip to content

Commit

Permalink
Merge pull request #761 from moneyphp/mod_int
Browse files Browse the repository at this point in the history
Allow divisor in mod to be a number as well
  • Loading branch information
frederikbosch committed Nov 22, 2023
2 parents 6fcdcaf + 80094f7 commit d1eecea
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/Money.php
Original file line number Diff line number Diff line change
Expand Up @@ -272,14 +272,20 @@ public function divide(int|string $divisor, int $roundingMode = self::ROUND_HALF
* the remainder after dividing the value by
* the given factor.
*/
public function mod(Money $divisor): Money
public function mod(Money|int|string $divisor): Money
{
// Note: non-strict equality is intentional here, since `Currency` is `final` and reliable.
if ($this->currency != $divisor->currency) {
throw new InvalidArgumentException('Currencies must be identical');
if ($divisor instanceof self) {
// Note: non-strict equality is intentional here, since `Currency` is `final` and reliable.
if ($this->currency != $divisor->currency) {
throw new InvalidArgumentException('Currencies must be identical');
}

$divisor = $divisor->amount;
} else {
$divisor = (string) Number::fromNumber($divisor);
}

return new self(self::$calculator::mod($this->amount, $divisor->amount), $this->currency);
return new self(self::$calculator::mod($this->amount, $divisor), $this->currency);
}

/**
Expand Down
31 changes: 31 additions & 0 deletions tests/MoneyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,37 @@ public function itCalculatesTheModulusOfAnAmount($left, $right, $expected): void
self::assertEquals($expected, $money->getAmount());
}

/**
* @psalm-param positive-int $left
* @psalm-param positive-int $right
* @psalm-param numeric-string $expected
*
* @dataProvider modExamples
* @test
*/
public function itCalculatesTheModulusOfNumber($left, $right, $expected): void
{
$money = new Money($left, new Currency(self::CURRENCY));

$money = $money->mod($right);

self::assertInstanceOf(Money::class, $money);
self::assertEquals($expected, $money->getAmount());
}

/**
* @test
*/
public function itThrowsWhenDivisorIsInvalidStringArgument(): void
{
$money = new Money(self::AMOUNT, new Currency(self::CURRENCY));

$this->expectException(InvalidArgumentException::class);

/** @psalm-suppress UnusedMethodCall this method throws */
$money->mod('test');
}

/**
* @test
*/
Expand Down

0 comments on commit d1eecea

Please sign in to comment.