Created
November 7, 2014 05:54
-
-
Save devosc/03c42541a461ba34b344 to your computer and use it in GitHub Desktop.
Constructor Plugin Arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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