Skip to content

Commit

Permalink
#87 Allow static Macros
Browse files Browse the repository at this point in the history
Money and Currency override the Macroable __callStatic
method, effectively disabling static macros.

Add a check in, if the statically called method exists
as a macro, then call the macro instead.
  • Loading branch information
Luke-Shepp committed Jul 20, 2023
1 parent 5f5efe5 commit b43e60f
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/Currency.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,9 @@
*/
class Currency implements Arrayable, Castable, Jsonable, JsonSerializable, Renderable
{
use Macroable;
use Macroable {
__callStatic as protected macroableCallStatic;
}

protected string $currency;

Expand Down Expand Up @@ -235,6 +237,10 @@ public function __construct(string $currency)

public static function __callStatic(string $method, array $arguments): Currency
{
if (static::hasMacro($method)) {
return static::macroableCallStatic($method, $arguments);
}

return new self($method);
}

Expand Down
8 changes: 7 additions & 1 deletion src/Money.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,9 @@
*/
class Money implements Arrayable, Castable, Jsonable, JsonSerializable, Renderable
{
use Macroable;
use Macroable {
__callStatic as protected macroableCallStatic;
}

const ROUND_HALF_UP = PHP_ROUND_HALF_UP;

Expand Down Expand Up @@ -283,6 +285,10 @@ protected function convertAmount(int|float $amount, bool $convert = false): int|

public static function __callStatic(string $method, array $arguments): Money
{
if (static::hasMacro($method)) {
return static::macroableCallStatic($method, $arguments);
}

$convert = isset($arguments[1]) && is_bool($arguments[1]) && $arguments[1];

return new self($arguments[0], new Currency($method), $convert);
Expand Down
7 changes: 7 additions & 0 deletions tests/CurrencyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,11 @@ public function testResetCurrencies()
$this->assertEmpty(Currency::getCurrencies());
Currency::setCurrencies($currencies);
}

public function testStaticMacro()
{
Currency::macro('testMacro', fn () => Currency::EUR());

$this->assertEquals(Currency::EUR(), Currency::testMacro());
}
}
7 changes: 7 additions & 0 deletions tests/MoneyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -411,4 +411,11 @@ public function testMakingMutable()
$this->assertTrue($money->isImmutable());
$this->assertFalse($money->mutable()->isImmutable());
}

public function testStaticMacro()
{
Money::macro('testMacro', fn () => Money::USD(1099));

$this->assertEquals(Money::USD(1099), Money::testMacro());
}
}

0 comments on commit b43e60f

Please sign in to comment.