Skip to content

Commit 38608a6

Browse files
committed
Container::getByType() improved exception message
1 parent 67ee8ec commit 38608a6

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

src/DI/Container.php

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,10 @@ class Container
4747
public function __construct(array $params = [])
4848
{
4949
$this->parameters = $params;
50-
$this->methods = array_flip(get_class_methods($this));
50+
$this->methods = array_flip(array_filter(
51+
get_class_methods($this),
52+
function ($s) { return preg_match('#^createService.#', $s); }
53+
));
5154
}
5255

5356

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

230233
} elseif ($throw) {
231-
throw new MissingServiceException("Service of type $type not found.");
234+
if (!class_exists($type) && !interface_exists($type)) {
235+
throw new MissingServiceException("Service of type '$type' not found. Check class name because it cannot be found.");
236+
}
237+
foreach ($this->methods as $method => $foo) {
238+
$methodType = (new \ReflectionMethod(get_class($this), $method))->getReturnType()->getName();
239+
if (is_a($methodType, $type, true)) {
240+
throw new MissingServiceException("Service of type $type is not autowired or is missing in di › export › types.");
241+
}
242+
}
243+
throw new MissingServiceException("Service of type $type not found. Did you add it to configuration file?");
232244
}
233245
return null;
234246
}

tests/DI/Container.getByType.phpt

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,11 @@ Assert::null($container->getByType('unknown', false));
5555

5656
Assert::exception(function () use ($container) {
5757
$container->getByType('unknown');
58-
}, Nette\DI\MissingServiceException::class, 'Service of type unknown not found.');
58+
}, Nette\DI\MissingServiceException::class, "Service of type 'unknown' not found. Check class name because it cannot be found.");
59+
60+
Assert::exception(function () use ($container) {
61+
$container->getByType('Exception');
62+
}, Nette\DI\MissingServiceException::class, 'Service of type Exception not found. Did you add it to configuration file?');
5963

6064

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

0 commit comments

Comments
 (0)