Skip to content

Commit

Permalink
InjectExtension: added type checking
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Dec 11, 2023
1 parent 49f7573 commit aadf600
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/DI/Extensions/InjectExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ private function updateDefinition(Definitions\ServiceDefinition $def): void
}
}

if ($builder) {
self::checkType($class, $property, $type, $builder, $def);
}
array_unshift($setups, $inject);
}

Expand Down Expand Up @@ -158,7 +161,26 @@ public static function callInjects(DI\Container $container, $service): void
}

foreach (self::getInjectProperties(get_class($service)) as $property => $type) {
self::checkType($service, $property, $type, $container, null);
$service->$property = $container->getByType($type);
}
}


private static function checkType(
$class,
string $name,
?string $type,
$container,
?Definitions\Definition $def
): void
{
if (!$container->getByType($type, false)) {
throw new Nette\DI\MissingServiceException(sprintf(
'Service of type %s required by %s not found. Did you add it to configuration file?',
$type,
Reflection::toString(new \ReflectionProperty($class, $name))
));
}
}
}
2 changes: 1 addition & 1 deletion tests/DI/InjectExtension.errors.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ services:
factory: ServiceA
inject: yes
');
}, InvalidStateException::class, "Service 'service' (type of ServiceA): Service of type DateTimeImmutable not found. Did you add it to configuration file?");
}, InvalidStateException::class, 'Service of type DateTimeImmutable required by ServiceA::$a not found. Did you add it to configuration file?');


Assert::exception(function () {
Expand Down

0 comments on commit aadf600

Please sign in to comment.