Files
xk-api-yii/common/core/BaseActiveRecord.php

63 lines
2.0 KiB
PHP
Raw Normal View History

2024-09-19 11:32:39 +08:00
<?php
namespace common\core;
2025-01-15 13:16:48 +08:00
use common\services\DataEncryptor;
use Yii;
2024-09-19 11:32:39 +08:00
use yii\base\Exception;
use yii\db\ActiveRecord;
/**
* 对框架的AR的扩展所有前台/后台数据模型都继承自该类
*/
class BaseActiveRecord extends ActiveRecord
{
public function saveOrFail($runValidation = true, $attributeNames = null){
if(!$this->save($runValidation, $attributeNames)){
throw new Exception(implode(',',$this->getFirstErrors()));
}
return true;
}
2025-01-15 13:16:48 +08:00
/**
* 新增和编辑数据的时候
* @param $insert
* @throws \Exception
*/
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
// 加密ID卡信息之前检查是否已经加密过
2025-01-18 09:44:50 +08:00
if (!empty($this->idcard) && !$this->is_encrypted($this->idcard)) {
2025-01-15 13:16:48 +08:00
$this->idcard = (new DataEncryptor(\Yii::$app->params['ase_key']))->encrypt($this->idcard);
}
// 加密ID卡信息之前检查是否已经加密过
2025-01-18 09:44:50 +08:00
if (!empty($this->id_card) && !$this->is_encrypted($this->id_card)) {
2025-01-15 13:16:48 +08:00
$this->id_card = (new DataEncryptor(\Yii::$app->params['ase_key']))->encrypt($this->id_card);
}
return true;
}
return false;
}
public function afterFind()
{
parent::afterFind();
// 解密ID卡信息之前检查是否已经是明文
2025-01-18 09:44:50 +08:00
if (!empty($this->id_card) && $this->is_encrypted($this->id_card)) {
2025-01-15 13:16:48 +08:00
$this->id_card = (new DataEncryptor(Yii::$app->params['ase_key']))->decrypt($this->id_card);
}
2025-01-18 09:44:50 +08:00
if (!empty($this->idcard) && $this->is_encrypted($this->idcard)) {
2025-01-15 13:16:48 +08:00
$this->idcard = (new DataEncryptor(Yii::$app->params['ase_key']))->decrypt($this->idcard);
}
}
2025-01-18 09:44:50 +08:00
private function is_encrypted($data): bool
{
if (!is_string($data)) {
return false;
}
// 这里应该有逻辑来判断$data是否已经被加密。未加密是true
return strpos($data, 'xk_ase_256_') === 0;
}
2024-09-19 11:32:39 +08:00
}