Skip to content

Commit

Permalink
Adding detecting circular dependecies
Browse files Browse the repository at this point in the history
  • Loading branch information
mamazu committed Oct 7, 2024
1 parent 406add6 commit 9299a3b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/PhpactorContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ class PhpactorContainer implements Container, ContainerBuilder
*/
private $services = [];

/**
* @var array<string>
*/
private array $servicesToResolve = [];

/**
* @param array<string,mixed> $parameters
*/
Expand Down Expand Up @@ -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];
}

Expand Down
12 changes: 12 additions & 0 deletions tests/Unit/PhpactorContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 9299a3b

Please sign in to comment.