Skip to content

Commit

Permalink
more self explanatory message for factory and service mismatch (closes
Browse files Browse the repository at this point in the history
  • Loading branch information
dakur authored and dg committed Mar 14, 2023
1 parent a878e41 commit dd87e7f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
16 changes: 12 additions & 4 deletions src/DI/Definitions/FactoryDefinition.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,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

0 comments on commit dd87e7f

Please sign in to comment.