diff --git a/_test/tests/inc/common_blank.test.php b/_test/tests/inc/common_blank.test.php new file mode 100644 index 0000000000000000000000000000000000000000..9df35936a2905dc21f29ebe6c2426eb3f1c00eee --- /dev/null +++ b/_test/tests/inc/common_blank.test.php @@ -0,0 +1,52 @@ +<?php + +class common_blank_test extends DokuWikiTest { + + private $nope; + + function test_blank() { + $tests = array( + // these are not blank + array('string', false), + array(1, false), + array(1.0, false), + array(0xff, false), + array(array('something'), false), + + // these aren't either! + array('0', false), + array(' ', false), + array('0.0', false), + array(0, false), + array(0.0, false), + array(0x00, false), + array(true, false), + + // but these are + array('', true), + array(array(), true), + array(null, true), + array(false, true), + array("\0", true) + ); + + foreach($tests as $test) { + $this->assertEquals($test[1], blank($test[0]), "using " . var_export($test[0], true)); + } + } + + function test_trim() { + $whitespace = " \t\r\n"; + $this->assertFalse(blank($whitespace), "using default \$trim value"); + $this->assertFalse(blank($whitespace, false), "using \$trim = false"); + $this->assertTrue(blank($whitespace, true), "using \$trim = true"); + } + + function test_undefined() { + $undef = array(); + $this->assertTrue(blank($var), "using undefined/unitialised variable"); + $this->assertTrue(blank($undef['nope']), "using undefined array index"); + $this->assertTrue(blank($this->nope), "using unset object property"); + } + +} diff --git a/inc/common.php b/inc/common.php index 17facd249d100346eb8986a98dc27e32210b52ed..55916dc05d1d66addec0fce231b00af4e2354279 100644 --- a/inc/common.php +++ b/inc/common.php @@ -30,6 +30,25 @@ function hsc($string) { return htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); } +/** + * Checks if the given input is blank + * + * This is similar to empty() but will return false for "0". + * + * @param $in + * @param bool $trim Consider a string of whitespace to be blank + * @return bool + */ +function blank(&$in, $trim = false) { + if(!isset($in)) return true; + if(is_null($in)) return true; + if(is_array($in)) return empty($in); + if($in === "\0") return true; + if($trim && trim($in) === '') return true; + if(strlen($in) > 0) return false; + return empty($in); +} + /** * print a newline terminated string *