Skip to content

Commit

Permalink
FactoryDefinition::resolveType() checks for type compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Sep 29, 2021
1 parent 1a04219 commit cc7c4e7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
27 changes: 17 additions & 10 deletions src/DI/Definitions/FactoryDefinition.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,24 +178,31 @@ public function getParameters(): array

public function resolveType(Nette\DI\Resolver $resolver): void
{
$interface = $this->getType();
if (!$interface) {
throw new ServiceCreationException('Type is missing in definition of service.');
}
$method = new \ReflectionMethod($interface, self::METHOD_CREATE);
$type = Type::fromReflection($method) ?? Helpers::getReturnTypeAnnotation($method);

$resultDef = $this->resultDefinition;
try {
$resolver->resolveDefinition($resultDef);
return;
} catch (ServiceCreationException $e) {
}

if (!$resultDef->getType()) {
$interface = $this->getType();
if (!$interface) {
throw new ServiceCreationException('Type is missing in definition of service.');
if ($resultDef->getType()) {
throw $e;
}
$method = new \ReflectionMethod($interface, self::METHOD_CREATE);
$type = Type::fromReflection($method) ?? Helpers::getReturnTypeAnnotation($method);
$resultDef->setType(Helpers::ensureClassType($type, "return type of $interface::create()"));
$resolver->resolveDefinition($resultDef);
}

$resolver->resolveDefinition($resultDef);
if ($type && !$type->allows($resultDef->getType())) {
throw new ServiceCreationException(sprintf(
'Factory for %s cannot create incompatible %s type.',
$type,
$resultDef->getType()
));
}
}


Expand Down
10 changes: 10 additions & 0 deletions tests/DI/Definitions.FactoryDefinition.resolve.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,13 @@ Assert::noError(function () {
$resolver->resolveDefinition($def);
$resolver->completeDefinition($def);
});


Assert::exception(function () {
$def = new FactoryDefinition;
$def->setImplement(Good2::class);
$def->getResultDefinition()->setType(DateTime::class);

$resolver = new Nette\DI\Resolver(new Nette\DI\ContainerBuilder);
$resolver->resolveDefinition($def);
}, Nette\DI\ServiceCreationException::class, 'Service of type Good2: Factory for stdClass cannot create incompatible DateTime type.');

0 comments on commit cc7c4e7

Please sign in to comment.