Skip to content

Commit

Permalink
Refactor Container to map class name aliases on demand instead of ctor
Browse files Browse the repository at this point in the history
  • Loading branch information
clue committed Jul 27, 2022
1 parent 440cf7e commit b86a271
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,7 @@ public function __construct($loader = [])
}

foreach (($loader instanceof ContainerInterface ? [] : $loader) as $name => $value) {
if (\is_string($value)) {
$loader[$name] = static function () use ($value) {
return $value;
};
} elseif (!$value instanceof \Closure && !$value instanceof $name) {
if (!\is_string($value) && !$value instanceof \Closure && !$value instanceof $name) {
throw new \BadMethodCallException('Map for ' . $name . ' contains unexpected ' . (is_object($value) ? get_class($value) : gettype($value)));
}
}
Expand Down Expand Up @@ -126,7 +122,13 @@ public function getErrorHandler(): ErrorHandler
private function load(string $name, int $depth = 64)
{
if (isset($this->container[$name])) {
if ($this->container[$name] instanceof \Closure) {
if (\is_string($this->container[$name])) {
if ($depth < 1) {
throw new \BadMethodCallException('Factory for ' . $name . ' is recursive');
}

$this->container[$name] = $this->load($this->container[$name], $depth - 1);
} elseif ($this->container[$name] instanceof \Closure) {
// build list of factory parameters based on parameter types
$closure = new \ReflectionFunction($this->container[$name]);
$params = $this->loadFunctionParams($closure, $depth);
Expand Down
17 changes: 17 additions & 0 deletions tests/ContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,23 @@ public function testCallableReturnsCallableThatThrowsWhenFactoryIsRecursive()
$callable($request);
}

public function testCallableReturnsCallableThatThrowsWhenFactoryIsRecursiveClassName()
{
$request = new ServerRequest('GET', 'http://example.com/');

$container = new Container([
\stdClass::class => function (): string {
return \stdClass::class;
}
]);

$callable = $container->callable(\stdClass::class);

$this->expectException(\BadMethodCallException::class);
$this->expectExceptionMessage('Factory for stdClass is recursive');
$callable($request);
}

public function testCallableReturnsCallableForClassNameViaPsrContainer()
{
$request = new ServerRequest('GET', 'http://example.com/');
Expand Down

0 comments on commit b86a271

Please sign in to comment.