Skip to content

Commit f477cf2

Browse files
committed
Container::getByType() fixed cooperation with dynamic factory [Closes #314]
1 parent e9700b0 commit f477cf2

File tree

2 files changed

+23
-15
lines changed

2 files changed

+23
-15
lines changed

src/DI/Container.php

+4-15
Original file line numberDiff line numberDiff line change
@@ -265,22 +265,11 @@ public function getByType(string $type, bool $throw = true): ?object
265265
} elseif ($throw) {
266266
if (!class_exists($type) && !interface_exists($type)) {
267267
throw new MissingServiceException(sprintf("Service of type '%s' not found. Check the class name because it cannot be found.", $type));
268+
} elseif ($this->findByType($type)) {
269+
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));
270+
} else {
271+
throw new MissingServiceException(sprintf('Service of type %s not found. Did you add it to configuration file?', $type));
268272
}
269-
270-
foreach ($this->methods as $method => $foo) {
271-
$methodType = (new \ReflectionMethod(static::class, $method))->getReturnType()->getName();
272-
if (is_a($methodType, $type, true)) {
273-
throw new MissingServiceException(sprintf(
274-
"Service of type %s is not autowired or is missing in di\u{a0}\u{a0}export\u{a0}\u{a0}types.",
275-
$type
276-
));
277-
}
278-
}
279-
280-
throw new MissingServiceException(sprintf(
281-
'Service of type %s not found. Did you add it to configuration file?',
282-
$type
283-
));
284273
}
285274

286275
return null;

tests/DI/Container.dynamic.phpt

+19
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,25 @@ test('closure with typehint', function () {
6464
});
6565

6666

67+
// getByType()
68+
Assert::exception(function () {
69+
$container = new Container;
70+
$container->addService('one', function () {
71+
return new Service;
72+
});
73+
$container->getByType(Service::class);
74+
}, Nette\DI\MissingServiceException::class, 'Service of type Service not found. Did you add it to configuration file?');
75+
76+
77+
Assert::exception(function () {
78+
$container = new Container;
79+
$container->addService('one', function (): Service {
80+
return new Service;
81+
});
82+
$container->getByType(Service::class);
83+
}, Nette\DI\MissingServiceException::class, 'Service of type Service not found. Did you add it to configuration file?');
84+
85+
6786
// bad closure
6887
Assert::exception(function () {
6988
$container = new Container;

0 commit comments

Comments
 (0)