Skip to content

Instantly share code, notes, and snippets.

@alright
Created November 10, 2011 20:38
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 alright/1356134 to your computer and use it in GitHub Desktop.
Save alright/1356134 to your computer and use it in GitHub Desktop.
<?php
function named_args (array $args, array $settings = array())
{
$native_types = array('boolean', 'integer', 'float', 'null', 'string', 'object', 'array', 'callable', 'resource');
foreach ($settings AS $name => $arg)
{
$type = NULL;
$required = FALSE;
if (is_int($name))
{
// It's an index of array
$required = TRUE;
$name = $arg;
}
if (strpos($name, ' ') !== FALSE)
{
// If there type definition
$parts = explode(' ', $name);
$type = $parts[0];
$name = $parts[1];
}
/**
* Defaults
*/
if ( ! $required && ! array_key_exists($name, $args))
{
if ($required)
{
throw new Exception($name.' must be passed into function');
}
$args[$name] = $arg;
}
/**
* Types
*/
if ( ! empty($type))
{
if (array_key_exists($type, $native_types))
{
// Native type
$function = ($type === 'boolean')
? 'is_bool'
: 'is_'.$type;
if ( ! $function($args[$name]))
{
throw new Exception($name.' must be '.$type);
}
}
elseif (is_object($args[$name]) && ! ($args[$name] instanceof $type))
{
// Class instance
throw new Exception($name.' must be instance of '.$type);
}
}
}
return $args;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment