Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More self explanatory message for factory and service mismatch #284

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions src/DI/Definitions/FactoryDefinition.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,12 +170,20 @@ private function completeParameters(Nette\DI\Resolver $resolver): void
$this->resultDefinition->getCreator()->arguments[$ctorParam->getPosition()] = new Php\Literal('$' . $ctorParam->name);

} elseif (!$this->resultDefinition->getSetup()) {
$hint = Nette\Utils\Helpers::getSuggestion(array_keys($ctorParams), $param->name);
// [param1, param2] => '$param1, $param2'
$stringifyParams = static fn(array $params): string => implode(', ', array_map(
static fn(string $param): string => sprintf('$%s', $param),
$params,
));
$ctorParamsKeys = array_keys($ctorParams);
$hint = Nette\Utils\Helpers::getSuggestion($ctorParamsKeys, $param->name);
throw new ServiceCreationException(sprintf(
'Unused parameter $%s when implementing method %s::create()',
$param->name,
'Cannot implement %s::create(): factory method parameters (%s) are not matching %s::__construct() parameters (%s).',
$interface,
) . ($hint ? ", did you mean \${$hint}?" : '.'));
$stringifyParams(array_map(static fn(\ReflectionParameter $param): string => $param->name, $method->getParameters())),
$class,
$stringifyParams($ctorParamsKeys),
) . ($hint ? " Did you mean to use '\${$hint}' in factory method?" : ''));
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions tests/DI/Compiler.generatedFactory.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ Assert::exception(function () {
->setImplement(Bad4::class);
$builder->complete();
}, Nette\InvalidStateException::class, "[Service 'one' of type Bad4]
Unused parameter \$baz when implementing method Bad4::create(), did you mean \$bar?");
Cannot implement Bad4::create(): factory method parameters (\$baz) are not matching Bad3::__construct() parameters (\$bar). Did you mean to use '\$bar' in factory method?");



Expand All @@ -311,7 +311,7 @@ Assert::exception(function () {
->setImplement(Bad6::class);
$builder->complete();
}, Nette\InvalidStateException::class, "[Service 'one' of type Bad6]
Unused parameter \$baz when implementing method Bad6::create().");
Cannot implement Bad6::create(): factory method parameters (\$baz) are not matching Bad5::__construct() parameters (\$xxx).");



Expand Down