Init.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace common\components;
  3. use Yii;
  4. use yii\base\BootstrapInterface;
  5. use yii\web\UnauthorizedHttpException;
  6. use common\models\member\Member;
  7. use common\helpers\StringHelper;
  8. use common\enums\AppEnum;
  9. /**
  10. * Class InitConfig
  11. * @package common\components
  12. * @author jianyan74 <751393839@qq.com>
  13. */
  14. class Init implements BootstrapInterface
  15. {
  16. /**
  17. * 应用ID
  18. *
  19. * @var
  20. */
  21. protected $id;
  22. /**
  23. * @param \yii\base\Application $application
  24. * @throws UnauthorizedHttpException
  25. * @throws \Exception
  26. */
  27. public function bootstrap($application)
  28. {
  29. Yii::$app->params['uuid'] = StringHelper::uuid('uniqid');
  30. $this->id = $application->id;// 初始化变量
  31. // 商户信息
  32. if (in_array(Yii::$app->id, [AppEnum::CONSOLE, AppEnum::BACKEND])) {
  33. $this->afreshLoad('');
  34. } elseif (in_array(Yii::$app->id, [AppEnum::MERCHANT, AppEnum::OAUTH2])) {
  35. /** @var Member $identity */
  36. $identity = Yii::$app->user->identity;
  37. $this->afreshLoad($identity->merchant_id ?? '');
  38. } else {
  39. $merchant_id = Yii::$app->request->headers->get('merchant-id', '');
  40. if (empty($merchant_id)) {
  41. $merchant_id = Yii::$app->request->get('merchant_id', '');
  42. }
  43. $this->afreshLoad($merchant_id);
  44. }
  45. }
  46. /**
  47. * @param $merchant_id
  48. * @throws UnauthorizedHttpException
  49. * @throws \yii\base\InvalidConfigException
  50. */
  51. public function afreshLoad($merchant_id)
  52. {
  53. try {
  54. Yii::$app->services->merchant->setId($merchant_id);
  55. // 初始化模块
  56. Yii::$app->setModules($this->getModulesByAddons());
  57. } catch (\Exception $e) {
  58. }
  59. }
  60. /**
  61. * 获取模块
  62. *
  63. * @throws \yii\base\InvalidConfigException
  64. */
  65. public function getModulesByAddons()
  66. {
  67. $addons = Yii::$app->services->addons->findCacheAllNames();
  68. $modules = [];
  69. $merchant = AppEnum::MERCHANT;
  70. foreach ($addons as $addon) {
  71. $name = $addon['name'];
  72. $app_id = $this->id;
  73. // 模块映射
  74. if ($this->id == AppEnum::BACKEND && $addon['is_merchant_route_map'] == true) {
  75. $app_id = $merchant;
  76. }
  77. $modules[StringHelper::toUnderScore($name)] = [
  78. 'class' => 'common\components\BaseAddonModule',
  79. 'name' => $name,
  80. 'app_id' => $app_id,
  81. ];
  82. // 初始化服务
  83. if (!empty($addon['service'])) {
  84. // 动态注入服务
  85. Yii::$app->set(lcfirst($name) . 'Service', [
  86. 'class' => $addon['service'],
  87. ]);
  88. }
  89. }
  90. return $modules;
  91. }
  92. }
粤ICP备19079148号