Skip to content

Instantly share code, notes, and snippets.

@devosc
Created November 7, 2014 05:54
Show Gist options
  • Save devosc/03c42541a461ba34b344 to your computer and use it in GitHub Desktop.
Save devosc/03c42541a461ba34b344 to your computer and use it in GitHub Desktop.
Constructor Plugin Arguments
<?php
/**
* @param string $name
* @param array $args
* @return object
*/
protected function newInstanceArgs($name, array $args = [])
{
$class = new ReflectionClass($name);
if (!$class->hasMethod('__construct')) {
return $class->newInstance();
}
if ($args && !is_string(key($args))) {
return $class->newInstanceArgs($this->args($args));
}
$matched = [];
$params = $class->getConstructor()->getParameters();
foreach($params as $param) {
if (isset($args[$param->name])) {
$matched[] = $args[$param->name];
continue;
}
if (Args::ARGS === $param->name) {
$matched[] = $args;
continue;
}
if ($match = $this->plugin($param->name)) {
$matched[] = $match;
continue;
}
if ($param->isDefaultValueAvailable()) {
$matched[] = $param->getDefaultValue();
continue;
}
if ($param->isArray()) {
$matched[] = [];
continue;
}
if (!$param->isOptional()) {
throw new RuntimeException('Missing required parameter ' . $param->name);
}
$matched[] = null;
}
return $class->newInstanceArgs($params ? $matched : $this->args($args));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment