Browse Source

Utility::notEmpty()

Mark Scherer 10 years ago
parent
commit
9946ccb687
2 changed files with 36 additions and 0 deletions
  1. 10 0
      src/Utility/Utility.php
  2. 26 0
      tests/TestCase/Utility/UtilityTest.php

+ 10 - 0
src/Utility/Utility.php

@@ -13,6 +13,16 @@ use Cake\Utility\Hash;
 class Utility {
 
 	/**
+	 * More sane !empty() method to not false positive `'0'` (0 as string) as empty.
+	 *
+	 * @param mixed $value
+	 * @return bool
+	 */
+	public static function notEmpty($value) {
+		return !empty($value) || $value === '0';
+	}
+
+	/**
 	 * Clean implementation of inArray to avoid false positives.
 	 *
 	 * in_array itself has some PHP flaws regarding cross-type comparison:

+ 26 - 0
tests/TestCase/Utility/UtilityTest.php

@@ -10,6 +10,32 @@ use Cake\Core\Configure;
  */
 class UtilityTest extends TestCase {
 
+	public function testNotEmpty() {
+		$res = Utility::notEmpty('a');
+		$this->assertTrue($res);
+
+		$res = Utility::notEmpty(2);
+		$this->assertTrue($res);
+
+		$res = Utility::notEmpty(0);
+		$this->assertFalse($res);
+
+		$res = Utility::notEmpty('0');
+		$this->assertTrue($res);
+
+		$res = Utility::notEmpty(null);
+		$this->assertFalse($res);
+
+		$res = Utility::notEmpty(false);
+		$this->assertFalse($res);
+
+		$res = Utility::notEmpty('');
+		$this->assertFalse($res);
+
+		$res = Utility::notEmpty([]);
+		$this->assertFalse($res);
+	}
+
 	/**
 	 * UtilityTest::testInArray()
 	 *