File tree Expand file tree Collapse file tree 3 files changed +44
-1
lines changed Expand file tree Collapse file tree 3 files changed +44
-1
lines changed Original file line number Diff line number Diff line change 66use Closure ;
77use Exception ;
88use Illuminate \Contracts \Container \BindingResolutionException ;
9+ use Illuminate \Contracts \Container \CircularDependencyFoundException ;
910use Illuminate \Contracts \Container \Container as ContainerContract ;
1011use LogicException ;
1112use ReflectionClass ;
@@ -659,7 +660,7 @@ public function get($id)
659660 try {
660661 return $ this ->resolve ($ id );
661662 } catch (Exception $ e ) {
662- if ($ this ->has ($ id )) {
663+ if ($ this ->has ($ id ) || $ e instanceof CircularDependencyFoundException ) {
663664 throw $ e ;
664665 }
665666
@@ -839,6 +840,11 @@ public function build($concrete)
839840 return $ this ->notInstantiable ($ concrete );
840841 }
841842
843+ // Check for circular dependencies
844+ if (in_array ($ concrete , $ this ->buildStack )) {
845+ throw new CircularDependencyFoundException ("Circular dependency while initiating [ {$ concrete }] " );
846+ }
847+
842848 $ this ->buildStack [] = $ concrete ;
843849
844850 $ constructor = $ reflector ->getConstructor ();
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace Illuminate \Contracts \Container ;
4+
5+ use Exception ;
6+ use Psr \Container \ContainerExceptionInterface ;
7+
8+ class CircularDependencyFoundException extends Exception implements ContainerExceptionInterface
9+ {
10+ //
11+ }
Original file line number Diff line number Diff line change 55use Illuminate \Container \Container ;
66use Illuminate \Container \EntryNotFoundException ;
77use Illuminate \Contracts \Container \BindingResolutionException ;
8+ use Illuminate \Contracts \Container \CircularDependencyFoundException ;
89use PHPUnit \Framework \TestCase ;
910use Psr \Container \ContainerExceptionInterface ;
1011use stdClass ;
@@ -562,6 +563,31 @@ public function testContainerCanResolveClasses()
562563
563564 $ this ->assertInstanceOf (ContainerConcreteStub::class, $ class );
564565 }
566+
567+ public function testContainerCanCatchCircularDependency () {
568+ $ this ->expectException (CircularDependencyFoundException::class);
569+
570+ $ container = new Container ;
571+ $ container ->get (CircularAStub::class);
572+ }
573+ }
574+
575+ class CircularAStub {
576+ public function __construct (CircularBStub $ b ) {
577+
578+ }
579+ }
580+
581+ class CircularBStub {
582+ public function __construct (CircularCStub $ c ) {
583+
584+ }
585+ }
586+
587+ class CircularCStub {
588+ public function __construct (CircularAStub $ a ) {
589+
590+ }
565591}
566592
567593class ContainerConcreteStub
You can’t perform that action at this time.
0 commit comments