Skip to content

Commit b48031b

Browse files
author
Kelt Dockins
committed
ioc resolves classes with optional params and accepts arguments
1 parent 23d23dd commit b48031b

File tree

1 file changed

+35
-9
lines changed

1 file changed

+35
-9
lines changed

laravel/ioc.php

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ protected static function build($type, $parameters = array())
172172
return new $type;
173173
}
174174

175-
$dependencies = static::dependencies($constructor->getParameters());
175+
$dependencies = static::dependencies($constructor->getParameters(), $parameters);
176176

177177
return $reflector->newInstanceArgs($dependencies);
178178
}
@@ -181,28 +181,54 @@ protected static function build($type, $parameters = array())
181181
* Resolve all of the dependencies from the ReflectionParameters.
182182
*
183183
* @param array $parameters
184+
* @param array $arguments that might have been passed into our resolve
184185
* @return array
185186
*/
186-
protected static function dependencies($parameters)
187+
protected static function dependencies($parameters, $arguments)
187188
{
188189
$dependencies = array();
189190

190191
foreach ($parameters as $parameter)
191192
{
192193
$dependency = $parameter->getClass();
193194

194-
// If the class is null, it means the dependency is a string or some other
195-
// primitive type, which we can not resolve since it is not a class and
196-
// we'll just bomb out with an error since we have nowhere to go.
197-
if (is_null($dependency))
195+
// If the person passed in some parameters to the class
196+
// then we should probably use those instead of trying
197+
// to resolve a new instance of the class
198+
if (count($arguments) > 0)
198199
{
199-
throw new \Exception("Unresolvable dependency resolving [$parameter].");
200+
$dependencies[] = array_shift($arguments);
201+
}
202+
else if (is_null($dependency))
203+
{
204+
$dependency[] = static::resolveNonClass($parameter);
205+
}
206+
else
207+
{
208+
$dependencies[] = static::resolve($dependency->name);
200209
}
201-
202-
$dependencies[] = static::resolve($dependency->name);
203210
}
204211

205212
return (array) $dependencies;
206213
}
207214

215+
/**
216+
* Resolves optional parameters for our dependency injection
217+
* pretty much took backport straight from L4's Illuminate\Container
218+
*
219+
* @param ReflectionParameter
220+
* @return default value
221+
*/
222+
protected static function resolveNonClass($parameter)
223+
{
224+
if ($parameter->isDefaultValueAvailable())
225+
{
226+
return $parameter->getDefaultValue();
227+
}
228+
else
229+
{
230+
throw new \Exception("Unresolvable dependency resolving [$parameter].");
231+
}
232+
}
233+
208234
}

0 commit comments

Comments
 (0)