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 6
6
use Closure ;
7
7
use Exception ;
8
8
use Illuminate \Contracts \Container \BindingResolutionException ;
9
+ use Illuminate \Contracts \Container \CircularDependencyFoundException ;
9
10
use Illuminate \Contracts \Container \Container as ContainerContract ;
10
11
use LogicException ;
11
12
use ReflectionClass ;
@@ -659,7 +660,7 @@ public function get($id)
659
660
try {
660
661
return $ this ->resolve ($ id );
661
662
} catch (Exception $ e ) {
662
- if ($ this ->has ($ id )) {
663
+ if ($ this ->has ($ id ) || $ e instanceof CircularDependencyFoundException ) {
663
664
throw $ e ;
664
665
}
665
666
@@ -839,6 +840,11 @@ public function build($concrete)
839
840
return $ this ->notInstantiable ($ concrete );
840
841
}
841
842
843
+ // Check for circular dependencies
844
+ if (in_array ($ concrete , $ this ->buildStack )) {
845
+ throw new CircularDependencyFoundException ("Circular dependency while initiating [ {$ concrete }] " );
846
+ }
847
+
842
848
$ this ->buildStack [] = $ concrete ;
843
849
844
850
$ 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 5
5
use Illuminate \Container \Container ;
6
6
use Illuminate \Container \EntryNotFoundException ;
7
7
use Illuminate \Contracts \Container \BindingResolutionException ;
8
+ use Illuminate \Contracts \Container \CircularDependencyFoundException ;
8
9
use PHPUnit \Framework \TestCase ;
9
10
use Psr \Container \ContainerExceptionInterface ;
10
11
use stdClass ;
@@ -562,6 +563,31 @@ public function testContainerCanResolveClasses()
562
563
563
564
$ this ->assertInstanceOf (ContainerConcreteStub::class, $ class );
564
565
}
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
+ }
565
591
}
566
592
567
593
class ContainerConcreteStub
You can’t perform that action at this time.
0 commit comments