Skip to content

Commit

Permalink
[9.x] Allow using static closures as callable for macros (#43589)
Browse files Browse the repository at this point in the history
* [9.x] Allow using static closures as callable for macros

* Update Macroable.php

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
paulbalandan and taylorotwell committed Aug 8, 2022
1 parent 56c6314 commit 93090dc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/Illuminate/Macroable/Traits/Macroable.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use BadMethodCallException;
use Closure;
use ReflectionClass;
use ReflectionFunction;
use ReflectionMethod;

trait Macroable
Expand Down Expand Up @@ -118,7 +119,15 @@ public function __call($method, $parameters)
$macro = static::$macros[$method];

if ($macro instanceof Closure) {
$macro = $macro->bindTo($this, static::class);
$reflection = new ReflectionFunction($macro);

$bindable = $reflection->getClosureScopeClass() === null || $reflection->getClosureThis() !== null;

if ($bindable) {
$macro = $macro->bindTo($this, static::class);
} else {
$macro = $macro->bindTo(null, static::class);
}
}

return $macro(...$parameters);
Expand Down
12 changes: 12 additions & 0 deletions tests/Support/SupportMacroableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ public function testClassBasedMacrosNoReplace()
$this->assertSame('foo', $instance->methodThree());
}

public function testSettingMacroUsingStaticClosures()
{
TestMacroable::macro('staticFn', static function () {
return 'I am unbound.';
});
TestMacroable::macro('speed', static fn () => 'I am speed.');
$instance = new TestMacroable;

$this->assertSame('I am unbound.', $instance->staticFn());
$this->assertSame('I am speed.', $instance->speed());
}

public function testFlushMacros()
{
TestMacroable::macro('flushMethod', function () {
Expand Down

0 comments on commit 93090dc

Please sign in to comment.