Skip to content

Commit

Permalink
Container::getByType() fixed cooperation with dynamic factory [Closes #…
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Apr 28, 2024
1 parent e9700b0 commit 9802979
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 15 deletions.
19 changes: 4 additions & 15 deletions src/DI/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -265,22 +265,11 @@ public function getByType(string $type, bool $throw = true): ?object
} elseif ($throw) {
if (!class_exists($type) && !interface_exists($type)) {
throw new MissingServiceException(sprintf("Service of type '%s' not found. Check the class name because it cannot be found.", $type));
} elseif ($this->findByType($type)) {
throw new MissingServiceException(sprintf("Service of type %s is not autowired or is missing in di\u{a0}\u{a0}export\u{a0}\u{a0}types.", $type));
} else {
throw new MissingServiceException(sprintf('Service of type %s not found. Did you add it to configuration file?', $type));
}

foreach ($this->methods as $method => $foo) {
$methodType = (new \ReflectionMethod(static::class, $method))->getReturnType()->getName();
if (is_a($methodType, $type, true)) {
throw new MissingServiceException(sprintf(
"Service of type %s is not autowired or is missing in di\u{a0}\u{a0}export\u{a0}\u{a0}types.",
$type
));
}
}

throw new MissingServiceException(sprintf(
'Service of type %s not found. Did you add it to configuration file?',
$type
));
}

return null;
Expand Down
15 changes: 15 additions & 0 deletions tests/DI/Container.dynamic.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,21 @@ test('closure with typehint', function () {
});


// getByType()
Assert::exception(function () {
$container = new Container;
$container->addService('one', fn() => new Service);
$container->getByType(Service::class);
}, Nette\DI\MissingServiceException::class, 'Service of type Service not found. Did you add it to configuration file?');


Assert::exception(function () {
$container = new Container;
$container->addService('one', fn(): Service => new Service);
$container->getByType(Service::class);
}, Nette\DI\MissingServiceException::class, 'Service of type Service not found. Did you add it to configuration file?');


// bad closure
Assert::exception(function () {
$container = new Container;
Expand Down

0 comments on commit 9802979

Please sign in to comment.