<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "{{%route_rule}}".
 *
 * @property string $id
 * @property string $name
 * @property string $controller
 * @property string $action
 * @property string $rule
 * @property integer $status
 */
class RouteRule extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%route_rule}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'controller', 'action', 'rule', 'status'], 'required'],
            [['status'], 'integer'],
            [['name', 'controller', 'action'], 'string', 'max' => 30],
            [['rule'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '页面',
            'controller' => '控制器',
            'action' => '方法',
            'rule' => '规则',
            'status' => '状态',
        ];
    }
    public static function updateCache(){
        $config = \common\models\Config::find()->asArray()->indexBy('name')->all();
        $data = self::find()->where(['status'=>1])->all();
        $content = "<?php\n\$config=[\n";
        $content.= "'components'=>[\n";
        $content.= "'urlManager'=>[\n";
        $content.= "'enablePrettyUrl' => ".$config['enablePrettyUrl']['value'].",\n";
        $content.= "'showScriptName' => ".$config['showScriptName']['value'].",\n";
        $content.= "'suffix' => '".$config['suffix']['value']."',\n";
        $content.= "'enableStrictParsing' => ".$config['enableStrictParsing']['value'].",\n";
        $content.= "'rules' => [\n";
        foreach ($data as $key => $value) {
            $content .= "'".$value['rule']."'=>'".$value['controller']."/".$value['action']."',\n";
        }
        $content.= "],\n";
        $content.= "],\n";
        $content.= "],\n";
        $content.= "];\n";
        $content.= "return \$config;";
        file_put_contents(FRONTEND_CONF_PATH.'route-rule.php',$content);
        return true;
    }
    public function afterSave($insert, $changedAttributes){
        parent::afterSave($insert, $changedAttributes);
        self::updateCache();
        return true;
    }
    public function afterDelete(){
        parent::afterDelete();
        self::updateCache();
        return true;
    }
}
