Skip to content

Commit

Permalink
改进模型数据初始化
Browse files Browse the repository at this point in the history
  • Loading branch information
liu21st committed Nov 18, 2024
1 parent 00aed1c commit 75c41b6
Showing 1 changed file with 38 additions and 30 deletions.
68 changes: 38 additions & 30 deletions src/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,6 @@ abstract class Entity implements JsonSerializable, ArrayAccess, Arrayable, Jsona
*/
public function __construct(array | object $data = [], ?Model $model = null)
{
// 解析模型数据
$data = $this->parseData($data);

// 获取对应模型对象
if (is_null($model)) {
$class = $this->parseModel();
Expand All @@ -69,19 +66,41 @@ public function __construct(array | object $data = [], ?Model $model = null)
];

$model->setEntity($this);

// 初始化模型数据
$this->initializeData($data);
}

/**
* 数据读取 类型转换.
* 解析模型实例名称.
*
* @return string
*/
protected function parseModel(): string
{
return str_replace('\\entity', '\\model', static::class);
}

/**
* 获取模型实例.
*
* @return Model
*/
public function model(): Model
{
return self::$weakMap[$this]['model'];
}

/**
* 初始化模型数据.
*
* @param array|object $data 实体模型数据
*
* @return void
*/
protected function initializeData(array | object $data)
{
// 分析数据
$data = $this->parseData($data);
// 获取字段列表
$schema = $this->getFields();
$fields = array_keys($schema);
Expand Down Expand Up @@ -226,26 +245,6 @@ protected function writeTransform($value, string $type)
};
}

/**
* 解析模型实例名称.
*
* @return string
*/
protected function parseModel()
{
return str_replace('entity', 'model', static::class);
}

/**
* 获取模型实例.
*
* @return Model
*/
public function model(): Model
{
return self::$weakMap[$this]['model'];
}

/**
* 获取数据表字段列表.
*
Expand Down Expand Up @@ -361,13 +360,12 @@ public function save(array | object $data = []): bool
}

if (!empty($data)) {
$data = $this->parseData($data);
// 初始化模型数据
$this->initializeData($data);
} else {
$data = $this->getData($this);
}

$origin = self::$weakMap[$this]['origin'];
$data = $this->getData();
$origin = $this->getOrigin();
$isUpdate = $this->model()->getKey();

foreach ($data as $name => &$val) {
Expand Down Expand Up @@ -553,7 +551,7 @@ public function setKey($value)
*
* @return array
*/
protected function getData(): array
public function getData(): array
{
if ($this->isStrictMode()) {
$class = new class {
Expand All @@ -571,6 +569,16 @@ function getPublicVars($object)
return $data;
}

/**
* 获取原始数据.
*
* @return array
*/
public function getOrigin(): array
{
return self::$weakMap[$this]['origin'];
}

/**
* 模型数据转数组.
*
Expand Down

0 comments on commit 75c41b6

Please sign in to comment.