Yii2 model rules自定义验证方法

公式验证
本文介绍了一种用于验证条件表达式和结果表达式的模型类。通过预设和自定义的公式变量进行合法性检查,确保了公式的正确性和安全性。
<?php

namespace common\models;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
/**
 * This is the model class for table "formula_item".
 *
 * @property int $id
 * @property int $formula_id
 * @property string $condition
 * @property string $outcome
 */
class FormulaItem extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'formula_item';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['formula_id'], 'integer'],
            [['condition', 'outcome'], 'string', 'max' => 2000],
            ['condition', 'validateCondition'],
            ['outcome', 'validateOutcome'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'formula_id' => 'Formula ID',
            'condition' => '条件表达式',
            'outcome' => '结果表达式',
        ];
    }

    //验证条件表达式合法性
    public function validateCondition($attribute,$params)
    {
        if(!$this->hasErrors())
        {
            $is_ok = self::conditionIsValid($this->$attribute);
            if(!$is_ok){
                $this->addError($attribute, "条件表达式有错误: {$this->$attribute}");
            }
        }
    }
    //验证结果表达式合法性
    public function validateOutcome($attribute, $params)
    {
        if(!$this->hasErrors())
        {
            $is_ok = self::outcomeIsValid($this->$attribute);
            if(!$is_ok){
                $this->addError($attribute, "结果表达式有错误: {$this->$attribute}");
            }
        }
    }

    /**
     * 判断条件表达式是否有效
     *
     * @param   string      $str
     *
     * @return  boolean
     */
    public static function conditionIsValid($str)
    {
        $is_ok = false;
        try
        {
            if($str == ''){
                return true;
            }

            ini_set('track_errors',true);
            $php_errormsg = null;

            //预设的公式变量
            $default = array_keys(FormulaVar::getDefaultList());
            //自定义的公式变量
            $list = FormulaVar::find()->asArray()->all();
            $keys = ArrayHelper::getColumn($list,'key');
            //预设的公式变量+自定义的公式变量
            $keys = array_merge($default,$keys);

            $args = [];
            foreach($keys as $k => $v){
                $args[$v] = 1;
                //字符串的vars变成args
                $find = "vars['" . $v . "']";
                $replace = '$args[' ."'" . $v ."']";
                $str = str_replace($find,$replace,$str);
            }

            $result = @eval("return $str;");
            //$result = @eval("return is_bool($str);");

            //if($php_errormsg == null && $result){
            if($php_errormsg == null){
                $is_ok = true;
            }
        }
        catch(\Error $e)
        {
            $is_ok = false;
        }
        return $is_ok;
    }
    /**
     * 判断结果表达式是否有效
     *
     * @param   string      $str
     *
     * @return  boolean
     */
    public static function outcomeIsValid($str)
    {
        $is_ok = false;
        try
        {
            ini_set('track_errors',true);
            $php_errormsg = null;

            //预设的公式变量
            $default = array_keys(FormulaVar::getDefaultList());
            //自定义的公式变量
            $list = FormulaVar::find()->asArray()->all();
            $keys = ArrayHelper::getColumn($list,'key');
            //预设的公式变量+自定义的公式变量
            $keys = array_merge($default,$keys);

            $args = [];
            foreach($keys as $k => $v){
                $args[$v] = 1;
                //字符串的vars变成args
                $find = "vars['" . $v . "']";
                $replace = '$args[' ."'" . $v ."']";
                $str = str_replace($find,$replace,$str);
            }

            //$result = @eval("return $str;");
            $result = @eval("return is_numeric($str);");
            if($php_errormsg == null && $result){
                $is_ok = true;
            }
        }
        catch(\Error $e)
        {
            $is_ok = false;
        }
        return $is_ok;
    }

}

<?php

namespace common\models;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
/**
 * This is the model class for table "formula_var_item".
 *
 * @property int $id
 * @property int $formula_var_id
 * @property string $condition
 * @property string $formula
 */
class FormulaVarItem extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'formula_var_item';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['formula_var_id'], 'integer'],
            [['condition', 'outcome'], 'string', 'max' => 2000],
            ['condition', 'validateCondition'],
            ['outcome', 'validateOutcome'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'formula_var_id' => 'formula_var_id',
            'condition' => '条件表达式',
            'outcome' => '结果表达式',
        ];
    }

    //验证条件表达式合法性
    public function validateCondition($attribute,$params)
    {
        if(!$this->hasErrors())
        {
            $is_ok = self::conditionIsValid($this->$attribute);
            if(!$is_ok){
                $this->addError($attribute, "条件表达式有错误: {$this->$attribute}");
            }
        }
    }
    //验证结果表达式合法性
    public function validateOutcome($attribute, $params)
    {
        if(!$this->hasErrors())
        {
            $is_ok = self::outcomeIsValid($this->$attribute);
            if(!$is_ok){
                $this->addError($attribute, "结果表达式有错误: {$this->$attribute}");
            }
        }
    }

    /**
     * 判断条件表达式是否有效
     *
     * @param   string      $str
     *
     * @return  boolean
     */
    public static function conditionIsValid($str)
    {
        $is_ok = false;
        try
        {
            if($str == ''){
                return true;
            }

            ini_set('track_errors',true);
            $php_errormsg = null;

            //预设的公式变量
            $default = array_keys(FormulaVar::getDefaultList());
            //自定义的公式变量
            $list = FormulaVar::find()->asArray()->all();
            $keys = ArrayHelper::getColumn($list,'key');
            //预设的公式变量+自定义的公式变量
            $keys = array_merge($default,$keys);

            $args = [];
            foreach($keys as $k => $v){
                $args[$v] = 1;
                //字符串的vars变成args
                $find = "vars['" . $v . "']";
                $replace = '$args[' ."'" . $v ."']";
                $str = str_replace($find,$replace,$str);
            }

            //$result = @eval("return $str;");
            $result = @eval("return is_bool($str);");

            //if($php_errormsg == null && $result){
            if($php_errormsg == null){
                $is_ok = true;
            }
        }
        catch(\Error $e)
        {
            $is_ok = false;
        }
        return $is_ok;
    }
    /**
     * 判断结果表达式是否有效
     *
     * @param   string      $str
     *
     * @return  boolean
     */
    public static function outcomeIsValid($str)
    {
        $is_ok = false;
        try
        {
            ini_set('track_errors',true);
            $php_errormsg = null;

            //预设的公式变量
            $default = array_keys(FormulaVar::getDefaultList());
            //自定义的公式变量
            $list = FormulaVar::find()->asArray()->all();
            $keys = ArrayHelper::getColumn($list,'key');
            //预设的公式变量+自定义的公式变量
            $keys = array_merge($default,$keys);

            $args = [];
            foreach($keys as $k => $v){
                $args[$v] = 1;
                //字符串的vars变成args
                $find = "vars['" . $v . "']";
                $replace = '$args[' ."'" . $v ."']";
                $str = str_replace($find,$replace,$str);
            }

            //$result = @eval("return $str;");
            $result = @eval("return is_numeric($str);");
            if($php_errormsg == null && $result){
                $is_ok = true;
            }
        }
        catch(\Error $e)
        {
            $is_ok = false;
        }
        return $is_ok;
    }

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值