Skip to content

Commit 575c46b

Browse files
authored
Merge pull request #302 from clue-labs/container-factory-return
Throw `TypeError` when container factory returns `Closure`
2 parents 136319f + 86eeb31 commit 575c46b

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

src/Container.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,10 @@ private function loadVariable(string $name, int $depth = 64) /*: object|string|i
413413
throw new \TypeError(
414414
'Return value of ' . self::functionName($closure) . ' for $' . $name . ' must be of type object|string|int|float|bool|null, ' . $this->gettype($value) . ' returned'
415415
);
416+
} elseif ($value instanceof \Closure) {
417+
throw new \TypeError(
418+
'Return value of ' . self::functionName($closure) . ' for $' . $name . ' must not be of type Closure'
419+
);
416420
}
417421

418422
$this->container[$name] = $value;

tests/ContainerTest.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2266,6 +2266,22 @@ public function testGetEnvThrowsIfFactoryFunctionReturnsInvalidResource(): void
22662266
$container->getEnv('X_FOO');
22672267
}
22682268

2269+
public function testGetEnvThrowsIfFactoryFunctionReturnsInvalidClosure(): void
2270+
{
2271+
$line = __LINE__ + 2;
2272+
$container = new Container([
2273+
'X_FOO' => function () {
2274+
return function () {
2275+
return 42;
2276+
};
2277+
}
2278+
]);
2279+
2280+
$this->expectException(\TypeError::class);
2281+
$this->expectExceptionMessage('Return value of {closure:' . __FILE__ . ':' . $line . '}() for $X_FOO must not be of type Closure');
2282+
$container->getEnv('X_FOO');
2283+
}
2284+
22692285
public function testGetEnvThrowsIfFactoryFunctionReturnsInvalidInt(): void
22702286
{
22712287
$container = new Container([
@@ -2810,6 +2826,22 @@ public function testGetObjectThrowsIfFactoryFunctionReturnsInvalidValue(): void
28102826
$container->getObject(AccessLogHandler::class);
28112827
}
28122828

2829+
public function testGetObjectThrowsIfFactoryFunctionReturnsInvalidClosure(): void
2830+
{
2831+
$line = __LINE__ + 2;
2832+
$container = new Container([
2833+
AccessLogHandler::class => function () {
2834+
return function () {
2835+
return 42;
2836+
};
2837+
}
2838+
]);
2839+
2840+
$this->expectException(\TypeError::class);
2841+
$this->expectExceptionMessage('Return value of {closure:' . __FILE__ . ':' . $line . '}() for FrameworkX\AccessLogHandler must be of type FrameworkX\AccessLogHandler, Closure returned');
2842+
$container->getObject(AccessLogHandler::class);
2843+
}
2844+
28132845
public function testGetObjectThrowsIfConfigIsRecursive(): void
28142846
{
28152847
$container = new Container([

0 commit comments

Comments
 (0)