浏览代码

V add filter method

Piotr Labudda 10 年之前
父节点
当前提交
3731833ee1
共有 1 个文件被更改,包括 27 次插入9 次删除
  1. 27 9
      SE/se-lib/V.php

+ 27 - 9
SE/se-lib/V.php

@@ -10,7 +10,7 @@ class V {
 	/**
 	 * Get variable from array or object.
 	 */
-	public static function get($name, $default, &$from, $type = '') {
+	public static function get($name, $default, $from, $type = '', $filterCallback = null) {
 		$ret = null;
 		if (is_array($from)) {
 			if (array_key_exists($name, $from)) {
@@ -27,13 +27,20 @@ class V {
 			$ret = V::convert($ret, $type);
 		}
 
-		return (isset($ret))? $ret : $default;
+		if (!empty($filterCallback)) {
+			if ($type == 'array' && is_array($ret) && !empty($ret)) {
+				$ret = V::filter($ret, $filterCallback);
+			}
+		}
+
+		$ret = (null !== $ret)? $ret : $default;
+		return $ret;
 	}
 
 	/**
 	 * Convert variable type.
 	 */
-	public static function convert(&$from, $type = 'string') {
+	public static function convert($from, $type = 'string') {
 		$type = strtolower($type);
 
 		// is_scalar($from) - return TRUE if int,float,string,bool, FALSE if array,object,resource, ...
@@ -66,7 +73,7 @@ class V {
 			case 'float':
 			case 'double':
 				if (is_scalar($from)) {
-					$ret = str_replace(',','.',$from);
+					$ret = str_replace(',', '.', $from);
 					settype($ret, $type);
 				}
 				break;
@@ -81,9 +88,9 @@ class V {
 				if (is_scalar($from) || is_array($from) || is_object($from)) {
 					$ret = array();
 					$arr = $from;
-					settype($arr, $type);
+					settype($arr, 'array');
 					foreach ($arr as $v) {
-						$v = V::convert($v,'int');
+						$v = V::convert($v, 'int');
 						$ret[] = $v;
 					}
 				}
@@ -92,9 +99,9 @@ class V {
 				if (is_scalar($from) || is_array($from) || is_object($from)) {
 					$ret = array();
 					$arr = $from;
-					settype($arr, $type);
+					settype($arr, 'array');
 					foreach ($arr as $v) {
-						$v = V::convert($v,'int');
+						$v = V::convert($v, 'int');
 						if ($v <= 0) continue;
 						$ret[] = $v;
 					}
@@ -104,7 +111,7 @@ class V {
 				if (is_scalar($from) || is_array($from) || is_object($from)) {
 					$ret = array();
 					$arr = $from;
-					settype($arr, $type);
+					settype($arr, 'array');
 					foreach ($arr as $v) {
 						$v = V::convert($v, 'float');
 						$ret[] = $v;
@@ -250,4 +257,15 @@ class V {
 		return $label;
 	}
 
+	public static function filter($array, $filterCallback) {
+		if (!is_callable($filterCallback)) {
+			throw new Exception("callback is not callable '" . ((is_array($filterCallback))? implode('.', $filterCallback) : $filterCallback) . "'");
+		}
+		return array_filter($array, $filterCallback);
+	}
+
+	public static function filterNotEmpty($value) {
+		return !empty($value);
+	}
+
 }