Skip to content

Instantly share code, notes, and snippets.

@paamayim
Last active March 2, 2016 00:06
Show Gist options
  • Save paamayim/8063fc78e9508ed427d5 to your computer and use it in GitHub Desktop.
Save paamayim/8063fc78e9508ed427d5 to your computer and use it in GitHub Desktop.
PHP array argument validation: Checks that required variables exist within a scope
<?php
/**
* Checks that required variables exist within a scope(array or object)
* If any required variable is not present, an exception is thrown.
* Also allows an input of default variables, which are set if not set beforehand
*
* Example usage:
* function foo($args){
* expect($args, ['a', 'b', 'c']); // throws error
* }
* foo(['a'=>1,'b'=>2,'d'=>3]);
*
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @author Joshua McKenzie <josh@ia.lc>
* @param mixed &$scope array or object to check against
* @param array $required_varnames list of variable names to check
* @param array $default_vars array of keys to check, and values to set
* @param class $exception exception class
*/
function expect(&$scope=null, $required_varnames=null, $default_vars=null, $exception = '\Exception'){
if(is_null($scope))$scope = $GLOBALS;
if(is_array($scope)){
if(!is_null($required_varnames)){
foreach($required_varnames as $varname){
if(!isset($scope[$varname]))
throw new $exception('Missing expect argument '.$varname);
}
}
if(!is_null($default_vars)){
foreach($default_vars as $key=>$value){
if(!isset($scope[$key]))
$scope[$key] = $value;
}
}
} else if(is_object($scope)){
if(!is_null($required_varnames)){
foreach($required_varnames as $varname){
if(!isset($scope->{$varname}))
throw new $exception('Missing expect argument '.$varname);
}
}
if(!is_null($default_vars)){
foreach($default_vars as $key=>$value){
if(!isset($scope->{$key}))
$scope->{$key} = $value;
}
}
} else throw new $exception('Invalid expect scope');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment