【发布时间】:2018-08-31 08:32:34
【问题描述】:
我有一个检查 $value 类型是否有效的功能。我当前的代码是一个简单的 switch 案例,其中太多的案例超过了圈复杂度到 17。我需要添加更多案例并降低复杂度。
/**
* Check type of attribute value
* @param $type
* @param $value
* @return bool
*/
public function typeCheck($type, $value)
{
$this->value = $value;
switch ($type) {
case 'string':
return is_string($value) || is_integer($value) || is_bool($value);
case 'StringNotNull':
return is_string($value);
case 'LongStringNotNull':
return is_string($value);
case 'SuperLongStringNotNull':
return is_string($value);
case 'FortyStringNotNull':
return is_string($value) && (strlen($value) < 41);
case 'integer':
return is_numeric($value);
case 'positiveInteger':
return is_numeric($value) && ($value > 0);
case 'boolean':
return is_bool($value) || ($value == 'true' || $value = 'false');
case 'float':
return is_numeric($value);
case 'decimal':
return is_numeric($value);
case 'PositiveDimension':
return is_numeric($value) && ($value > 0);
case 'Dimension':
return is_numeric($value) && (strlen($value) < 13);
case 'Barcode':
$validator = $this->getBarcodeValidator();
$validator->setBarcode($value);
return is_string($value) && (strlen($value) < 17 && $validator->isValid());
case 'dateTime':
return true;
case 'normalizedString':
$this->value = strip_tags($value);
return is_string($value);
default:
return is_string($value);
}
}
有更好的方法吗?
【问题讨论】:
标签: php if-statement switch-statement cyclomatic-complexity