Skip to content

Commit 12dfad8

Browse files
[12.x] fix: use contextual bindings in class dependency resolution (#55090)
* fix: use contextual bindings in class dependency resolution * formatting --------- Co-authored-by: Taylor Otwell <taylor@laravel.com>
1 parent 468fb74 commit 12dfad8

File tree

2 files changed

+17
-11
lines changed

2 files changed

+17
-11
lines changed

src/Illuminate/Container/Container.php

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1187,17 +1187,12 @@ protected function resolveClass(ReflectionParameter $parameter)
11871187
{
11881188
$className = Util::getParameterClassName($parameter);
11891189

1190-
// First, we check if the dependency has been explicitly bound in the container
1191-
// and if so, we will resolve it directly from there to respect any explicit
1192-
// bindings the developer has defined rather than using any default value.
1193-
if ($this->bound($className)) {
1194-
return $this->make($className);
1195-
}
1196-
1197-
// If no binding exists, we will check if a default value has been defined for
1198-
// the parameter. If it has, we should return it to avoid overriding any of
1199-
// the developer specified default values for the constructor parameters.
1200-
if ($parameter->isDefaultValueAvailable()) {
1190+
// First we will check if a default value has been defined for the parameter.
1191+
// If it has, and no explicit binding exists, we should return it to avoid
1192+
// overriding any of the developer specified defaults for the parameters.
1193+
if ($parameter->isDefaultValueAvailable() &&
1194+
! $this->bound($className) &&
1195+
$this->findInContextualBindings($className) === null) {
12011196
return $parameter->getDefaultValue();
12021197
}
12031198

tests/Container/ContainerTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,17 @@ public function testResolutionOfClassWithDefaultParameters()
319319
$this->assertInstanceOf(ContainerConcreteStub::class, $instance->default);
320320
}
321321

322+
public function testResolutionOfClassWithDefaultParametersAndContextualBindings()
323+
{
324+
$container = new Container;
325+
326+
$container->when(ContainerClassWithDefaultValueStub::class)
327+
->needs(ContainerConcreteStub::class)
328+
->give(fn () => new ContainerConcreteStub);
329+
$instance = $container->make(ContainerClassWithDefaultValueStub::class);
330+
$this->assertInstanceOf(ContainerConcreteStub::class, $instance->default);
331+
}
332+
322333
public function testBound()
323334
{
324335
$container = new Container;

0 commit comments

Comments
 (0)