Application.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: NODELOG
  5. * Date: 2016/11/6
  6. * Time: 下午6:17
  7. */
  8. namespace install;
  9. use Yii;
  10. class Application extends \yii\web\Application
  11. {
  12. public $installFile = '@root/web/storage/install.txt';
  13. public $envPath = '@root/.env';
  14. public function beforeAction($action)
  15. {
  16. if (parent::beforeAction($action)) {
  17. if ($this->checkInstalled() == true && Yii::$app instanceof \yii\web\Application) {
  18. Yii::$app->getResponse()->redirect('./');
  19. return false;
  20. }
  21. return true;
  22. }
  23. }
  24. public function checkInstalled()
  25. {
  26. return file_exists(Yii::getAlias($this->installFile));
  27. }
  28. public function setInstalled()
  29. {
  30. file_put_contents(Yii::getAlias($this->installFile), time());
  31. }
  32. public function setKeys($file)
  33. {
  34. $file = Yii::getAlias($file);
  35. $content = file_get_contents($file);
  36. $content = preg_replace_callback('/<generated_key>/', function () {
  37. $length = 32;
  38. $bytes = openssl_random_pseudo_bytes(32, $cryptoStrong);
  39. return strtr(substr(base64_encode($bytes), 0, $length), '+/', '_-');
  40. }, $content);
  41. file_put_contents($file, $content);
  42. }
  43. public function setEnv($name, $value)
  44. {
  45. $file = Yii::getAlias($this->envPath);
  46. if (!file_exists($file)) {
  47. @copy(Yii::getAlias('@root/.env.example'), $file);
  48. }
  49. $content = preg_replace("/({$name}\s*=)\s*(.*)/", "\${1}$value", file_get_contents($file));
  50. file_put_contents($file, $content);
  51. }
  52. }