Commit 2e4f8eed authored by Thorsten Buss's avatar Thorsten Buss

FIX: wrong assertCurrency on MoneyConstructor if currency was a string - fixed and add tests

parent ccadbff2
......@@ -40,6 +40,7 @@ class Money implements \JsonSerializable, Jsonable, Arrayable {
public function __construct($amount, $currency=null) {
// FIX: if $amount is a money obj
if ($amount instanceof Money) {
// given currency, or the currency of the amount
$currency = $currency ?? $amount->currency;
$amount->assertCurrency($currency);
$amount = $amount->value();
......@@ -304,12 +305,19 @@ class Money implements \JsonSerializable, Jsonable, Arrayable {
/**
* assertCurrency.
*
* @param Currency $currency
* @param Currency|string $currency
*
* @throws \InvalidArgumentException
*/
protected function assertCurrency(Currency $currency) {
if (!$this->isCurrency($currency)) {
protected function assertCurrency($currency) {
if (empty($currency))
return;
if (!$currency instanceof Currency) {
$currency = new Currency($currency);
}
if (!$this->isCurrency($currency)) {
throw new \InvalidArgumentException('Different currencies "' . $this->currency . '" and "' . $currency . '"');
}
}
......
......@@ -71,6 +71,31 @@ class MoneyTest extends \PHPUnit_Framework_TestCase {
}
}
public function testConstructorCurrencyAssert() {
$amount = 123456;
$m = $this->money($amount, $this->currency());
// asserts are OK
$this->money($m, null);
$this->money($m, 'EUR');
$this->money($m, $this->currency());
try {
$this->money($m, 'USD');
$this->fail('No Exception of asserting USD is not EUR');
} catch (\InvalidArgumentException $e) {
$x = 'Different currencies';
$this->assertTrue(substr($e->getMessage(), 0, strlen($x)) === $x, 'correct ExceptionMessage');
}
try {
$this->money($m, new Currency('USD'));
$this->fail('No Exception of asserting USD is not EUR 2');
} catch (\InvalidArgumentException $e) {
$x = 'Different currencies';
$this->assertTrue(substr($e->getMessage(), 0, strlen($x)) === $x, 'correct ExceptionMessage');
}
}
public function testConstructorWithMoneyObj() {
$amount = 123456;
$m = $this->money($amount, $this->currency());
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment