Created
July 21, 2013 17:30
-
-
Save ralphschindler/6049243 to your computer and use it in GitHub Desktop.
Matching Named 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 | |
function matchNamedArguments($target, $arguments = array()) | |
{ | |
if (!is_array($arguments) && !$arguments instanceof \ArrayAccess) { | |
throw new \InvalidArgumentException('$arguments for ' . __CLASS__ . ' must be array or ArrayAccess'); | |
} | |
if (is_string($target) || $target instanceof \Closure) { | |
$r = new \ReflectionFunction($target); | |
$rps = $r->getParameters(); | |
} elseif (is_array($target) && count($target) == 2) { | |
$r = (is_string($target[0])) ? new \ReflectionClass($target[0]) : new \ReflectionObject($target[0]); | |
$method = strtolower($target[1]); | |
if (!$r->hasMethod($method)) { | |
throw new \Exception('Unknown callable method ' . $method); | |
} | |
$rps = $r->getMethod($method)->getParameters(); | |
} else { | |
throw new \Exception('Unknown callable'); | |
} | |
$dispatchParams = array(); | |
foreach ($rps as $rp) { | |
$paramName = $rp->getName(); | |
if (isset($arguments[$paramName])) { | |
// call-time arguments get priority | |
$dispatchParams[] = $arguments[$paramName]; | |
} elseif ($rp->isOptional()) { | |
// use default specified by method signature | |
$dispatchParams[] = $rp->getDefaultValue(); | |
} else { | |
// otherwise, null | |
$dispatchParams[] = null; | |
} | |
} | |
return $dispatchParams; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment