<file_sep><?php
return [
    'user' => [
        'class' => 'weikit\core\components\web\User',
        'identityClass' => 'weikit\core\models\User',
        'enableAutoLogin' => true,
        'founders' => [1] // 创始人ID可多个
    ],
    'db' => require(__DIR__ . '/db.php'),
    'authManager' => [
        'class' => 'yii\rbac\DbManager'
    ],
    'cache' => [
        'class' => 'yii\caching\FileCache',
    ],
    'log' => [
        'traceLevel' => YII_DEBUG ? 3 : 0,
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
                'levels' => ['error', 'warning'],
            ],
        ],
    ],
    'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        // send all mails to a file by default. You have to set
        // 'useFileTransport' to false and configure a transport
        // for the mailer to send real emails.
        'useFileTransport' => true,
    ],
    'formatter' => [
        'datetimeFormat' => 'php:Y-m-d H:i:s'
    ],
    'httpClient' => [
        'class' => 'yii\httpclient\Client',
        'transport' => 'yii\httpclient\CurlTransport',
        'requestConfig' => [
            'options' => [
                'CONNECTTIMEOUT' => 60,
                'TIMEOUT' => 60,
                'USERAGENT' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1',
                'SSL_VERIFYPEER' => false,
                'SSL_VERIFYHOST' => 0,
                'SSLVERSION' => CURL_SSLVERSION_TLSv1,
            ]
        ]
    ],
    'config' => [
        'class' => 'weikit\core\components\base\Config'
    ]
];<file_sep><?php
if (php_sapi_name() != 'cli') {
    exit('如果您看到这条消息, 那就是说您还未执行安装程序, 请参考文档在命令行执行安装程序!');
}

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=weikit',
    'username' => 'root',
    'password' => '',
    'tablePrefix' => 'wk_',
    'charset' => 'utf8',
    'enableSchemaCache' => !YII_DEBUG
];<file_sep><?php

return [
    /* 系统内置模块 !!慎重修改!! */
    'admin' => [
        'class' => 'weikit\core\modules\admin\Module',
        'modules' => [
            'wechat' => ['class' => 'weikit\core\modules\wechat\admin\Module'],
            'user' => ['class' => 'weikit\core\modules\user\admin\Module'],
        ]
    ],
    'user' => [
        'class' => 'weikit\core\modules\user\Module'
    ],
    'wechat' => [
        'class' => 'weikit\core\modules\wechat\Module'
    ],
    'component' => [
        'class' => 'weikit\core\modules\component\Module'
    ],
    'gridview' =>  ['class' => '\kartik\grid\Module'],

    /* 自定义模块 */
//    'xxx' =>  ['class' => 'app\modules\xxx\Module']
];<file_sep><?php
defined('TIMESTAMP') or define('TIMESTAMP', time());

$params = require(__DIR__ . '/params.php');

$config = [
    'id' => 'weikit',
    'basePath' => dirname(__DIR__),
    'language' => 'zh-CN',
    'timeZone' => 'Asia/Shanghai',
    'bootstrap' => ['log'],
    'modules' => require (__DIR__ . '/modules.php'),
    'components' => array_merge(require(__DIR__ . '/components.php'), [
        'request' => [
            'class' => 'weikit\core\components\web\Request',
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => '1',
            'parsers' => [ // Raw方式提交的json数据解析
                'application/json' => 'yii\web\JsonParser',
            ]
        ],
        'response' => [
            'class' => 'weikit\core\components\web\Response',
        ],
        'urlManager' => [
            'class' => 'yii\web\UrlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => false
        ],
        'assetManager' => [
            'forceCopy' => YII_DEBUG
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
    ]),
    'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        'panels' => [
            'httpclient' => [
                'class' => 'yii\httpclient\debug\HttpClientPanel',
            ]
        ]
    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        'generators' => [
            'adminCrud' => [
                'class' => 'weikit\core\generators\admin\crud\Generator'
            ],
            'wechatModule' => [
                'class' => 'weikit\core\generators\wechat\module\Generator'
            ]
        ]
    ];
}

return $config;
<file_sep><?php
namespace app\commands;

use Yii;
use yii\helpers\Console;
use yii\console\Controller;

/**
 * Class WeikitController
 * @package app\commands
 */
class WeikitController extends Controller
{
    public $defaultSteps = [
        '运行环境监测' => 'check',
        '数据库配置' => 'db',
        '初始化数据库数据' => 'migrate'
    ];

    /**
     * 安装
     */
    public function actionInstall()
    {
        $lockFile = Yii::getAlias('@app/install.lock');
        if (file_exists($lockFile)) {
            $this->stdout("站点已经配置完毕,无需再配置\n", Console::FG_GREEN);
            usleep(500000);
            $this->stdout("\n - 如需重新配置, 请删除{$lockFile}文件后再执行命令!\n");
            return;
        }
        $result = $this->runSteps($this->defaultSteps);
        if ($result) {
            sleep(1);
            $this->stdout("恭喜, 站点配置成功!\n", Console::FG_GREEN);
            touch($lockFile);
        }
    }

    /**
     * 检查当前环境是否可用
     *
     * @param string $path
     * @return bool|null
     */
    public function actionCheck($path = '@app/requirements.php')
    {
        ob_start();
        ob_implicit_flush(false);
        require Yii::getAlias($path);
        $content = ob_get_clean();
        $content = strtr($content, [
            'OK' => $this->ansiFormat("OK", Console::FG_GREEN),
            'WARNING!!!' => $this->ansiFormat("WARNING!!!", Console::FG_YELLOW),
            'FAILED!!!' => $this->ansiFormat("FAILED!!!", Console::FG_RED)
        ]);

        foreach (explode("\n\n", $content) as $line) {
            $this->stdout($line . "\n\n");
            usleep(200000);
        }

        if (stripos($content, 'FAILED!!!') !== false) {
            $this->stdout('*** 运行环境监测不通过, 请修复红色字体行所需的环境后重试 ***', Console::FG_RED);
            return false;
        }
    }

    /**
     * 生成数据库配置文件
     * @return mixed
     */
    public function actionDb()
    {
        $dbFile = Yii::getAlias('@app/config/db.php');
        $result = $this->generateDbFile($dbFile);
        if ($result !== false) { // 生成文件了之后.加载db配置
            Yii::$app->set('db', require $dbFile);
        }
        return $result;
    }

    /**
     * 创建数据库配置文件
     *
     * @param $dbFile
     * @return mixed
     */
    protected function generateDbFile($dbFile)
    {
        $host = $this->prompt('请输入数据库主机地址:', [
            'default' => 'localhost'
        ]);
        $dbName = $this->prompt("请输入数据库名称:", [
            'default' => 'weikit'
        ]);
        $dbConfig = [
            'dsn' => "mysql:host={$host};dbname={$dbName}",
            'username' => $this->prompt("请输入数据库访问账号:", [
                'default' => 'root'
            ]),
            'password' => $this->prompt("请输入数据库访问密码:"),
            'tablePrefix' => $this->prompt("请输入数据库表前缀:", [
                'default' => 'wk_'
            ]),
            'charset' => $this->prompt("请输入数据默认的字符集:", [
                'default' => 'utf8'
            ])
        ];
        if (empty($dbName)) {
            $dbConfig['dsn'] .= $dbConfig['username'];
        }
        $message = null;
        if ($this->confirm('是否测试数据库可用?', true)) {
            $db = Yii::createObject(array_merge(['class' => 'yii\db\Connection'], $dbConfig));
            try {
                $db->open();
                $this->stdout("数据连接成功\n", Console::FG_GREEN);
            } catch (\Exception $e) {
                $this->stdout("数据连接失败:" . $e->getMessage() . "\n", Console::FG_RED);
                $message = '依然写入文件?(如果依然写入文件, 会影响后续安装步骤)';
            }
        }
        if ($message === null || $this->confirm($message)) {
            $this->stdout("生成数据库配置文件...\n");
            $code = <<<EOF
<?php
return [
    'class' => 'yii\db\Connection',
    'dsn' => '{$dbConfig['dsn']}',
    'username' => '{$dbConfig['username']}',
    'password' => '{$dbConfig['password']}',
    'tablePrefix' => '{$dbConfig['tablePrefix']}',
    'charset' => '{$dbConfig['charset']}',
    'enableSchemaCache' => !YII_DEBUG
];
EOF;
            file_put_contents($dbFile, $code);
            $this->stdout("恭喜! 数据库配置完毕!\n", Console::FG_GREEN);
        } elseif($this->confirm("是否重新设置?", true)) {
            return $this->generateDbFile($dbFile);
        } else {
            return false;
        }
    }


    public $defaultMigrationPath = [
        '默认目录' => '@app/migrations',
        '内核目录' => '@weikit/core/migrations'
    ];
    /**
     * 迁移数据库
     */
    public function actionMigrate()
    {
        $this->stdout("\n开始迁移数据库结构和数据\n", Console::FG_YELLOW);
        $this->stdout("\n\n** 如无特殊需求,当询问是否迁移数据时回复yes即可 **\n\n", Console::FG_RED);
        sleep(3);
        foreach ($this->defaultMigrationPath as $name => $migrationPath) {
            $migrationPath = Yii::getAlias($migrationPath);
            if (!is_dir($migrationPath)) {
                continue;
            }
            $this->stdout("\n\n正在执行{$name}迁移: {$migrationPath}\n", Console::FG_YELLOW);
            Yii::$app->runAction('migrate/up', ['migrationPath' => $migrationPath]);
        }
    }
    
    /**
     * 运行安装步骤
     *
     * @param array $steps
     * @return bool
     */
    protected function runSteps(array $steps)
    {
        $i = 1;
        foreach ($steps as $step => $args) {
            $this->stdout("\n\n - Step {$i} {$step} \n");
            $this->stdout("==================================================\n");
            !is_array($args) && $args = (array)$args;
            $method = array_shift($args);
            usleep(500000);
            $result = call_user_func_array([$this, 'action' . $method], $args);
            if ($result === false) {
                $this->stdout("{$step}失败, 退出安装流程\n", Console::FG_RED);
                return false;
            }
            sleep(1);
            $i++;
        }
        return true;
    }
}