Skip to content

Commit

Permalink
新增keyMap
Browse files Browse the repository at this point in the history
  • Loading branch information
yf committed Nov 27, 2018
1 parent 60b7eb1 commit 4bb2cf3
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/SplBean.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ class SplBean implements \JsonSerializable
{
const FILTER_NOT_NULL = 1;
const FILTER_NOT_EMPTY = 2;//0 不算empty

private $_keyMap = [];

public function __construct(array $data = null,$autoCreateProperty = false)
{
$this->_keyMap = $this->setKeyMap();
if($data){
$this->arrayToBean($data,$autoCreateProperty);
}
Expand Down Expand Up @@ -59,6 +63,15 @@ function toArray(array $columns = null,$filter = null):array

final public function arrayToBean(array $data,$autoCreateProperty = false):SplBean
{
//先做keyMap转化
if(!empty($this->_keyMap)){
foreach ($this->_keyMap as $dataKey => $beanKey){
if(array_key_exists($dataKey,$data)){
$data[$beanKey] = $data[$dataKey];
unset($data[$dataKey]);
}
}
}
if($autoCreateProperty == false){
$data = array_intersect_key($data,array_flip($this->allProperty()));
}
Expand Down Expand Up @@ -89,6 +102,15 @@ final public function jsonSerialize():array
foreach ($this as $key => $item){
$data[$key] = $item;
}
unset($data['_keyMap']);
if(!empty($this->_keyMap)){
foreach ($this->_keyMap as $dataKey => $beanKey){
if(array_key_exists($beanKey,$data)){
$data[$dataKey] = $data[$beanKey];
unset($data[$beanKey]);
}
}
}
return $data;
}

Expand All @@ -100,6 +122,15 @@ protected function initialize():void

}

/*
* 如果需要用到keyMap 请在子类重构并返回对应的map数据
* return ['dataKey'=>'beanKey']
*/
protected function setKeyMap():array
{
return [];
}

public function __toString()
{
// TODO: Implement __toString() method.
Expand Down

0 comments on commit 4bb2cf3

Please sign in to comment.