diff --git a/src/DI/Container.php b/src/DI/Container.php index 2eb1ea19d..e273c07f0 100644 --- a/src/DI/Container.php +++ b/src/DI/Container.php @@ -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); } + )); } @@ -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; } diff --git a/tests/DI/Container.getByType.phpt b/tests/DI/Container.getByType.phpt index 860792a30..458abfa43 100644 --- a/tests/DI/Container.getByType.phpt +++ b/tests/DI/Container.getByType.phpt @@ -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'));