AddonsService.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. namespace services\common;
  3. use Yii;
  4. use yii\helpers\Console;
  5. use yii\web\NotFoundHttpException;
  6. use yii\web\UnprocessableEntityHttpException;
  7. use common\enums\StatusEnum;
  8. use common\helpers\ArrayHelper;
  9. use common\helpers\AddonHelper;
  10. use common\models\common\Addons;
  11. use common\components\BaseAddonConfig;
  12. use common\components\Service;
  13. use common\helpers\StringHelper;
  14. use common\enums\AppEnum;
  15. use common\enums\OfficialEnum;
  16. use common\interfaces\AddonWidget;
  17. use Overtrue\Pinyin\Pinyin;
  18. /**
  19. * Class AddonsService
  20. * @package services\common
  21. */
  22. class AddonsService extends Service
  23. {
  24. /**
  25. * 初始化模块信息
  26. *
  27. * @param $name
  28. * @return array|\yii\db\ActiveRecord|null
  29. * @throws NotFoundHttpException
  30. */
  31. public function initParams($name)
  32. {
  33. if (!$name) {
  34. throw new NotFoundHttpException("插件不能为空");
  35. }
  36. if (!($addon = Yii::$app->services->addons->findCacheByName($name, Yii::$app->id == AppEnum::BACKEND))) {
  37. throw new NotFoundHttpException("插件不存在");
  38. }
  39. Yii::$app->params['addon'] = $addon;
  40. Yii::$app->params['addonName'] = StringHelper::toUnderScore(Yii::$app->params['addon']['name']);
  41. Yii::$app->params['inAddon'] = true;
  42. return $addon;
  43. }
  44. /**
  45. * 更新配置
  46. *
  47. * @param $name
  48. * @param BaseAddonConfig $config
  49. * @param $default_config
  50. * @return array|Addons|\yii\db\ActiveRecord|null
  51. * @throws NotFoundHttpException
  52. */
  53. public function updateByName($name, $config, $default_config)
  54. {
  55. if (!($model = $this->findByName($name))) {
  56. $model = new Addons();
  57. $model = $model->loadDefaultValues();
  58. }
  59. $model->attributes = $config->info;
  60. $model->is_merchant_route_map = $config->isMerchantRouteMap ? StatusEnum::ENABLED : StatusEnum::DISABLED;
  61. $model->group = $config->group;
  62. $model->bootstrap = $config->bootstrap ?? '';
  63. $model->service = $config->service ?? '';
  64. $model->default_config = $default_config;
  65. $model->console = $config->console ?? [];
  66. $model->updated_at = time();
  67. // 首先字母转大写拼音
  68. if (($chinese = StringHelper::strToChineseCharacters($model->title)) && !empty($chinese[0])) {
  69. $title_initial = mb_substr($chinese[0][0], 0, 1, 'utf-8');
  70. $model->title_initial = ucwords((new Pinyin())->abbr($title_initial));
  71. }
  72. !$model->save() && $this->error($model);
  73. // 更新缓存
  74. Yii::$app->services->addons->updateCacheByName($name);
  75. return $model;
  76. }
  77. /**
  78. * 升级数据库
  79. *
  80. * @param $name
  81. * @return bool
  82. * @throws NotFoundHttpException
  83. * @throws UnprocessableEntityHttpException
  84. */
  85. public function upgradeSql($name)
  86. {
  87. if (
  88. !($class = AddonHelper::getConfigClass($name)) ||
  89. !($model = $this->findByName($name))
  90. ) {
  91. throw new NotFoundHttpException('实例化失败,插件不存在或检查插件名称');
  92. }
  93. // 更新数据库
  94. $upgradeClass = AddonHelper::getAddonRoot($name) . (new $class)->upgrade;
  95. if (!class_exists($upgradeClass)) {
  96. throw new NotFoundHttpException($upgradeClass . '未找到');
  97. }
  98. /** @var AddonWidget $upgradeModel */
  99. $upgradeModel = new $upgradeClass;
  100. if (!method_exists($upgradeModel, 'run')) {
  101. throw new NotFoundHttpException($upgradeClass . '/run方法未找到');
  102. }
  103. if (!isset($upgradeModel->versions)) {
  104. throw new NotFoundHttpException($upgradeClass . '下 versions 属性未找到');
  105. }
  106. $versions = $upgradeModel->versions;
  107. $count = count($versions);
  108. for ($i = 0; $i < $count; $i++) {
  109. // 验证版本号和更新
  110. if ($model->version == $versions[$i] && isset($versions[$i + 1])) {
  111. // 开启事务
  112. $transaction = Yii::$app->db->beginTransaction();
  113. try {
  114. $model->version = $versions[$i + 1];
  115. $upgradeModel->run($model);
  116. $model->save();
  117. // 输出日志
  118. Yii::$app->id == AppEnum::CONSOLE && Console::output('updating...' . $model->version . '...' . date('Y-m-d H:i:s'));
  119. // 完成事务
  120. $transaction->commit();
  121. } catch (\Exception $e) {
  122. // 回滚事务
  123. $transaction->rollBack();
  124. throw new UnprocessableEntityHttpException($e->getMessage());
  125. }
  126. }
  127. }
  128. return true;
  129. }
  130. /**
  131. * 获取本地插件列表
  132. *
  133. * @return array
  134. */
  135. public function getLocalList()
  136. {
  137. $addonDir = Yii::getAlias('@addons');
  138. // 获取插件列表
  139. $dirs = array_map('basename', glob($addonDir . '/*'));
  140. $list = ArrayHelper::toArray($this->findByNames($dirs, ['*']));
  141. $tmpAddons = ArrayHelper::arrayKey($list, 'name');
  142. $addons = [];
  143. foreach ($dirs as $value) {
  144. // 判断是否安装
  145. if (!isset($tmpAddons[$value])) {
  146. // 实例化插件失败忽略执行
  147. if (class_exists($class = AddonHelper::getAddonConfig($value))) {
  148. $config = new $class;
  149. $addons[$value] = $config->info;
  150. }
  151. }
  152. }
  153. return $addons;
  154. }
  155. /**
  156. * @param $name
  157. * @return array|null|\yii\db\ActiveRecord
  158. */
  159. public function findCacheByName($name, $noCache = false)
  160. {
  161. $cacheKey = 'addon'. ':' . Yii::$app->id . ':' . $name;
  162. if (!$noCache && Yii::$app->cache->exists($cacheKey)) {
  163. return Yii::$app->cache->get($cacheKey);
  164. }
  165. $data = $this->findByName($name);
  166. if (Yii::$app->id == AppEnum::CONSOLE) {
  167. return $data;
  168. }
  169. Yii::$app->cache->set($cacheKey, $data, 360);
  170. return $data;
  171. }
  172. /**
  173. * 获取插件名称列表
  174. *
  175. * @param bool $noCache
  176. * @return array|mixed|\yii\db\ActiveRecord[]
  177. */
  178. public function findCacheAllNames($noCache = false)
  179. {
  180. if (Yii::$app->id == AppEnum::CONSOLE) {
  181. return $this->findAllInInit();
  182. }
  183. $cacheKey = 'addonsName';
  184. if (!$noCache && Yii::$app->cache->exists($cacheKey)) {
  185. return Yii::$app->cache->get($cacheKey);
  186. }
  187. $models = $this->findAllInInit();
  188. Yii::$app->cache->set($cacheKey, $models, 360);
  189. return $models;
  190. }
  191. /**
  192. * @return array|\yii\db\ActiveRecord[]
  193. */
  194. protected function findAllInInit()
  195. {
  196. return Addons::find()
  197. ->select(['name', 'is_merchant_route_map', 'service', 'updated_at'])
  198. ->where(['status' => StatusEnum::ENABLED])
  199. ->asArray()
  200. ->all();
  201. }
  202. /**
  203. * 获取列表
  204. *
  205. * @return array|\yii\db\ActiveRecord[]
  206. */
  207. public function findAll()
  208. {
  209. return Addons::find()
  210. ->where(['status' => StatusEnum::ENABLED])
  211. ->asArray()
  212. ->all();
  213. }
  214. /**
  215. * @param $name
  216. * @return array|null|\yii\db\ActiveRecord|Addons
  217. */
  218. public function findByName($name)
  219. {
  220. return Addons::find()
  221. ->where(['name' => $name, 'status' => StatusEnum::ENABLED])
  222. ->one();
  223. }
  224. /**
  225. * @param array $names
  226. * @return array|\yii\db\ActiveRecord[]
  227. */
  228. public function findByNames(array $names, $select = ['id', 'name', 'title'])
  229. {
  230. return Addons::find()
  231. ->select($select)
  232. ->where(['status' => StatusEnum::ENABLED])
  233. ->andWhere(['in', 'name', $names])
  234. ->all();
  235. }
  236. /**
  237. * @param array $names
  238. * @return array|\yii\db\ActiveRecord[]
  239. */
  240. public function findBrief()
  241. {
  242. return Addons::find()
  243. ->select(['title', 'name', 'group'])
  244. ->asArray()
  245. ->all();
  246. }
  247. /**
  248. * @param $name
  249. * @return array|null|\yii\db\ActiveRecord
  250. */
  251. public function findAuthority()
  252. {
  253. return Addons::find()
  254. ->where(['name' => OfficialEnum::AUTHORITY, 'status' => StatusEnum::ENABLED])
  255. ->one();
  256. }
  257. /**
  258. * 触发更新缓存
  259. *
  260. * @param $name
  261. */
  262. public function updateCacheByName($name)
  263. {
  264. $this->findCacheAllNames(true);
  265. $this->findCacheByName($name, true);
  266. }
  267. }
粤ICP备19079148号