浏览代码

Fix Utility::notEmpty() as Utility::notBlank()

mscherer 7 年之前
父节点
当前提交
5449ebba9a
共有 2 个文件被更改,包括 42 次插入0 次删除
  1. 13 0
      src/Utility/Utility.php
  2. 29 0
      tests/TestCase/Utility/UtilityTest.php

+ 13 - 0
src/Utility/Utility.php

@@ -15,8 +15,21 @@ use RuntimeException;
 class Utility {
 class Utility {
 
 
 	/**
 	/**
+	 * More sane !empty() check for actual (form) data input.
+	 * It allows only empty string `''`, bool `false` or `null` to be failing the check.
+	 *
+	 * @param mixed $value
+	 * @return bool
+	 */
+	public static function notBlank($value) {
+		return $value === 0 || $value === 0.0 || $value === '0' || !empty($value);
+	}
+
+	/**
 	 * More sane !empty() method to not false positive `'0'` (0 as string) as empty.
 	 * More sane !empty() method to not false positive `'0'` (0 as string) as empty.
 	 *
 	 *
+	 * @deprecated Use notBlank() instead as it correctly handles also numeric input (int/float).
+	 *
 	 * @param mixed $value
 	 * @param mixed $value
 	 * @return bool
 	 * @return bool
 	 */
 	 */

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

@@ -15,6 +15,35 @@ class UtilityTest extends TestCase {
 	/**
 	/**
 	 * @return void
 	 * @return void
 	 */
 	 */
+	public function testNotBlank() {
+		$res = Utility::notBlank('a');
+		$this->assertTrue($res);
+
+		$res = Utility::notBlank(2);
+		$this->assertTrue($res);
+
+		$res = Utility::notBlank(0);
+		$this->assertTrue($res);
+
+		$res = Utility::notBlank('0');
+		$this->assertTrue($res);
+
+		$res = Utility::notBlank(null);
+		$this->assertFalse($res);
+
+		$res = Utility::notBlank(false);
+		$this->assertFalse($res);
+
+		$res = Utility::notBlank('');
+		$this->assertFalse($res);
+
+		$res = Utility::notBlank([]);
+		$this->assertFalse($res);
+	}
+
+	/**
+	 * @return void
+	 */
 	public function testNotEmpty() {
 	public function testNotEmpty() {
 		$res = Utility::notEmpty('a');
 		$res = Utility::notEmpty('a');
 		$this->assertTrue($res);
 		$this->assertTrue($res);