diff --git a/src/Illuminate/Container/Container.php b/src/Illuminate/Container/Container.php index d57904e099ec..1e9f65ad0551 100755 --- a/src/Illuminate/Container/Container.php +++ b/src/Illuminate/Container/Container.php @@ -949,6 +949,7 @@ protected function resolveClass(ReflectionParameter $parameter) // the value of the dependency, similarly to how we do this with scalars. catch (BindingResolutionException $e) { if ($parameter->isOptional()) { + array_pop($this->buildStack); return $parameter->getDefaultValue(); } diff --git a/tests/Container/ContextualBindingTest.php b/tests/Container/ContextualBindingTest.php index c1694cae8076..cfa2ed769109 100644 --- a/tests/Container/ContextualBindingTest.php +++ b/tests/Container/ContextualBindingTest.php @@ -209,6 +209,29 @@ public function testContextualBindingWorksWithAliasedTargets() $this->assertInstanceOf(ContainerContextImplementationStub::class, $one->impl); $this->assertInstanceOf(ContainerContextImplementationStubTwo::class, $two->impl); } + + + public function testContextualBindingWorksForNestedPrimitiveResolvingForMultipleClassesInjection() + { + $container = new Container; + + $container->when(ContainerTestContextInjectTwoInstances::class)->needs(ContainerTestContextPrimitiveTwo::class)->give(function() { + return new ContainerTestContextPrimitiveTwo('test'); + }); + + $resolvedInstance = $container->make(ContainerTestContextInjectTwoInstances::class); + $this->assertInstanceOf( + ContainerTestContextWithNestedOptionalDependencyStubWithPrimitive::class, + $resolvedInstance->implOne + ); + $this->assertNull($resolvedInstance->implOne->inner); + + $this->assertInstanceOf( + ContainerTestContextPrimitiveTwo::class, + $resolvedInstance->implTwo + ); + $this->assertEquals($resolvedInstance->implTwo->primitive, 'test'); + } } interface IContainerContextContractStub @@ -265,3 +288,45 @@ public function __construct(IContainerContextContractStub $impl) $this->impl = $impl; } } + +class ContainerTestContextInjectTwoInstances +{ + public $implOne; + public $implTwo; + + public function __construct(ContainerTestContextWithNestedOptionalDependencyStubWithPrimitive $implOne, ContainerTestContextPrimitiveTwo $implTwo) + { + $this->implOne = $implOne; + $this->implTwo = $implTwo; + } +} + +class ContainerTestContextWithNestedOptionalDependencyStubWithPrimitive +{ + public $inner; + + public function __construct(ContainerTestContextPrimitiveOne $inner = null) + { + $this->inner = $inner; + } +} + +class ContainerTestContextPrimitiveOne +{ + public $primitive; + + public function __construct(string $primitive) + { + $this->primitive = $primitive; + } +} + +class ContainerTestContextPrimitiveTwo +{ + public $primitive; + + public function __construct(string $primitive) + { + $this->primitive = $primitive; + } +}