diff --git a/lib/PhpactorContainer.php b/lib/PhpactorContainer.php index 11a71bf9..918fd73e 100644 --- a/lib/PhpactorContainer.php +++ b/lib/PhpactorContainer.php @@ -30,6 +30,11 @@ class PhpactorContainer implements Container, ContainerBuilder */ private $services = []; + /** + * @var array + */ + private array $servicesToResolve = []; + /** * @param array $parameters */ @@ -80,8 +85,19 @@ public function get($id) )); } + if (in_array($id, $this->servicesToResolve)) { + throw new RuntimeException(sprintf( + 'Circular dependency detected: %s->%s', + implode('->', $this->servicesToResolve), + $id + )); + } + $this->servicesToResolve[] = $id; + $this->services[$id] = $this->factories[$id]($this); + $this->servicesToResolve = []; + return $this->services[$id]; } diff --git a/tests/Unit/PhpactorContainerTest.php b/tests/Unit/PhpactorContainerTest.php index b79adf5e..adc63a66 100644 --- a/tests/Unit/PhpactorContainerTest.php +++ b/tests/Unit/PhpactorContainerTest.php @@ -62,6 +62,18 @@ public function testThrowsExceptionForUnknownService(): void $this->container->get('foobar'); } + public function testThrowsExceptionForCircularDependency(): void + { + $this->container->register('foobar', function (Container $container) { + $container->get('foobar'); + }); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Circular dependency detected: foobar->foobar'); + + $this->container->get('foobar'); + } + public function testRetrievesService(): void { $this->container->register('foobar', function (Container $container) {