Skip to content

Commit

Permalink
Fix for #96 Handle optional parameters for constructor/method injection
Browse files Browse the repository at this point in the history
  • Loading branch information
mnapoli committed Sep 8, 2013
1 parent 4d1fb05 commit 52cea76
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/DI/Factory.php
Expand Up @@ -15,7 +15,9 @@
use DI\Definition\PropertyInjection;
use Exception;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use ReflectionParameter;

/**
* Factory class, responsible of instantiating classes
Expand Down Expand Up @@ -104,14 +106,22 @@ private function injectConstructor(ReflectionClass $classReflection, MethodInjec
. "$nbRequiredParameters parameters, " . count($parameterInjections) . " defined or guessed");
}

// No parameters
if (count($parameterInjections) === 0) {
return $classReflection->newInstance();
}

$parameters = $this->getMethodReflectionParameters($constructorReflection);

$args = array();
foreach ($parameterInjections as $parameterInjection) {
$entryName = $parameterInjection->getEntryName();

if ($entryName === null) {
// If the parameter is optional and wasn't specified, then we skip all next parameters
if ($parameters[$parameterInjection->getParameterName()]->isOptional()) {
break;
}
throw new DefinitionException("The parameter '" . $parameterInjection->getParameterName()
. "' of the constructor of '{$classReflection->name}' has no type defined or guessable");
}
Expand Down Expand Up @@ -168,10 +178,17 @@ private function injectMethod($object, MethodInjection $methodInjection)
return;
}

$parameters = $this->getMethodReflectionParameters($methodReflection);

$args = array();
foreach ($parameterInjections as $parameterInjection) {
$entryName = $parameterInjection->getEntryName();

if ($entryName === null) {
// If the parameter is optional and wasn't specified, then we skip all next parameters
if ($parameters[$parameterInjection->getParameterName()]->isOptional()) {
break;
}
throw new DefinitionException("The parameter '" . $parameterInjection->getParameterName()
. "' of {$classReflection->name}::$methodName has no type defined or guessable");
}
Expand Down Expand Up @@ -222,4 +239,22 @@ private function injectProperty($object, PropertyInjection $propertyInjection)
$property->setValue($object, $value);
}

/**
* @param ReflectionMethod $reflectionMethod
* @return ReflectionParameter[]
*/
private function getMethodReflectionParameters(ReflectionMethod $reflectionMethod)
{
$parameters = $reflectionMethod->getParameters();

$keys = array_map(
function (ReflectionParameter $parameter) {
return $parameter->getName();
},
$parameters
);

return array_combine($keys, $parameters);
}

}

0 comments on commit 52cea76

Please sign in to comment.