Skip to content

Instantly share code, notes, and snippets.

@adrian-enspired
Last active August 29, 2015 14:02
Show Gist options
  • Save adrian-enspired/f8374753d08108436c17 to your computer and use it in GitHub Desktop.
Save adrian-enspired/f8374753d08108436c17 to your computer and use it in GitHub Desktop.
convenience function for ?: short ternary assignment syntax; avoids need for isset() checks.
<?php
/**
* performs validation on a variable, returning the variable's value on success.
*
* @author Adrian <[email protected]>
* @copyright 2013
* @since 2014-08-21 allows a validator callback
* @license MIT <http://opensource.org/licenses/MIT>
*
* @example<code>
* <?php
* // originally developed to replace "isset" checks in ternary operators
* $declared = "hello, world!";
* $default = "goodbye, world.";
*
* // allows you to do:
* print is( $declared )?: $default; // prints "hello, world!"
* print is( $undeclared )?: $default; // prints "goodbye, world."
*
* // instead of:
* print isset( $declared )? $declared: $default; // prints "hello, world!"
* print isset( $undeclared )? $undeclared: $default; // prints "goodbye, world."
*
*
* // also allows for validation using a callback:
* $object = (object)['email':'[email protected]"];
* $string = "foo";
*
* // named functions
* print is( $string,"is_string" )?: "not a string"; // prints "foo"
* print is( $object,"is_string" )?: "not a string"; // prints "not a string"
*
* // closures
* $validator = function( $v ){
* return is_object( $v )
* && isset( $v->email )
* && filter_var( $v->email,FILTER_VALIDATE_EMAIL );
* };
* print is( $object,$validator )? "thank you": "you forgot your email address"; // prints "thank you"
*
* </code>
*
* @param mixed $var the variable to check (need not be declared in advance)
* @param callable $validator validation method (in the form bool validator( $var ))
* @return mixed the value of $var on success; null otherwise
*/
function is( &$var,callable $validator=null ){
if( $validator && ! $validator( $var )){ return null; }
return $var;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment