From e3f70d5293309a85ec10ea118e7b8e3aa0042a0d Mon Sep 17 00:00:00 2001 From: Martin Bean Date: Fri, 16 May 2025 23:57:32 +0100 Subject: [PATCH] Add context attribute --- .../Container/Attributes/Context.php | 31 +++++++++++++++++++ .../ContextualAttributeBindingTest.php | 23 ++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 src/Illuminate/Container/Attributes/Context.php diff --git a/src/Illuminate/Container/Attributes/Context.php b/src/Illuminate/Container/Attributes/Context.php new file mode 100644 index 000000000000..a6dee5581ed6 --- /dev/null +++ b/src/Illuminate/Container/Attributes/Context.php @@ -0,0 +1,31 @@ +make(Repository::class)->get($attribute->key, $attribute->default); + } +} diff --git a/tests/Container/ContextualAttributeBindingTest.php b/tests/Container/ContextualAttributeBindingTest.php index 8c0d7f7f9f69..610e4a1d1cd8 100644 --- a/tests/Container/ContextualAttributeBindingTest.php +++ b/tests/Container/ContextualAttributeBindingTest.php @@ -11,6 +11,7 @@ use Illuminate\Container\Attributes\Authenticated; use Illuminate\Container\Attributes\Cache; use Illuminate\Container\Attributes\Config; +use Illuminate\Container\Attributes\Context; use Illuminate\Container\Attributes\CurrentUser; use Illuminate\Container\Attributes\Database; use Illuminate\Container\Attributes\Log; @@ -28,6 +29,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Filesystem\FilesystemManager; use Illuminate\Http\Request; +use Illuminate\Log\Context\Repository as ContextRepository; use Illuminate\Log\LogManager; use Mockery as m; use PHPUnit\Framework\TestCase; @@ -215,6 +217,20 @@ public function testRouteParameterAttribute() $container->make(RouteParameterTest::class); } + public function testContextAttribute(): void + { + $container = new Container; + + $container->singleton(ContextRepository::class, function () { + $context = m::mock(ContextRepository::class); + $context->shouldReceive('get')->once()->with('foo', null)->andReturn('foo'); + + return $context; + }); + + $container->make(ContextTest::class); + } + public function testStorageAttribute() { $container = new Container; @@ -425,6 +441,13 @@ public function __construct(#[Config('foo')] string $foo, #[Config('bar')] strin } } +final class ContextTest +{ + public function __construct(#[Context('foo')] string $foo) + { + } +} + final class DatabaseTest { public function __construct(#[Database('foo')] Connection $foo, #[Database('bar')] Connection $bar)