Skip to content

Commit

Permalink
Merge pull request #1365 from splitbrain/blank
Browse files Browse the repository at this point in the history
add convenience function for empty check without 0
  • Loading branch information
splitbrain committed Sep 25, 2015
2 parents ee6517f + ddd88cd commit fef14ec
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
52 changes: 52 additions & 0 deletions _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");
}

}
19 changes: 19 additions & 0 deletions inc/common.php
Expand Up @@ -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
*
Expand Down

0 comments on commit fef14ec

Please sign in to comment.