modified 完善mock随机库

This commit is contained in:
zhaoxiang 2018-08-24 19:11:30 +08:00
parent 7f7021371a
commit c693810513

View File

@ -28,7 +28,12 @@ class Mock {
"myNum|1-100" => 1,
"myFloat|1-100.1-10" => 1,
"myFa|123.1-10" => 1,
"myFb|123.3" => 1
"myFb|123.3" => 1,
"object|2" => [
"name|1-3" => ['myName', 123123, '1231541asdasd', 'jjjjsssss', '2345123afasgvawe'],
"name2|2" => ['myName', 123123, '1231541asdasd', 'jjjjsssss', '2345123afasgvawe'],
'age|25-68' => 1
]
];
$data = $this->buildData($config);
@ -54,6 +59,7 @@ class Mock {
$data[$name] = $this->buildInt($rule);
break;
case 'array':
$data[$name] = $this->buildArray($rule, $value);
break;
case 'string':
$data[$name] = $this->buildString($rule);
@ -113,6 +119,7 @@ class Mock {
$hasVertical = strstr($rule, '-');
if ($hasVertical) {
list($min, $max) = explode('-', $rule);
return mt_rand($min, $max);
} else {
return intval($rule);
@ -137,12 +144,81 @@ class Mock {
return Strs::randString($len);
}
private function buildArray($rule = '') {
/**
* 构建随机的数组列表数据
* @param string $rule
* @param array $value
* @return array
* @author zhaoxiang <zhaoxiang051405@gmail.com>
*/
private function buildArray($rule = '', $value = []) {
$isAssoc = $this->isAssoc($value);
if ($isAssoc) {
$has = strstr($rule, '-');
if ($has) {
list($min, $max) = explode('-', $rule);
$num = mt_rand($min, $max);
} else {
$num = intval($rule);
}
$res = [];
for ($i = 0; $i < $num; $i++) {
$new = [];
foreach ($value as $vKey => $item) {
$hasVertical = strstr($vKey, '|');
if ($hasVertical) {
$new = array_merge($new, $this->buildData([$vKey => $item]));
} else {
$new[$vKey] = $item;
}
}
$res[] = $new;
}
return $res;
} else {
$hasVertical = strstr($rule, '-');
if ($hasVertical) {
$new = [];
list($min, $max) = explode('-', $rule);
$num = mt_rand($min, $max);
for ($i = 0; $i < $num; $i++) {
$new = array_merge($new, $value);
}
return $new;
} else {
$rule = intval($rule);
if (count($value) <= $rule) {
return $value;
} else {
$new = [];
shuffle($value);
for ($i = 0; $i < $rule; $i++) {
$new[] = $value[$i];
}
return $new;
}
}
}
}
private function buildObject($rule = '') {
/**
* 判断是否是关联数组
* @param $array
* @return bool true 是关联数组 false 是索引数组
* @author zhaoxiang <zhaoxiang051405@gmail.com>
*/
private function isAssoc($array) {
if (is_array($array)) {
$keys = array_keys($array);
return $keys !== array_keys($keys);
}
return false;
}
}