Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -412,13 +412,8 @@ private function loadVariable(string $name, int $depth = 64) /*: mixed (PHP 8.0+
$this->container[$name] = $factory;
}

if ($value instanceof \Closure) {
throw new \TypeError(
'Return value of ' . self::functionName($closure) . ' for $' . $name . ' must not be of type Closure'
);
}

$this->container[$name] = $value;
// cache result, but wrap closure so it is not invoked as factory on next call
$this->container[$name] = $value instanceof \Closure ? static function () use ($value) { return $value; } : $value;
} elseif (\is_array($this->container) && \array_key_exists($name, $this->container)) {
$value = $this->container[$name];
} elseif (isset($_ENV[$name])) {
Expand Down
20 changes: 18 additions & 2 deletions tests/ContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1936,6 +1936,23 @@ public function testGetEnvReturnsStringFromFactoryFunctionWithCallableTypeAndArr
$this->assertEquals('UTC', $container->getEnv('X_FOO'));
}

public function testGetEnvReturnsStringFromFactoryFunctionWithClosureValueFromFactoryFunctionCalledOnlyOnce(): void
{
$calls = 0;
$closure = function () { };
$container = new Container([
'X_FOO' => function (\Closure $fn) use ($closure) { return var_export($fn === $closure, true); },
'X_BAR' => function (\Closure $fn) use ($closure) { return var_export($fn === $closure, true); },
'X_BAZ' => function (\Closure $fn) use ($closure) { return var_export($fn === $closure, true); },
'fn' => function () use ($closure, &$calls) { ++$calls; return $closure; }
]);

$this->assertEquals('true', $container->getEnv('X_FOO'));
$this->assertEquals('true', $container->getEnv('X_BAR'));
$this->assertEquals('true', $container->getEnv('X_BAZ'));
$this->assertEquals(1, $calls);
}

/**
* @requires PHP 8.2
*/
Expand Down Expand Up @@ -2316,7 +2333,6 @@ public function testGetEnvThrowsIfFactoryFunctionThrows(): void

public function testGetEnvThrowsIfFactoryFunctionReturnsInvalidClosure(): void
{
$line = __LINE__ + 2;
$container = new Container([
'X_FOO' => function () {
return function () {
Expand All @@ -2326,7 +2342,7 @@ public function testGetEnvThrowsIfFactoryFunctionReturnsInvalidClosure(): void
]);

$this->expectException(\TypeError::class);
$this->expectExceptionMessage('Return value of {closure:' . __FILE__ . ':' . $line . '}() for $X_FOO must not be of type Closure');
$this->expectExceptionMessage('Return value of FrameworkX\Container::getEnv() for $X_FOO must be of type string|null, Closure returned');
$container->getEnv('X_FOO');
}

Expand Down