Skip to content

Instantly share code, notes, and snippets.

@ralphschindler
Created July 21, 2013 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralphschindler/6049243 to your computer and use it in GitHub Desktop.
Save ralphschindler/6049243 to your computer and use it in GitHub Desktop.
Matching Named Arguments
<?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