Skip to content

Commit

Permalink
Container::getByType() improved exception message
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Aug 13, 2020
1 parent e61b88d commit 766e818
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
16 changes: 14 additions & 2 deletions src/DI/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ class Container
public function __construct(array $params = [])
{
$this->parameters = $params;
$this->methods = array_flip(get_class_methods($this));
$this->methods = array_flip(array_filter(
get_class_methods($this),
function ($s) { return preg_match('#^createService.#', $s); }
));
}


Expand Down Expand Up @@ -228,7 +231,16 @@ public function getByType(string $type, bool $throw = true)
throw new MissingServiceException("Multiple services of type $type found: " . implode(', ', $names) . '.');

} elseif ($throw) {
throw new MissingServiceException("Service of type $type not found.");
if (!class_exists($type) && !interface_exists($type)) {
throw new MissingServiceException("Service of type '$type' not found. Check class name because it cannot be found.");
}
foreach ($this->methods as $method => $foo) {
$methodType = (new \ReflectionMethod(get_class($this), $method))->getReturnType()->getName();
if (is_a($methodType, $type, true)) {
throw new MissingServiceException("Service of type $type is not autowired or is missing in di › export › types.");
}
}
throw new MissingServiceException("Service of type $type not found. Did you add it to configuration file?");
}
return null;
}
Expand Down
6 changes: 5 additions & 1 deletion tests/DI/Container.getByType.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@ Assert::null($container->getByType('unknown', false));

Assert::exception(function () use ($container) {
$container->getByType('unknown');
}, Nette\DI\MissingServiceException::class, 'Service of type unknown not found.');
}, Nette\DI\MissingServiceException::class, "Service of type 'unknown' not found. Check class name because it cannot be found.");

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


Assert::same(['one', 'child'], $container->findByType('Service'));
Expand Down

0 comments on commit 766e818

Please sign in to comment.