diff --git a/src/Illuminate/Support/Optional.php b/src/Illuminate/Support/Optional.php index faa63bd86dc5..091fdde21214 100644 --- a/src/Illuminate/Support/Optional.php +++ b/src/Illuminate/Support/Optional.php @@ -4,7 +4,9 @@ class Optional { - use Traits\Macroable; + use Traits\Macroable { + __call as macroCall; + } /** * The underlying object. @@ -49,5 +51,9 @@ public function __call($method, $parameters) if (is_object($this->value)) { return $this->value->{$method}(...$parameters); } + + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } } } diff --git a/tests/Support/SupportHelpersTest.php b/tests/Support/SupportHelpersTest.php index 776c9708cb2b..2337e0d779b1 100755 --- a/tests/Support/SupportHelpersTest.php +++ b/tests/Support/SupportHelpersTest.php @@ -9,6 +9,7 @@ use Illuminate\Support\Arr; use Illuminate\Support\Str; use PHPUnit\Framework\TestCase; +use Illuminate\Support\Optional; class SupportHelpersTest extends TestCase { @@ -768,6 +769,31 @@ public function something() })->something()); } + public function testOptionalIsMacroable() + { + Optional::macro('present', function () { + if (is_object($this->value)) { + return $this->value->present(); + } + + return new Optional(null); + }); + + $this->assertNull(optional(null)->present()->something()); + + $this->assertEquals('$10.00', optional(new class { + public function present() + { + return new class { + public function something() + { + return '$10.00'; + } + }; + } + })->present()->something()); + } + public function testTransform() { $this->assertEquals(10, transform(5, function ($value) {