* Format fields of response data.

This commit is contained in:
zhujinyong
2021-07-21 06:44:41 +08:00
parent 51558901a5
commit 8f6bf9800e
20 changed files with 155 additions and 39 deletions
+99
View File
@@ -381,4 +381,103 @@ class baseEntry
}
}
}
/**
* 格式化数据的字段类型.
* Format fields of response data.
*
* @param object|array $data
* @param string $fields
* @access public
* @return object|array
*/
public function format($data, $fields)
{
if(is_array($data))
{
foreach($data as $object) $this->formatFields($object, $fields);
}
$this->formatFields($data, $fields);
return $data;
}
/**
* 格式化对象的字段类型.
* Format fields of object.
*
* @param object $object
* @param string $fields
* @access public
* @return object
*/
private function formatFields(&$object, $fields)
{
$fields = explode(',', $fields);
foreach($fields as $field)
{
$field = explode(':', $field);
$key = $field[0];
$type = $field[1];
$isArray = false;
$pos = strpos($type, ']');
if($pos !== FALSE)
{
$is_array = true;
$type = substr($type, $pos + 1);
}
/* Format value. */
if(!$isArray)
{
$object->$key = $this->cast($object->$key, $type);
continue;
}
/* Format array. */
$value = array();
if(is_array($object->$key))
{
foreach($object->$key as $v) $value[] = $this->cast($v, $type);
}
else
{
$vs = implode(',', $object->$key);
foreach($vs as $v)
{
if($v === '') continue;
$value[] = $this->cast($v, $type);
}
}
$object->$key = $value;
}
}
/**
* 类型转换.
* Typecasting.
*
* @param mixed $vaule
* @param string $type
* @access public
* @return mixed
*/
private function cast($value, $type)
{
switch($type)
{
case 'time':
$timeFormat = $this->param('timeFormat', '');
if($timeFormat == 'utc')
{
if(!$value or $value == '0000-00-00 00:00:00') return null;
return gmdate("Y-m-d\TH:i:s\Z", strtotime($value));
}
return $value;
default:
return $value;
}
}
}